# Export Logs to Elasticsearch Source: https://docs.golf.dev/gateway/guides/audit-trail/export-to-elasticsearch Configure Elasticsearch audit log export for search and analytics. Configure Elasticsearch export to send audit logs to your Elasticsearch cluster for search, analytics, and long-term retention. ## Prerequisites * Golf Gateway deployed and running * Elasticsearch cluster (self-hosted or Elastic Cloud) * API key with write permissions - See [Create API keys](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html) in Elastic documentation Required API key privileges on `golf-gateway-*` indices: * `write` * `create_index` * `manage` ## Configure Elasticsearch export **Self-Hosted Elasticsearch:** ```yaml theme={null} exporters: elasticsearch: - name: primary-es enabled: true url: https://elasticsearch.example.com:9200 api_key: ${ELASTICSEARCH_API_KEY} index_prefix: golf-gateway ``` **Elastic Cloud:** ```yaml theme={null} exporters: elasticsearch: - name: cloud-es enabled: true cloud_id: ${ELASTIC_CLOUD_ID} api_key: ${ELASTIC_CLOUD_API_KEY} index_prefix: golf-gateway ``` 1. Go to **Connections** > **Add Connection** 2. Select **Elasticsearch** 3. Choose deployment type (Self-hosted or Elastic Cloud) 4. Enter connection details 5. Click **Test Connection** 6. Click **Save** ## Index naming Golf Gateway creates daily indices with the pattern: ``` {index_prefix}-YYYY.MM.DD ``` Example: `golf-gateway-2026.01.08` ## Index mapping The index mapping is created automatically with these key fields: | Field | Type | Description | | ----------------------- | ------- | ---------------------------------------- | | `timestamp` | date | Event timestamp | | `event_type` | keyword | Event type (request, response, security) | | `session_id` | keyword | MCP session identifier | | `security.blocked` | boolean | Whether request was blocked | | `security.was_scrubbed` | boolean | Whether PII was masked in the payload | | `mcp_method` | keyword | MCP method called | | `mcp_tool_name` | keyword | Tool name (for tool calls) | ## Verify export is working 1. Check gateway health: ```bash theme={null} curl http://localhost:8080/health # Should show export adapter status ``` 2. Generate some traffic, then search in Kibana: ``` GET golf-gateway-*/_search { "query": { "match_all": {} }, "size": 10 } ``` ## Troubleshooting * **Connection refused**: Verify Elasticsearch URL and network connectivity * **401 Unauthorized**: Check API key has correct permissions * **Index not created**: Verify API key has `create_index` privilege ## Related guides * [Export Logs to OpenTelemetry](/gateway/guides/audit-trail/export-to-opentelemetry) - OTLP export * [Set Up Metrics and Monitoring](/gateway/guides/operations/setup-monitoring) - Health monitoring # Export Logs to OpenTelemetry Source: https://docs.golf.dev/gateway/guides/audit-trail/export-to-opentelemetry Configure OTLP export for logs, metrics, and traces. Configure OpenTelemetry (OTLP) export to send audit logs, metrics, and traces to any OTLP-compatible backend. ## Prerequisites * Golf Gateway deployed and running * OpenTelemetry Collector or compatible backend (Grafana, Datadog, etc.) ## Configure OTLP export **gRPC (Recommended):** ```yaml theme={null} exporters: otel: - name: primary-otel enabled: true endpoint: otel-collector.example.com:4317 protocol: grpc service_name: golf-gateway export_logs: true export_metrics: true ``` **HTTP/Protobuf:** ```yaml theme={null} exporters: otel: - name: primary-otel enabled: true endpoint: https://otlp.example.com/v1/logs protocol: http/protobuf service_name: golf-gateway headers: Authorization: "Bearer ${OTEL_TOKEN}" ``` 1. Go to **Connections** > **Add Connection** 2. Select **OpenTelemetry** 3. Enter OTLP endpoint 4. Select protocol (gRPC or HTTP) 5. Configure which signals to export (logs, metrics, traces) 6. Click **Test Connection** 7. Click **Save** ## Export signals | Signal | YAML Field | Description | | ------- | ---------------------- | ------------------- | | Logs | `export_logs: true` | Audit log entries | | Metrics | `export_metrics: true` | Performance metrics | | Traces | `export_traces: true` | Request traces | ## Resource attributes Golf Gateway includes these resource attributes: | Attribute | Value | | ------------------- | ------------------------- | | `service.name` | From `service_name` field | | `service.version` | Gateway version | | `golf.gateway.id` | Gateway ID (if managed) | | `golf.gateway.name` | Gateway name | Add custom attributes: ```yaml theme={null} exporters: otel: - name: primary-otel # ... other fields resource_attributes: environment: production region: us-west-2 ``` ## Semantic conventions Log records follow OpenTelemetry semantic conventions: | Attribute | Description | | --------------------- | ------------ | | `event.name` | Event type | | `http.request.method` | HTTP method | | `url.path` | Request path | | `mcp.method` | MCP method | | `mcp.tool.name` | Tool name | ## Common OTLP backends Consult your observability platform's documentation for OTLP endpoint configuration: | Platform | Documentation | | ------------- | -------------------------------------------------------------------------------------------------------------- | | Grafana Cloud | [Send data via OTLP](https://grafana.com/docs/grafana-cloud/send-data/otlp/) | | Datadog | [OpenTelemetry in Datadog](https://docs.datadoghq.com/opentelemetry/) | | New Relic | [OpenTelemetry setup](https://docs.newrelic.com/docs/opentelemetry/get-started/opentelemetry-set-up-your-app/) | | Honeycomb | [OpenTelemetry overview](https://docs.honeycomb.io/send-data/opentelemetry/) | ## Verify export is working 1. Check health endpoint includes OTEL status 2. View logs in your OTLP backend 3. Search for `service.name: golf-gateway` ## Troubleshooting * **Connection timeout**: Verify endpoint is reachable * **401/403 errors**: Check authentication headers * **No data appearing**: Verify `export_logs: true` in your YAML config ## Related guides * [Export Logs to Elasticsearch](/gateway/guides/audit-trail/export-to-elasticsearch) - ES export * [Export Logs to Azure Sentinel](/gateway/guides/audit-trail/export-to-sentinel) - Sentinel export # Export Logs to Azure Sentinel Source: https://docs.golf.dev/gateway/guides/audit-trail/export-to-sentinel Configure Microsoft Sentinel DCR-based log ingestion. Configure Azure Sentinel export to send audit logs to Microsoft Sentinel using Data Collection Rules (DCR) for security monitoring and analytics. ## Prerequisites Before configuring Golf Gateway, set up these Azure resources: 1. **Data Collection Endpoint (DCE)** - See [Create a DCE](https://learn.microsoft.com/en-us/azure/azure-monitor/essentials/data-collection-endpoint-overview) in Microsoft documentation. 2. **Data Collection Rule (DCR)** with custom table `GolfGateway_CL` - See [Create a DCR](https://learn.microsoft.com/en-us/azure/azure-monitor/essentials/data-collection-rule-overview) in Microsoft documentation. 3. **Service Principal** with `Monitoring Metrics Publisher` role on the DCR - See [Create service principal](https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal) in Microsoft documentation. You'll need: * DCE Logs Ingestion endpoint URL * DCR Immutable ID * DCR Stream Name (default: `Custom-GolfGateway_CL`) * Service Principal: Tenant ID, Client ID, Client Secret ## Configure Sentinel export ```yaml theme={null} exporters: sentinel: - name: azure-sentinel enabled: true dcr_immutable_id: ${SENTINEL_DCR_ID} dcr_endpoint: https://my-dce.eastus.ingest.monitor.azure.com dcr_stream_name: Custom-GolfGateway_CL tenant_id: ${AZURE_TENANT_ID} client_id: ${AZURE_CLIENT_ID} client_secret: ${AZURE_CLIENT_SECRET} ``` 1. Go to **Connections** > **Add Connection** 2. Select **Microsoft Sentinel** 3. Enter DCR immutable ID and endpoint 4. Enter service principal credentials 5. Click **Test Connection** 6. Click **Save** ## Verify export is working 1. Generate some gateway traffic 2. Wait for batch timeout (default: 10 seconds) 3. Query the `GolfGateway_CL` table in Log Analytics See [Query logs in Azure Monitor](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-query-overview) for query syntax. ## Troubleshooting * **401 Unauthorized**: Verify service principal credentials * **403 Forbidden**: Check service principal has role on DCR * **404 Not Found**: Verify DCR immutable ID is correct ## Related guides * [Export Logs to Elasticsearch](/gateway/guides/audit-trail/export-to-elasticsearch) - ES export * [Export Logs to OpenTelemetry](/gateway/guides/audit-trail/export-to-opentelemetry) - OTLP export # Deploy in Centralized Mode Source: https://docs.golf.dev/gateway/guides/getting-started/deploy-control-plane Connect your gateway to the Golf Gateway Control Plane for centralized management. Connect your gateway to the Golf Gateway Control Plane to receive centralized configuration, security policies, and monitoring. ## Prerequisites * Golf Gateway account (sign up at [app.golf.dev](https://app.golf.dev)) * Docker and Docker Compose installed on your deployment machine * Network access to Control Plane URL Golf Gateway **requires Redis** for session management, rate limiting, replay protection, and authentication caching. The Docker Compose examples below include Redis automatically. ## Create a gateway in Control Plane 1. Log in to the Admin Portal 2. Navigate to **Gateway Manager** > **Add Gateway** 3. Enter a gateway name (e.g., `production-gateway-1`) 4. Click **Create** 5. **Copy the API key** - you won't see it again Save your gateway API key securely. It cannot be retrieved after creation. ## Deploy the gateway ```yaml theme={null} version: "3.8" services: redis: image: redis:7-alpine ports: - "6379:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 5s retries: 3 golf-gateway: image: ghcr.io/golf-mcp/golf-gateway-backend:latest ports: - "8080:8080" environment: GOLF_GATEWAY_ID: GOLF_GATEWAY_API_KEY: GOLF_GATEWAY_CONTROL_PLANE_URL: https://api.golf.dev GOLF_CACHE_REDIS_URL: redis://redis:6379/0 depends_on: redis: condition: service_healthy ``` ```yaml theme={null} # Redis is required - use a Redis service or managed Redis # Example using a simple Redis deployment: --- apiVersion: apps/v1 kind: Deployment metadata: name: redis spec: replicas: 1 selector: matchLabels: app: redis template: metadata: labels: app: redis spec: containers: - name: redis image: redis:7-alpine ports: - containerPort: 6379 --- apiVersion: v1 kind: Service metadata: name: redis spec: selector: app: redis ports: - port: 6379 --- apiVersion: apps/v1 kind: Deployment metadata: name: golf-gateway spec: replicas: 1 selector: matchLabels: app: golf-gateway template: metadata: labels: app: golf-gateway spec: containers: - name: golf-gateway image: ghcr.io/golf-mcp/golf-gateway-backend:latest ports: - containerPort: 8080 env: - name: GOLF_GATEWAY_ID valueFrom: secretKeyRef: name: golf-gateway-secrets key: gateway-id - name: GOLF_GATEWAY_API_KEY valueFrom: secretKeyRef: name: golf-gateway-secrets key: api-key - name: GOLF_GATEWAY_CONTROL_PLANE_URL value: "https://api.golf.dev" - name: GOLF_CACHE_REDIS_URL value: "redis://redis:6379/0" ``` For production, use a managed Redis service (AWS ElastiCache, Azure Cache for Redis, or Redis Enterprise) for high availability. Golf Gateway offers additional Helm charts for different deployment scenarios. Contact the Golf team for more details on available charts and enterprise deployment options. ## Verify the connection 1. Check gateway status: ```bash theme={null} curl http://localhost:8080/health ``` Expected response: `{"status": "healthy", ...}` 2. In the Admin Portal, verify gateway status shows **Active** ## Configuration received from Control Plane When connected, your gateway automatically receives: * MCP server configurations * Security policies (rate limiting, RBAC) * Export destinations (Elasticsearch, OTEL, Sentinel) * Encryption keys for credential storage Gateways send heartbeats every 30 seconds. Configuration changes in Control Plane are applied within one heartbeat interval. ## Related guides * [Deploy in Distributed Mode](/gateway/guides/getting-started/deploy-hybrid-mode) - Local server definitions with central policies # Deploy in Distributed Mode Source: https://docs.golf.dev/gateway/guides/getting-started/deploy-hybrid-mode Use local server definitions with centralized policy management from Control Plane. Deploy in Distributed mode to maintain local control over MCP server definitions while receiving security policies and organization settings from the Control Plane. ## Prerequisites * Golf Gateway account with gateway created * Docker or Kubernetes environment (with Redis available) * Local YAML configuration file Golf Gateway **requires Redis** for session management, rate limiting, replay protection, and authentication caching. Ensure Redis is available before deploying. ## When to use Distributed Mode Distributed mode is ideal when you need: * Local control over MCP server definitions * Central management of security policies * Gradual migration to full Centralized mode management ## Create the configuration file Create `golf-gateway.yaml`. The `control_plane` section activates Distributed mode — the gateway reads servers from this YAML file while fetching organization policies from the Control Plane. ```yaml theme={null} version: "1.0" # Control Plane connection (activates distributed mode) control_plane: api_key: ${GOLF_GATEWAY_API_KEY} gateway_id: ${GOLF_GATEWAY_ID} servers: - name: github-mcp url: http://localhost:3001 description: "GitHub MCP Server" server_type: third_party rbac_enabled: true allowed_groups: - developers - devops - name: slack-mcp url: http://localhost:3002 description: "Slack MCP Server" server_type: inhouse allowed_groups: - all-users ``` **Treat your configuration file as a secret.** The YAML file may contain sensitive information such as server URLs, group names, and policy configurations. Never commit it to version control unencrypted. For production deployments, store your configuration in: * **AWS Secrets Manager** with External Secrets Operator * **HashiCorp Vault** with External Secrets Operator * **Kubernetes Secrets** (not ConfigMaps) ## Deploy with YAML config ```yaml theme={null} version: "3.8" services: redis: image: redis:7-alpine ports: - "6379:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 5s retries: 3 golf-gateway: image: ghcr.io/golf-mcp/golf-gateway-backend:latest ports: - "8080:8080" volumes: - ./golf-gateway.yaml:/app/golf-gateway.yaml:ro environment: # These env vars are referenced by ${} in the YAML file GOLF_GATEWAY_API_KEY: GOLF_GATEWAY_ID: GOLF_GATEWAY_EXTERNAL_URL: https://gateway.example.com GOLF_CACHE_REDIS_URL: redis://redis:6379/0 depends_on: redis: condition: service_healthy ``` ```yaml theme={null} apiVersion: v1 kind: Secret metadata: name: golf-gateway-config type: Opaque stringData: golf-gateway.yaml: | version: "1.0" control_plane: api_key: ${GOLF_GATEWAY_API_KEY} gateway_id: ${GOLF_GATEWAY_ID} servers: - name: github-mcp url: http://github-mcp-service:3001 rbac_enabled: true allowed_groups: - developers --- apiVersion: apps/v1 kind: Deployment metadata: name: golf-gateway spec: template: spec: containers: - name: golf-gateway env: - name: GOLF_GATEWAY_EXTERNAL_URL value: "https://gateway.example.com" - name: GOLF_CACHE_REDIS_URL value: "redis://redis:6379/0" volumeMounts: - name: config mountPath: /app/golf-gateway.yaml subPath: golf-gateway.yaml readOnly: true volumes: - name: config secret: secretName: golf-gateway-config ``` For production, use External Secrets Operator to sync from AWS Secrets Manager or HashiCorp Vault. Golf Gateway offers additional Helm charts for different deployment scenarios. Contact the Golf team for more details on available charts and enterprise deployment options. ## What comes from where | Configuration | Centralized | Distributed | | ------------------------ | ------------- | ------------- | | MCP server definitions | Control Plane | YAML file | | Server-level RBAC | Control Plane | YAML file | | Gateway-level policy | Control Plane | YAML file | | Security engine settings | Control Plane | YAML file | | Exporters | Control Plane | YAML file | | Org-wide policies | Control Plane | Control Plane | ## Verify Distributed mode 1. Check health endpoint: ```bash theme={null} curl http://localhost:8080/health ``` 2. Verify servers synced to Control Plane: * In Admin Portal, go to **MCP Servers** * Your YAML-defined servers appear with a **YAML** badge Changes to the YAML file are detected automatically. The gateway reloads configuration without restart. ## Related guides * [Deploy in Centralized Mode](/gateway/guides/getting-started/deploy-control-plane) - Full Centralized mode management * [YAML Configuration Schema](/gateway/reference/yaml-schema) - Complete YAML reference # Configure Identity Providers Source: https://docs.golf.dev/gateway/guides/identity-providers/configure-idp Set up Auth0, Microsoft Entra ID, or Descope for MCP client authentication Configure your identity provider to authenticate users accessing in-house MCP servers through Golf Gateway. Golf Gateway supports Auth0, Microsoft Entra ID (Azure AD), and Descope. ## When IdP Configuration is Required The IdP configuration in the **Connections** page is required when you have **in-house MCP servers** where you control the identity provider. In this scenario: 1. Users authenticate with your IdP and receive a JWT token 2. MCP clients present this token to Golf Gateway 3. Gateway validates the token using your IdP's JWKS endpoint 4. Gateway extracts user identity for RBAC and audit logging For **third-party MCP servers** that have their own OAuth authorization, users authenticate through Golf Gateway's Authorization Server, which proxies the OAuth flow between the MCP client and the upstream server. The IdP configuration in Connections is not used in this flow. ## Prerequisites Create a Single Page Application or Regular Web Application in Auth0. **Required:** * Domain (e.g., `your-tenant.auth0.com`) * JWKS endpoint URL (e.g., `https://your-tenant.auth0.com/.well-known/jwks.json`) **For Capability Discovery (Optional):** * Machine-to-Machine Application * Client ID and Client Secret for the M2M app Register an application in Microsoft Entra ID. **Required:** * Directory (tenant) ID **For Capability Discovery (Optional):** * App registration with appropriate permissions * Client secret for the app registration Gather your Descope credentials from the Descope Console. **Required:** * Project ID **For Capability Discovery (Optional):** * Inbound App credentials ## When Capability Discovery Credentials Are Needed Capability discovery credentials (M2M tokens) enable the gateway to fetch MCP server capabilities autonomously. These are **optional** but required in specific scenarios: When you enable automatic capability refresh for an MCP server, the gateway periodically connects to discover tools, prompts, and resources. Since no user is present during these background jobs, M2M credentials authenticate the gateway as a service account. When `capability_versioning_enabled` is set on a server, the gateway tracks changes to capabilities over time. New or modified tools are flagged for approval before becoming available. M2M credentials enable the gateway to discover these changes automatically. For advanced RBAC that uses tool annotations (read-only, destructive, etc.), the gateway needs capability schemas to enforce policies. M2M credentials allow the gateway to fetch and cache these schemas for runtime access control decisions. **You don't need capability discovery credentials if:** * You only use manual, user-initiated capability discovery * You use simple server-level RBAC without capability granularity * You don't need scheduled refresh ## Configure via Control Plane 1. Navigate to **Connections** in the sidebar 2. In the **Identity Providers** section, click **Add identity provider** 3. Select **Auth0** 4. Configure the following sections: **User Identity Extraction (Required)** These fields are required to validate JWT tokens from your MCP clients. | Field | Description | Example | | ------------- | ----------------------------------- | ----------------------------------------------------- | | Display name | Friendly name for this IdP | `Production Auth0` | | JWKS endpoint | Auth0 JWKS URL for token validation | `https://your-tenant.auth0.com/.well-known/jwks.json` | **Token Audience Validation (Optional)** Configure audience validation to ensure tokens are intended for your API. | Field | Description | Example | | --------------- | ----------------------------- | ------------------------- | | API identifiers | List of valid audience values | `https://api.example.com` | API identifiers must match the `aud` claim in your JWT tokens. Add multiple identifiers if your tokens may have different audiences. **Capability Discovery (Optional)** These M2M credentials allow the gateway to discover MCP server capabilities on behalf of users. | Field | Description | Example | | ------------- | ----------------------------- | ------------------ | | Client ID | M2M application Client ID | `abc123...` | | Client secret | M2M application Client Secret | `***` | | Scopes | OAuth scopes | `openid` (default) | 5. Click **Save** 1. Navigate to **Connections** in the sidebar 2. In the **Identity Providers** section, click **Add identity provider** 3. Select **Microsoft Entra ID** 4. Configure the following sections: **User Identity Extraction (Required)** These fields are required to validate JWT tokens from your MCP clients. | Field | Description | Example | | ------------ | -------------------------- | -------------------------------------- | | Display name | Friendly name for this IdP | `Corporate Entra ID` | | Tenant ID | Azure AD tenant ID (UUID) | `12345678-1234-1234-1234-123456789012` | **Token Audience Validation (Optional)** Configure audience validation to ensure tokens are intended for your API. | Field | Description | Example | | --------------- | ----------------------------- | ------------------- | | API identifiers | List of valid audience values | `api://your-app-id` | **Capability Discovery (Optional)** These credentials allow the gateway to discover MCP server capabilities on behalf of users. | Field | Description | Example | | ------------- | ------------------------------ | -------------------- | | Client ID | App registration Client ID | `abc123...` | | Client secret | App registration Client Secret | `***` | | Scopes | API scopes | `.default` (default) | 5. Click **Save** 1. Navigate to **Connections** in the sidebar 2. In the **Identity Providers** section, click **Add identity provider** 3. Select **Descope** 4. Configure the following sections: **User Identity Extraction (Required)** These fields are required to validate JWT tokens from your MCP clients. | Field | Description | Example | | ------------ | -------------------------- | -------------------- | | Display name | Friendly name for this IdP | `Descope Production` | | Project ID | Descope Project ID | `P2abc123...` | For Descope, the JWKS endpoint and issuer URL are automatically derived from your Project ID. **Token Audience Validation (Optional)** Configure audience validation to ensure tokens are intended for your API. | Field | Description | Example | | --------------- | ----------------------------- | ------------------------- | | API identifiers | List of valid audience values | `https://api.example.com` | **Capability Discovery (Optional)** These credentials allow the gateway to discover MCP server capabilities on behalf of users. | Field | Description | Example | | ------------- | ------------------------- | ------------------ | | Client ID | Inbound App Client ID | `abc123...` | | Client secret | Inbound App Client Secret | `***` | | Scopes | OAuth scopes | `openid` (default) | 5. Click **Save** ## Configure via YAML (Distributed Mode) ```yaml theme={null} identity_providers: - name: auth0 type: auth0 issuer: https://YOUR_TENANT.auth0.com/ jwks_uri: https://YOUR_TENANT.auth0.com/.well-known/jwks.json api_identifiers: - https://your-api.example.com # Optional: M2M credentials for capability discovery client_id: ${AUTH0_CLIENT_ID} client_secret: ${AUTH0_CLIENT_SECRET} ``` ```yaml theme={null} identity_providers: - name: entra-id type: microsoft-entra-id tenant_id: YOUR_TENANT_ID issuer: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 jwks_uri: https://login.microsoftonline.com/YOUR_TENANT_ID/discovery/v2.0/keys api_identifiers: - api://your-app-id # Optional: Credentials for capability discovery client_id: ${ENTRA_ID_CLIENT_ID} client_secret: ${ENTRA_ID_CLIENT_SECRET} ``` ```yaml theme={null} identity_providers: - name: descope type: descope project_id: ${DESCOPE_PROJECT_ID} # issuer and jwks_uri are auto-generated for Descope # Optional: Credentials for capability discovery client_id: ${DESCOPE_CLIENT_ID} client_secret: ${DESCOPE_CLIENT_SECRET} ``` ## Authentication Flows Golf Gateway supports two authentication scenarios depending on the MCP server type: ### In-House Servers (Direct IdP Validation) For MCP servers you own and control, users authenticate with your IdP: 1. User authenticates with your IdP (Auth0, Entra ID, Descope) 2. MCP client receives JWT token 3. Client presents token to Golf Gateway 4. Gateway validates token using IdP's JWKS endpoint (configured in Connections) 5. Gateway extracts user identity and applies RBAC policies 6. Request is forwarded to the in-house MCP server **This is when IdP configuration in Connections is required.** ### Third-Party Servers (Gateway Authorization Server) For third-party MCP servers with their own OAuth requirements, Golf Gateway acts as an OAuth 2.0 Authorization Server that proxies authentication between MCP clients and upstream servers: 1. MCP client discovers OAuth endpoints via the gateway 2. Gateway redirects user to authenticate with your platform SSO 3. After authentication, user separately authorizes with the third-party MCP server 4. Gateway stores the user's OAuth token for that server 5. On subsequent requests, gateway injects the stored token when proxying to the upstream server **IdP configuration in Connections is NOT used in this flow.** ## Linking IdP to MCP Servers After configuring an IdP, link it to your in-house MCP servers: 1. Go to **Connections** > **MCP Servers** 2. Create or edit an MCP server 3. Set **Server type** to **In-house** 4. Select your IdP from the **Identity provider** dropdown 5. Save The gateway will now validate tokens for that server using the selected IdP configuration. ## Troubleshooting ### Token validation fails * Verify JWKS endpoint is accessible from your gateway * Check that API identifiers match the `aud` claim in your tokens * Ensure the token hasn't expired ### User identity not extracted * Verify the JWT contains expected claims (sub, email, name) * Check gateway logs for token validation errors ### RBAC not working as expected * Verify group names in RBAC policies match JWT claims exactly (case-sensitive) * Check the 3-layer policy hierarchy (org → gateway → server) * Use audit logs to see which user identity was extracted ## Next Steps * [Set Up Server RBAC](/gateway/guides/security/setup-server-rbac) - Control server access based on user identity * [Set Up Capability RBAC](/gateway/guides/security/setup-capability-rbac) - Fine-grained tool permissions # SSO Connections Source: https://docs.golf.dev/gateway/guides/identity-providers/sso-connections Configure platform SSO and user management for your organization Golf provides flexible options for managing user access to your organization. You can use Golf's built-in user management or connect to your existing identity provider for enterprise SSO and automatic group synchronization. ## User Management Options ### Option 1: Golf User Management Use Golf's built-in user management to invite and manage users directly: 1. Navigate to **Settings** > **Users** 2. Click **Invite user** 3. Enter the user's email address 4. Select a role (Admin or Member) 5. Click **Send invitation** The user receives an email invitation and can join your organization after accepting. **Roles:** | Role | Permissions | | ------ | -------------------------------------------- | | Admin | Manage users, gateways, and all settings | | Member | View and use MCP servers from the dev portal | ### Option 2: Connect to Your Identity Provider For enterprise SSO, connect your organization to an external identity provider. This enables: * Single sign-on with your corporate credentials * Automatic user provisioning * Group synchronization for RBAC policies To configure SSO: 1. Navigate to **Settings** > **Organization** 2. Find the **SSO Configuration** section 3. Click **Configure SSO** to open the setup portal 4. Follow the guided setup to connect your identity provider Supported identity providers include SAML-based providers and OAuth/OIDC providers like Microsoft Entra ID, Okta, and Google Workspace. ## Identity and NameID Golf identifies and authorizes every SSO user by their **email address**. When a user authenticates, Golf reads the email claim from the SSO assertion and uses it as the canonical identity: it is the key for organization membership and for resolving the security groups that authorize access (whether groups come from Directory Sync or your identity provider's directory). ### Recommended NameID Configure your identity provider to send the user's **email address** as the SSO NameID. The value Golf receives as the email claim must exactly match the email recorded for that user in the directory that supplies their group membership (matching is case-insensitive). Golf does **not** authorize on `userPrincipalName` (UPN), object ID, or any alternate identifier — only the email claim is used for group resolution. ### Attribute mapping Golf consumes the standard SSO profile attribute mapping. All four attributes are **required**. Map each Golf attribute to the corresponding claim your identity provider emits. | Golf attribute | Microsoft Entra ID (SAML claim URI) | Okta | Google Workspace | | -------------- | -------------------------------------------------------------------- | --------------------- | --------------------- | | `idpId` | `http://schemas.microsoft.com/identity/claims/objectidentifier` | *Details coming soon* | *Details coming soon* | | `email` | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress` | *Details coming soon* | *Details coming soon* | | `firstName` | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname` | *Details coming soon* | *Details coming soon* | | `lastName` | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname` | *Details coming soon* | *Details coming soon* | For OIDC providers, the equivalent claims are `email` (→ `email`), `given_name` (→ `firstName`), `family_name` (→ `lastName`), and `sub` or `oid` (→ `idpId`). Authorization always keys on the resolved email regardless of protocol. ## Group Synchronization When connected to an identity provider, Golf Gateway can automatically sync user groups for use in RBAC policies. ### How Group Sync Works 1. Users authenticate via your identity provider 2. Gateway retrieves the user's group memberships 3. Groups are available for Server RBAC and Capability RBAC policies ### Configuring Group Sync Group sync configuration depends on your identity provider: When using Microsoft Entra ID for SSO, group synchronization is automatic via directory sync (SCIM). Groups are synced in real-time as changes occur in your directory. **Setup:** 1. Navigate to **Settings** > **Organization** 2. Click **Configure SSO** and complete the Entra ID setup 3. Enable directory sync in the setup portal 4. Select which groups to sync Groups appear automatically in RBAC policy dropdowns. For Auth0 or Descope, configure Management API credentials to enable group fetching: 1. Navigate to **Settings** > **Organization** 2. Find **Group Sync Configuration** 3. Enter your Management API credentials: * **Auth0**: M2M application Client ID and Secret * **Descope**: Management Key 4. Click **Save** The gateway fetches groups on-demand during user authentication. ### Using Groups in RBAC Once group sync is configured, use groups in your access policies: **Server RBAC:** * Set `allowed_groups` to restrict server access to specific groups * Set `denied_groups` to block specific groups from accessing a server **Capability RBAC:** * Assign groups to individual tools, prompts, or resources * Use annotation-based policies to apply group restrictions based on tool characteristics (read-only, destructive, etc.) See [Set Up Server RBAC](/gateway/guides/security/setup-server-rbac) and [Set Up Capability RBAC](/gateway/guides/security/setup-capability-rbac) for detailed configuration. ## Troubleshooting ### Users can't sign in with SSO * Verify SSO is correctly configured in **Settings** > **Organization** * Check that the user exists in your identity provider * Ensure the user's email domain matches your organization's verified domain ### Groups not appearing in RBAC policies * For Entra ID: Verify directory sync is enabled and the groups are selected for sync * For Auth0/Descope: Check that Management API credentials are correctly configured * Allow a few minutes for group changes to propagate ### User has wrong permissions * Verify the user's group memberships in your identity provider * Check that RBAC policies reference the correct group names (case-sensitive) * Review the policy hierarchy: organization → gateway → server ## Next Steps * [Configure Identity Provider](/gateway/guides/identity-providers/configure-idp) - Set up IdP for MCP client authentication * [Set Up Server RBAC](/gateway/guides/security/setup-server-rbac) - Control server access based on groups * [Set Up Capability RBAC](/gateway/guides/security/setup-capability-rbac) - Fine-grained tool permissions # Configure Rate Limiting Source: https://docs.golf.dev/gateway/guides/operations/configure-rate-limiting Throttle MCP traffic with per-user, per-server, and global rate limits to prevent abuse and protect upstreams. Golf Gateway rate limits MCP traffic using a Redis-backed sliding window. Limits are enforced in layers — per-user, per-server, and system-wide — so you can protect individual upstreams and the gateway as a whole from abuse or runaway clients. ## Prerequisites * Golf Gateway deployed and running * Redis configured ## How it works Each request is checked against the limits in order, from most specific to most general: 1. **Per-user** — requests per window for a single authenticated user. Anonymous requests fall back to a **per-IP** limit using the same threshold. 2. **Per-server** — requests per window for a single user against a specific MCP server. 3. **Global** — system-wide requests per window across all users. The first limit that is exceeded stops the request. Each layer uses the same sliding-window algorithm over the configured `window_seconds`. Rate limiting **fails open**: if Redis is unavailable, requests are allowed through rather than blocked, so a cache outage never takes down your gateway. ## Configure the per-user limit The per-user limit is the only limit configurable via environment variables or YAML. Set it with the `GOLF_RATE_LIMIT_` variables: ```bash theme={null} GOLF_RATE_LIMIT_ENABLED=true GOLF_RATE_LIMIT_REQUESTS_PER_MINUTE=1000 # per-user limit, range 1-5000 GOLF_RATE_LIMIT_WINDOW_SECONDS=60 # sliding window, range 10-300 ``` Or in YAML (Distributed mode), under the `security` section: ```yaml golf-gateway.yaml theme={null} security: rate_limiting: enabled: true requests_per_minute: 1000 window_seconds: 60 ``` | Setting | Env Variable | Default | Range | Description | | --------------------- | ------------------------------------- | ------- | ------ | ------------------------------------ | | `enabled` | `GOLF_RATE_LIMIT_ENABLED` | `true` | - | Enable rate limiting | | `requests_per_minute` | `GOLF_RATE_LIMIT_REQUESTS_PER_MINUTE` | `1000` | 1-5000 | Per-user (and per-IP fallback) limit | | `window_seconds` | `GOLF_RATE_LIMIT_WINDOW_SECONDS` | `60` | 10-300 | Sliding window duration | ## Global and per-server limits System-wide (**global**) and **per-server** limits are managed through the **Control Plane** in Centralized mode — they are not configurable via environment variables or YAML. Their defaults are: | Limit | Default | Configured via | | ---------- | ----------------- | ------------------------------- | | Per-user | `1000` req/window | Env var, YAML, or Control Plane | | Per-server | `500` req/window | Control Plane only | | Global | `1000` req/window | Control Plane only | All three limits share the same `window_seconds`. The window is always read from the environment and is not overridden by Control Plane configuration. ## Related guides * [Set Up Metrics and Monitoring](/gateway/guides/operations/setup-monitoring) - Monitor gateway health * [Set Up Alerting](/gateway/guides/operations/setup-alerting) - Alert on anomalies * [Environment Variables](/gateway/reference/environment-variables) - Full configuration reference * [YAML Config Schema](/gateway/reference/yaml-schema) - Distributed mode configuration # Set Up Metrics and Monitoring Source: https://docs.golf.dev/gateway/guides/operations/setup-monitoring Configure health endpoints and metrics collection for gateway monitoring. Configure health endpoints and metrics collection to monitor your Golf Gateway deployment and set up alerting. ## Prerequisites * Golf Gateway deployed and running * Monitoring system ## Health endpoints Golf Gateway exposes two health endpoints: ### `/health` - Liveness probe Returns component health status: ```bash theme={null} curl http://localhost:8080/health ``` Response: ```json theme={null} { "status": "healthy", "redis": "ok", "redis_circuit_breaker": "closed", "database": "ok", "upstreams": "3 configured", "http_client": "ok", "gateway_id": "abc-123", "gateway_name": "production-gateway" } ``` | Status Code | Meaning | | ----------- | -------------------------------- | | 200 | All components healthy | | 503 | One or more components unhealthy | ### `/readiness` - Readiness probe Returns whether gateway is ready to accept traffic: ```bash theme={null} curl http://localhost:8080/readiness ``` Response: ```json theme={null} { "status": "ready", "draining": false, "http_client": "initialized", "upstreams": "3 loaded", "redis_manager": "initialized" } ``` | Status Code | Meaning | | ----------- | ----------------------- | | 200 | Ready to accept traffic | | 503 | Not ready or draining | ## Kubernetes probes Configure probes in your deployment: ```yaml theme={null} apiVersion: apps/v1 kind: Deployment spec: template: spec: containers: - name: golf-gateway livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 3 readinessProbe: httpGet: path: /readiness port: 8080 initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 2 ``` ## Health status levels | Status | Meaning | | ----------- | -------------------------------- | | `HEALTHY` | All systems operational | | `DEGRADED` | Partial issues, still functional | | `UNHEALTHY` | Critical issues, exports blocked | ## Related guides * [Export Logs to OpenTelemetry](/gateway/guides/audit-trail/export-to-opentelemetry) - OTLP metrics * [Export Logs to Elasticsearch](/gateway/guides/audit-trail/export-to-elasticsearch) - Log analytics # Configure PII Scrubbing Source: https://docs.golf.dev/gateway/guides/security/configure-pii-scrubbing Set up data protection to automatically redact sensitive information from MCP responses. Configure PII scrubbing to automatically redact sensitive information from MCP responses before they're logged or returned to clients. ## Prerequisites * [Golf Control Plane account](https://app.golf.dev) with Admin role * MCP server registered in Control Plane * Golf Gateway deployed in [Distributed mode](/gateway/guides/getting-started/deploy-hybrid-mode) * Familiarity with the [YAML schema](/gateway/reference/yaml-schema) ## Understanding the 3-layer policy hierarchy PII scrubbing follows the same 3-layer hierarchy as other Golf Gateway policies: | Layer | Where Configured | Scope | | ---------------- | ----------------------------------- | --------------------------- | | **Organization** | Control Plane > Settings > Policies | All gateways & servers | | **Gateway** | Control Plane > Gateway > Policies | All servers on this gateway | | **Server** | Control Plane > Server > Policies | Single MCP server | **Policy Merge Rules:** * **Sensitive fields**: Combined from ALL layers (union) * **Whitelist fields**: Combined from ALL layers (union) * **Custom rules**: Combined from ALL layers (union) * **Custom entities**: Combined from ALL layers (union) * **Enabled flag**: True if ANY layer enables scrubbing Set organization-wide defaults for common PII types, then add server-specific rules for domain-specific data. ## Enable PII scrubbing **Organization defaults:** 1. Go to **Settings** > **Policies** 2. Find the **PII Protection** section 3. Enable **PII Scrubbing** 4. Configure default sensitive field names 5. Click **Save** **Gateway overrides:** 1. Go to **Gateways** > select a gateway > **Policies** 2. Find the **PII Protection** section 3. Add gateway-specific sensitive fields 4. Click **Save** **Server-level configuration:** 1. Go to **MCP Servers** > select a server 2. Open the **Policies** tab > **PII** 3. Enable **PII Protection** 4. Add custom sensitive field names 5. Click **Save** **Gateway-level defaults** (applies to all servers): ```yaml theme={null} gateway_policy: scrubbing: enabled: true sensitive_fields: - password - api_key - secret whitelist_fields: # Fields that should NEVER be scrubbed - connection_id - session_id - cursor - tool_name recognizers: - entity_type: EMAIL_ADDRESS enabled: true - entity_type: CREDIT_CARD enabled: true - entity_type: URL enabled: false # Disable URL scrubbing ``` **Server-level overrides** (merged on top of gateway defaults): ```yaml theme={null} servers: - name: my-server url: http://localhost:3001 security: enabled: true sensitive_fields: - api_key - password whitelist_fields: - report_id recognizers: - entity_type: EMAIL_ADDRESS enabled: true replacement: "[PII_EMAIL]" # Custom replacement for this server ``` ## Built-in PII detection Golf Gateway detects many entity types by default. Common examples include: | Entity Type | Example | | ---------------- | ------------------------------------------- | | `CREDIT_CARD` | 4111-1111-1111-1111 | | `EMAIL_ADDRESS` | [user@example.com](mailto:user@example.com) | | `PHONE_NUMBER` | (415) 555-1234 | | `US_SSN` | 123-45-6789 | | `IP_ADDRESS` | 192.168.1.1 | | `US_BANK_NUMBER` | 1234567890 | | `URL` | [https://example.com](https://example.com) | | `IBAN_CODE` | DE89370400440532013000 | Additional supported types include `PERSON`, `LOCATION`, `ORGANIZATION` (via GLiNER), `US_DRIVER_LICENSE`, `US_PASSPORT`, `JWT_TOKEN`, and more. ## Add custom scrubbing rules For patterns not covered by built-in detection, add custom rules: 1. Go to the appropriate level (Settings, Gateway, or Server > Policies) 2. Find the **PII Protection** section 3. Click **Add Custom Rule** 4. Enter the regex pattern and select the masking method 5. Click **Save** Add custom rules at the **gateway level** (applies to all servers) or **server level** (per-server overrides): ```yaml theme={null} # Gateway-level custom rules gateway_policy: scrubbing: enabled: true custom_rules: - pattern: "sk-[a-zA-Z0-9]+" # API keys method: mask # Server-level custom rules (merged with gateway rules) servers: - name: my-server url: http://localhost:3001 security: enabled: true custom_rules: - pattern: "LINEAR-[A-Z]+-[0-9]+" # Linear issue IDs method: mask - pattern: "TXN-\\d+" # Transaction IDs method: replace replacement: "[TXN_ID]" ``` **Masking methods:** | Method | Behavior | Example | | --------- | ----------------------------------------- | -------------------------------- | | `mask` | Replace with `[REDACTED]` | `sk-abc123` → `[REDACTED]` | | `hash` | Replace with SHA256 hash (first 16 chars) | `sk-abc123` → `a1b2c3d4e5f6g7h8` | | `remove` | Remove the value entirely | `sk-abc123` → \`\` | | `replace` | Replace with custom text | `sk-abc123` → `[API_KEY]` | ## Configure per-server scrubbing Different servers can have different scrubbing settings: Configure each server individually through **MCP Servers** > server > **Policies** > **PII**. ```yaml theme={null} servers: # Internal tools - minimal scrubbing - name: internal-tools url: http://localhost:3001 security: enabled: true sensitive_fields: [password] whitelist_fields: [file_path, tool_name] # External API - comprehensive scrubbing - name: external-api url: http://localhost:3002 security: enabled: true sensitive_fields: [api_key, bearer_token, secret, password] custom_rules: - pattern: "Bearer [a-zA-Z0-9\\-_]+" method: mask recognizers: - entity_type: EMAIL_ADDRESS enabled: true replacement: "[PII_EMAIL]" - entity_type: CREDIT_CARD enabled: true replacement: "[PII_CARD]" ``` ## Verify scrubbing is active 1. In Admin Portal, go to **Logs** 2. Select a session and find a request containing PII 3. In the security pipeline, look for the **PII Scrubbed** step 4. Verify sensitive data shows entity-specific placeholders like `[EMAIL]`, `[SSN]`, or `[MASKED]` ## Fields never scrubbed These fields are preserved for audit purposes and are never scrubbed regardless of configuration: * `connection_id`, `session_id`, `correlation_id` * `timestamp`, `event_type`, `method` * `user.email`, `user.sub` (for compliance) You can also configure additional fields to be excluded from scrubbing using `whitelist_fields` at the gateway or server level. This is useful for protecting operational data like file paths, tool names, or cursor tokens from accidental scrubbing. ## Troubleshooting * **PII not being detected**: Verify scrubbing is enabled at all policy levels (org, gateway, server) * **Custom pattern not matching**: Test your regex pattern - Golf Gateway uses Python regex syntax * **Too much data being scrubbed**: Check if multiple layers are adding overlapping rules ## Related guides * [Set Up Server RBAC](/gateway/guides/security/setup-server-rbac) - Access control * [Golf Gateway Overview](/gateway/overview/golf-gateway#pii-scrubbing-policy) - Policy engine architecture # Set Up Capability RBAC Source: https://docs.golf.dev/gateway/guides/security/setup-capability-rbac Configure fine-grained access control for individual tools, prompts, and resources. Configure capability RBAC to control access to individual tools, prompts, and resources within an MCP server. ## Prerequisites * [Golf Control Plane account](https://app.golf.dev) with Admin role * Server RBAC configured ([Set Up Server RBAC](/gateway/guides/security/setup-server-rbac)) * Groups synced from your identity provider * Golf Gateway deployed in [Distributed mode](/gateway/guides/getting-started/deploy-hybrid-mode) * Server RBAC configured in your YAML file * Familiarity with the [YAML schema](/gateway/reference/yaml-schema) ## How it works Capability RBAC extends server RBAC to control access to individual: * **Tools** - Functions the AI can call * **Prompts** - Prompt templates * **Resources** - Data sources ### 4-layer policy merge Capability RBAC uses a 4-layer policy merge to determine access: | Layer | Where Configured | Purpose | | ------------------- | ----------------------------------- | ------------------------------------- | | **1. Organization** | Control Plane > Settings > Policies | Base annotation defaults | | **2. Gateway** | Control Plane > Gateway > Policies | Override org defaults | | **3. Annotation** | From MCP server tool metadata | Selects which policy category applies | | **4. Capability** | Per-server capability overrides | Most specific per-tool rules | Each layer can only make access **more restrictive**, never less. The final access decision is the intersection of all layers. ### Tool annotations MCP servers provide annotations that describe each tool's behavior. Golf Gateway uses these to apply the appropriate access policy automatically: | Annotation | Meaning | Default Policy | | ----------------------- | ------------------------------------- | -------------------- | | `readOnlyHint: true` | Tool only reads data, no side effects | More permissive | | `destructiveHint: true` | Tool may delete or overwrite data | More restrictive | | Neither | Tool behavior is unspecified | Configurable default | With these organization defaults: ``` read_only.allowed_groups = ["all-users"] destructive.allowed_groups = ["admins"] unspecified.allowed_groups = ["developers", "admins"] ``` When a user invokes a tool: * `list_files` (readOnlyHint: true) → Allowed for all users * `delete_file` (destructiveHint: true) → Requires admin group * `send_message` (no annotations) → Requires developers or admins ## Enable capability RBAC 1. Go to **MCP Servers** > select a server 2. Navigate to the **Policies** tab > **Permissions** section 3. Click **Enabled** to turn on capability RBAC 4. Go to the **Capabilities** tab to view discovered tools, prompts, and resources 5. Use **Review Changes** to review and approve pending capabilities ```yaml theme={null} servers: - name: github-mcp url: http://localhost:3001 rbac_enabled: true allowed_groups: [developers] capability_rbac_enabled: true # Enable per-capability RBAC ``` ## Configure annotation-based defaults Set default access groups for each annotation category. These defaults apply to all capabilities that match the annotation. **Organization-level defaults:** 1. Go to **Settings** > **Policies** 2. Find the **Capability RBAC** section 3. Configure default groups for each category: * **Read-only tools** - Tools with `readOnlyHint: true` * **Destructive tools** - Tools with `destructiveHint: true` * **Unspecified tools** - Tools without annotations 4. Click **Save** **Gateway-level overrides:** 1. Go to **Gateways** > select a gateway > **Policies** 2. Find the **Capability RBAC** section 3. Override organization defaults as needed (can only be more restrictive) 4. Click **Save** Configure at the gateway level in `gateway_policy`: ```yaml theme={null} gateway_policy: capability_rbac: read_only: default_groups: [all-users] # Permissive for read-only destructive: default_groups: [admins] # Restrictive for destructive unspecified: default_groups: [developers, admins] ``` Organization-level annotation defaults are configured in the Control Plane UI, even when using Distributed mode. The `gateway_policy` in YAML provides gateway-level overrides. ## Configure per-capability overrides For specific tools that need different access than their annotation category, configure per-capability overrides: 1. Go to **MCP Servers** > select a server > **Capabilities** tab 2. Find the capability you want to restrict 3. Click the capability row to expand details 4. Click **Edit Permissions** 5. Enable **Custom Access** to override annotation defaults 6. Select allowed groups for this specific capability 7. Click **Save** Use `capability_overrides` on the server to set per-capability rules: ```yaml theme={null} servers: - name: github-mcp url: http://localhost:3001 capability_rbac_enabled: true capability_overrides: # Restrict delete operations to repo admins only - capability: "tools/delete_repo" rbac_enabled: true rbac_mode: allow allowed_groups: [repo-admins] # Allow all users to list repositories - capability: "tools/list_repos" rbac_enabled: true allowed_groups: [all-users] # Use wildcards for patterns - capability: "tools/delete_*" allowed_groups: [admins] ``` **Capability patterns:** * `tools/exact_name` - Match specific tool * `tools/prefix_*` - Match tools starting with prefix * `resources/*` - Match all resources * `prompts/category/*` - Match prompts in category ## Pending approval workflow When capability versioning is enabled, new or modified capabilities require admin approval before becoming active: 1. Gateway discovers new tool/prompt/resource during connection 2. Capability appears in the **Capabilities** tab with **New** or **Changed** badge 3. Click **Review Changes** to see all pending capabilities 4. Review the capability schema and intended behavior 5. Click **Approve All** or approve individual changes 6. Users can now access the approved capabilities To disable pending approval and auto-approve new capabilities: ```yaml theme={null} servers: - name: github-mcp capability_versioning_enabled: false # Auto-approve new capabilities ``` Disabling capability versioning means new tools are immediately available to users. Only disable this for trusted internal MCP servers. ## Complete example Here's a complete configuration showing all capability RBAC features: ```yaml theme={null} # Gateway-level annotation defaults gateway_policy: capability_rbac: read_only: default_groups: [all-users] destructive: default_groups: [senior-developers, admins] unspecified: default_groups: [developers, admins] servers: - name: github-mcp url: http://localhost:3001 rbac_enabled: true allowed_groups: [engineering] idp: auth0 # Enable capability RBAC capability_rbac_enabled: true # Per-capability overrides capability_overrides: # Only repo admins can delete repositories - capability: "tools/delete_repo" allowed_groups: [repo-admins] # Only security team can manage secrets - capability: "tools/*_secret" allowed_groups: [security-team] # Require approval for new capabilities capability_versioning_enabled: true ``` ## Verify capability RBAC 1. Connect your MCP client (Claude Desktop, Cursor, etc.) to the gateway as an authorized user 2. Ask the AI to list available tools - verify restricted tools are filtered from the response 3. Try to use a restricted tool (e.g., `delete_repo`) - verify you receive an access denied error 4. Check audit log in Admin Portal > **Audit Logs** for the blocked request ## Troubleshooting * **Tool not appearing**: Check if capability versioning is enabled and the tool is pending approval * **Access denied with correct groups**: Verify all layers (org, gateway, capability override) - access is the intersection of all * **Wildcard not matching**: Patterns use prefix matching with `*`, ensure your pattern is correct ## Related guides * [Set Up Server RBAC](/gateway/guides/security/setup-server-rbac) - Server-level access control * [Golf Gateway Overview](/gateway/overview/golf-gateway#capability-rbac) - Policy engine architecture # Set Up Server RBAC Source: https://docs.golf.dev/gateway/guides/security/setup-server-rbac Control which users can access which MCP servers based on group membership. Configure server-level role-based access control (RBAC) to restrict which users can access which MCP servers based on their group membership. ## Prerequisites * [Golf Control Plane account](https://app.golf.dev) with Admin role * Identity provider configured with group sync enabled ([Configure SSO](/gateway/guides/identity-providers/sso-connections)) * MCP server registered in Control Plane * Golf Gateway deployed in [Distributed mode](/gateway/guides/getting-started/deploy-hybrid-mode) * Identity provider configured in your YAML file * Familiarity with the [YAML schema](/gateway/reference/yaml-schema) ## How it works Server RBAC controls access to entire MCP servers based on user group membership. Users must be in an allowed group (or not in a denied group) to access the server. ## Understanding the 3-layer policy hierarchy Golf Gateway uses a 3-layer policy hierarchy where policies at each level can override or inherit from the level above: | Layer | Where Configured | Scope | Inheritance | | ---------------- | ----------------------------------- | --------------------------- | ----------------------- | | **Organization** | Control Plane > Settings > Policies | All gateways & servers | Base defaults | | **Gateway** | Control Plane > Gateway > Policies | All servers on this gateway | NULL = inherit from org | | **Server** | Control Plane > Server > Policies | Single MCP server | Most specific | **Policy Merge Rules ("Most Restrictive Wins"):** * **Boolean flags** (rbac\_enabled, scrubbing\_enabled): OR logic - if ANY layer enables, it's enabled * **Allowed groups**: INTERSECTION - user must be in allowed groups at ALL levels * **Denied groups**: UNION - user denied if in denied groups at ANY level Start with permissive organization defaults and add restrictions at the gateway or server level as needed. ## RBAC modes | Mode | Behavior | | ------------------- | ---------------------------------------------------- | | **Allow** (default) | Only users in `allowed_groups` can access | | **Deny** | Users in `denied_groups` are blocked, others allowed | When both modes are configured across layers, deny lists are checked first and take precedence. ## Configure server RBAC **Organization defaults:** 1. Go to **Settings** > **Policies** 2. Find the **Server Access** section 3. Enable RBAC and set default mode (Allow/Deny) 4. Add default allowed or denied groups 5. Click **Save** **Gateway overrides:** 1. Go to **Gateways** > select a gateway > **Policies** 2. Override organization defaults as needed 3. Click **Save** **Server-level configuration:** 1. Go to **MCP Servers** > select a server 2. Open the **Policies** tab 3. Enable the **Access** policy 4. Select mode: **Allowlist** or **Denylist** 5. Add groups from your identity provider 6. Click **Save** **Gateway-level defaults** (applies to all servers): ```yaml theme={null} gateway_policy: server_rbac: rbac_enabled: true rbac_mode: allow allowed_groups: [gateway-users] denied_groups: [] ``` **Server-level configuration:** Allow mode (users must be in at least one allowed group): ```yaml theme={null} servers: - name: admin-tools url: http://localhost:3001 rbac_enabled: true rbac_mode: allow allowed_groups: - platform-admins - devops ``` Deny mode (users must NOT be in any denied group): ```yaml theme={null} servers: - name: general-tools url: http://localhost:3002 rbac_enabled: true rbac_mode: deny denied_groups: - contractors - external-users ``` ## Configure multiple servers Different servers can have different access requirements: Configure each server individually through **MCP Servers** > server > **Policies**. ```yaml theme={null} servers: # Admin-only tools - name: admin-dashboard url: http://localhost:3001 rbac_enabled: true rbac_mode: allow allowed_groups: [admins] # Developer tools - name: dev-tools url: http://localhost:3002 rbac_enabled: true rbac_mode: allow allowed_groups: [developers, admins] # Public tools (no RBAC) - name: public-docs url: http://localhost:3003 rbac_enabled: false ``` ## Verify RBAC is working 1. Authenticate as a user NOT in the allowed groups 2. Connect your MCP client (Claude Desktop, Cursor, etc.) to the gateway 3. Try to use any tool from the protected server 4. Verify you receive an access denied error 5. Check audit log in Admin Portal > **Audit Logs** ## Troubleshooting * **Access denied unexpectedly**: Verify the user's identity provider groups match at least one of the allowed groups configured in the server's Access policy * **Groups not appearing**: Verify management API credentials for your identity provider * **Inherited policy blocking**: Check organization and gateway policies - the most restrictive setting wins ## Related guides * [Set Up Capability RBAC](/gateway/guides/security/setup-capability-rbac) - Fine-grained tool access * [Configure SSO](/gateway/guides/identity-providers/sso-connections) - Identity provider setup # Golf Control Plane Source: https://docs.golf.dev/gateway/overview/control-plane Single pane of glass for configuring policies, viewing audit logs, and managing access across your organization The Control Plane is where governance happens. It's the single pane of glass for configuring policies, viewing audit logs, and managing access across your entire organization—regardless of how many gateways you deploy. ## The Questions You Need to Answer Without centralized governance, your security team can't answer basic questions: * Which AI agents are employees using? * Which internal systems do those agents connect to? * What data flows through those connections? * Is there an approval process for new integrations? * Can you revoke access across all agents at once? * Do you control which tools are available to which roles? * Can you produce an audit log of all agent activity? * Are you confident PII isn't flowing to model providers? * Do your DLP policies cover agent connections? * If credentials were compromised, what did the attacker access? * What did this agent do between 2pm and 4pm last Tuesday? * Could a departing employee exfiltrate data through agent integrations? The Control Plane lets you answer all of these. ## Architecture Control Plane architecture: Admin/Dev Portal connects to API, which manages Database and Config Distribution to multiple Gateways ## Hosting Options The Control Plane can be deployed wherever your organization requires: **Managed by Golf** * Hosted and operated by Golf * Zero infrastructure management * Automatic updates and scaling * SOC 2 Type II compliant **Full on-premises deployment** * Complete data residency control * Deploy to your cloud * Kubernetes deployment via Helm charts **Requirements:** * PostgreSQL database * Redis cache * Kubernetes cluster Both options provide identical functionality. Your gateways connect to the Control Plane URL you configure—whether that's Golf Cloud or your own infrastructure. ## Organizations Organizations are the top-level tenant boundary in Golf. Each organization has its own: * Gateways * MCP Servers * Identity Providers * Exporters * Members and RBAC groups ### Member Roles | Role | Capabilities | | ------ | ------------------------------------------------ | | Owner | Full access, cannot be removed from organization | | Admin | Full access, can manage members and invitations | | Member | Dev Portal access only | ## Gateway Manager The Gateway Manager handles the lifecycle of all gateway instances. ### Gateway Lifecycle | Status | Description | | ------------ | -------------------------------------------- | | Pending | Created but not yet activated | | Active | Running and sending heartbeats | | Draining | Graceful shutdown, rejecting new connections | | Stopped | Intentionally deactivated | | Unresponsive | Missed 3+ heartbeats (90s timeout) | ### Creating a Gateway 1. Navigate to Gateways > Create Gateway 2. Enter gateway name and external URL 3. Save the API key immediately (only shown once) 4. Configure gateway with ID, API key, and Control Plane URL Save your API key immediately when creating a gateway. You won't be able to view it again. ## MCP Server Management ### Server Types | Type | When to Use | | ----------- | ---------------------------------------------------------- | | In-house | Servers managed by your organization | | Third party | External servers requiring OAuth or API key authentication | ### Third-Party Server Authentication When MCP servers require authentication to external services (GitHub, Notion, Slack), Golf Gateway manages per-user credentials. **How It Works:** 1. User clicks "Authorize" on a third-party server card in the Dev Portal 2. Gateway initiates OAuth flow with the external service 3. User grants permissions 4. Gateway stores encrypted access + refresh tokens 5. On each MCP request, gateway injects the user's token **Credential Security:** * Tokens are encrypted at rest and at transport * Per-user scoping: each user has their own credentials * Automatic token refresh when access tokens expire * Credentials never sent to client, only injected by gateway **Supported Auth Types:** | Type | Description | | ------- | ---------------------------------------------- | | OAuth | Full OAuth 2.0 flow, supports token refresh | | API Key | User provides static API key, stored encrypted | | None | Server doesn't require authentication | ## For Developers (Dev Portal) The Dev Portal is where you discover available MCP servers and get connection instructions for your AI tools. ### Finding and Connecting to Servers 1. Sign in to Golf Control Plane 2. Browse available servers on the **MCP Servers** page 3. Click a server to view its URL and capabilities 4. Copy the gateway URL to your MCP client configuration You only see servers you have access to based on your group memberships. Contact your administrator if you need access to additional servers. ### Troubleshooting * **Server not appearing**: Verify the gateway URL is correct, check that the server is enabled, restart your MCP client * **Authentication errors**: Re-authorize the server through the OAuth flow or re-enter your API key * **Connection timeouts**: Check network connectivity to the gateway, verify gateway status is green * **Can't see expected servers**: Server may need admin approval or be in a different organization ## For Administrators (Admin Portal) The Admin Portal provides comprehensive tools to manage MCP servers, gateways, security policies, and monitor system activity. ### Configuration Sections | Section | Purpose | | ----------- | ------------------------------------------------------------------------ | | MCP Servers | Add, configure, and manage MCP servers with RBAC and capability controls | | Gateways | Deploy, monitor, and manage gateway instances | | Connections | Configure data exporters and identity providers | | Settings | Organization configuration, members, and default policies | ### Monitoring The Admin Portal provides three monitoring views: **Analytics**: View usage metrics and system health including request volume, token consumption, error rates, and latency metrics. **Security Incidents**: Investigate blocked requests, RBAC denials, replay attempts, rate-limit events, and PII redaction events. **Audit Logs**: Search and investigate audit logs with graph view for MCP message flow visualization and timeline view for chronological events. ## Governance Capabilities ### Integration Inventory See every MCP server your organization uses: * Which gateways it's assigned to * Which groups can access it * What capabilities it exposes ### Access Control Enforce least privilege by default: * Server RBAC (which teams can access which servers) * Capability RBAC (which roles can use which tools) * Approval workflows for new integrations ### Audit & Visibility Log every request across all gateways: you can see WHO did WHAT and WHERE. Search and filter. Export to your SIEM. Answer auditor questions. ### Policy Enforcement Golf Gateway uses a 3-layer policy hierarchy for flexible governance: | Layer | Where Configured | Scope | | ---------------- | ----------------------------------- | --------------------------- | | **Organization** | Control Plane > Settings > Policies | All gateways & servers | | **Gateway** | Control Plane > Gateway > Policies | All servers on this gateway | | **Server** | Control Plane > Server > Policies | Single MCP server | ## Related * [Gateway](/gateway/overview/golf-gateway) - The runtime component that routes traffic * [Deploy in Centralized Mode](/gateway/guides/getting-started/deploy-control-plane) - Setup guide # Golf Gateway Source: https://docs.golf.dev/gateway/overview/golf-gateway Enterprise security gateway for MCP servers Golf is the **enterprise MCP platform**. Get centralized control and visibility over all your MCPs, enforce access policies, and integrate with your SIEM. * **Broker upstream credentials** - Agents authenticate once; Golf injects API keys and OAuth tokens for upstream MCP servers * **Enforce strict role-based access** - Control which agents can access which servers, tools, and resources * **Continuous governance through logging** - Every interaction is logged with tamper-proof audit trails * **Ringfence sensitive data** - Automatically redact PII to prevent leakage to model providers and downstream systems ## The Problem Traditional API gateways and WAFs were not built for MCP. They see HTTP and JSON, but they don't understand: * MCP methods, tools, resources, prompts, elicitation, sampling, and other protocol primitives * Multi-step agent flows and how tools are actually used * Authorization decisions that require MCP-aware context (tools, resources, and capabilities) Whether you've blocked AI agents entirely (but employees use them anyway on personal devices) or approved them (but now have fragmented control points across Claude, Cursor, ChatGPT, etc.) - you need a governance layer. ## What Golf Gateway Does Single control point regardless of which agent (Claude, Cursor, ChatGPT, Copilot) employees use. Full audit trail for every interaction. Export to your SIEM (Elasticsearch, Sentinel, OTLP). Centralized RBAC for non-human identities. One policy layer across all your agents and MCP servers. Redact PII automatically and enforce rate limits and replay protection. Golf Gateway is **protocol-aware**: it understands MCP semantics and uses that to protect your agents and backend systems. The gateway operates as a **transparent proxy**—neither MCP clients nor servers need modifications: ```mermaid theme={null} flowchart LR A["MCP Client"] --> B["MCP Server"] ``` Direct connection. No visibility. No control. ```mermaid theme={null} flowchart LR A["MCP Client"] --> B["Golf Gateway"] B --> C["MCP Server"] style B fill:#f97728,stroke:#ea580c,color:#ffffff ``` All traffic visible. All access controlled. All actions logged. To route through the gateway, configure your MCP client to connect to the gateway's URL instead of the MCP server directly: ```json theme={null} { "mcpServers": { "github": { "url": "https://gateway.company.com/github/mcp" } } } ``` ## Security Golf Gateway applies multiple security controls on every MCP request. ### Rate Limiting Protect against abuse with sliding-window rate limiting at three layers: | Layer | Scope | | -------------- | ----------------- | | **Per-User** | Individual user | | **Per-Server** | Single MCP server | | **Global** | Entire gateway | The most restrictive limit applies. ### Replay Protection Prevent session token theft and reuse: 1. When a session is first used, it's bound to the authenticated user 2. If the same session ID appears with a different user, it's flagged as replay 3. Replay attempts are blocked and logged ### Audit & Visibility Every request is logged with cryptographic integrity: * **HMAC-SHA256 hash chain** - Tamper-evident logging * **Sequence numbers** - Detect missing or reordered entries * **Rich metadata** - User, server, tool, latency, authorization result This gives you incident response capability and the audit trail compliance teams need. ## Policy Engine The Policy Engine is the centralized governance system that manages and enforces access control and data protection across Golf Gateway. It operates on a **3-layer hierarchy** where policies at each level can restrict (but never expand) permissions: ``` Organization → Gateway → Server/Capability ``` The Policy Engine manages four policy types: | Policy | Purpose | Hierarchy | | ------------------------- | ----------------------------------------------- | -------------------------- | | **Server RBAC** | Control which groups can access MCP servers | All 3 layers | | **Capability RBAC** | Control access to tools, prompts, and resources | All 3 layers + annotations | | **PII Scrubbing** | Detect and mask sensitive data | All 3 layers | | **Capability Versioning** | Require approval for capability changes | Server only | ### How Policies Merge Policies follow a **"most restrictive wins"** doctrine. As you move down the hierarchy, policies can only become more restrictive, never less: | Field | Merge Rule | Behavior | | --------------------------- | ------------ | --------------------------------------- | | Enabled flags | OR | True if ANY layer enables | | Allowed groups (allow mode) | Intersection | User must be in ALL layers' groups | | Denied groups (deny mode) | Union | Blocked if in ANY layer's deny list | | Sensitive fields | Union | All fields from all layers are scrubbed | | Custom rules & entities | Union | Combined from all layers | ``` Organization: allowed_groups = ["admins", "devs", "viewers"] Gateway: allowed_groups = ["admins", "devs"] Server: allowed_groups = ["admins"] Result: Only "admins" can access (intersection of all layers) ``` ### Server RBAC Server RBAC controls which user groups can connect to each MCP server. Configure at any layer to set defaults or restrictions: | Mode | Behavior | | ------------------- | ---------------------------------------------------- | | **Allow** (default) | Only users in `allowed_groups` can access | | **Deny** | Users in `denied_groups` are blocked, others allowed | When both modes are configured across layers, deny lists are checked first and take precedence. ### Capability RBAC Capability RBAC provides fine-grained access control for individual tools, prompts, and resources. It uses a **4-layer merge** that incorporates MCP tool annotations: Set default groups for each annotation category (read-only, destructive, unspecified) Override or restrict org defaults (merged via intersection) Tool annotations determine which policy category applies Per-tool group restrictions (intersected with policy) #### Tool Annotations Annotations are metadata hints that MCP servers provide about their tools. They're part of the [MCP specification](https://modelcontextprotocol.io/specification/2025-03-26/server/tools#annotations) and describe the nature of each tool's behavior—whether it only reads data, makes destructive changes, or falls somewhere in between. Golf Gateway discovers these annotations automatically when it connects to an MCP server and uses them to apply the appropriate access policy: | Annotation | Meaning | Policy Category | | ----------------------- | ----------------------------------------------------------- | --------------- | | `readOnlyHint: true` | Tool only reads data, no side effects | Read-only | | `destructiveHint: true` | Tool may perform destructive operations (delete, overwrite) | Destructive | | Neither annotation | Tool behavior is unspecified or mixed | Unspecified | You configure these defaults at the organization level: ``` read_only.allowed_groups = ["all-users"] destructive.allowed_groups = ["admins"] unspecified.allowed_groups = ["developers", "admins"] ``` When a user invokes a tool: * `list_files` (readOnlyHint: true) → Allowed for all users * `delete_file` (destructiveHint: true) → Requires admin group * `send_message` (no annotations) → Requires developers or admins This allows you to set broad policies like "all destructive tools require admin access" at the org level, while still allowing per-tool overrides at the capability level when needed. ### PII Scrubbing Policy PII scrubbing configuration follows the same 3-layer merge. At each layer you can configure: * **Sensitive fields**: Field names to always mask * **Pre-built recognizers**: Toggle built-in entity detection (21 types) * **Custom rules**: Regex patterns with mask/remove/hash/replace methods * **Custom entities**: AI-powered detection for custom data types All configurations are merged using union—if any layer adds a field or rule, it applies. ### Capability Versioning Unlike RBAC and scrubbing policies, versioning is configured **per-server only** and is not part of the 3-layer policy hierarchy. When enabled on a server, new or modified capabilities require admin approval before becoming active: 1. Gateway discovers new/changed capabilities during refresh 2. Changes are marked as "pending approval" 3. Capabilities are blocked until an admin approves them 4. All changes are recorded in the capability history for audit For step-by-step setup, see [Configure Server RBAC](/gateway/guides/security/setup-server-rbac), [Configure Capability RBAC](/gateway/guides/security/setup-capability-rbac), and [Configure PII Scrubbing](/gateway/guides/security/configure-pii-scrubbing). ## Authentication Golf Gateway implements a **proxy authentication model**: users authenticate to the gateway once, and the gateway manages credentials for upstream MCP servers. Authentication flow: MCP Client connects to Golf Gateway, which redirects to Identity Provider for SSO, then injects credentials for MCP Server requests **How It Works** 1. **User authenticates to Gateway** via your identity provider (Auth0, Entra ID, Descope) 2. **Gateway issues a session token** (HS256 JWT) for subsequent requests 3. **Gateway injects upstream credentials** for each MCP server the user accesses 4. **Users never see upstream credentials** - they're managed entirely by the gateway **Credential Types** Golf supports two types of upstream credentials: For MCP servers that accept static API keys: 1. User provides their API key once in the Dev Portal 2. Key is encrypted and stored securely 3. Gateway injects the key into requests automatically **Use case**: Internal APIs, services with static authentication For third-party services requiring OAuth: 1. User authorizes the service once via OAuth flow 2. Gateway stores encrypted access + refresh tokens 3. Gateway automatically refreshes expired tokens **Use case**: GitHub, Slack, Notion, other OAuth-enabled services **Security Benefits** Golf Gateway's credential management provides several important security benefits. First, credential isolation ensures that users never see or handle raw API keys or OAuth tokens; all sensitive credentials are stored and managed by the gateway itself. The system also supports automatic refresh of OAuth tokens, so users maintain access without manual intervention or interruptions. Centralized revocation gives administrators the ability to disable access instantly by removing credentials from the gateway, eliminating the risk of lingering permissions. Additionally, Golf Gateway maintains a complete audit trail—every time credentials are used, that activity is securely logged, enabling compliance, oversight, and incident response. ## Configuration Modes Golf Gateway supports two primary configuration modes that determine where configuration and policies are loaded from: **All configuration from Control Plane** ```mermaid theme={null} flowchart LR A["Control Plane"] --> B["Gateway"] style A fill:#6366f1,stroke:#4f46e5,color:#ffffff ``` * MCP servers, policies, and exporters defined in Control Plane UI * Gateway fetches configuration bundles on startup and heartbeat * Hot reload on configuration changes (no restart needed) **Best for**: Teams wanting full UI-based management, multi-gateway deployments **Local YAML + Control Plane policies** ```mermaid theme={null} flowchart LR A["YAML File"] --> B["Gateway"] C["Control Plane"] -.->|"policies only"| B style C fill:#6366f1,stroke:#4f46e5,color:#ffffff ``` * MCP servers and gateway config defined in local YAML file * Organization-wide policies fetched from Control Plane * YAML changes hot-reloaded via file watcher **Best for**: GitOps workflows, infrastructure-as-code teams **What Comes From Where** | Configuration | Centralized | Distributed | | ------------------------ | ------------- | ------------- | | MCP server definitions | Control Plane | YAML file | | Server-level RBAC | Control Plane | YAML file | | Gateway-level policy | Control Plane | YAML file | | Security engine settings | Control Plane | YAML file | | Exporters | Control Plane | YAML file | | Org-wide policies | Control Plane | Control Plane | These modes are not mutually exclusive. You can run some gateways in centralized mode and others in distributed mode within the same organization. All gateways share organization-wide policies from the Control Plane. **Mode Detection** Golf Gateway automatically detects which mode to use: 1. **YAML file with `control_plane` section** → Distributed mode 2. **Control Plane environment variables only (no YAML)** → Centralized mode No explicit mode configuration is required. **Hot Reload** Both modes support hot reload without gateway restart: | Mode | Trigger | Latency | | ----------- | ---------------------------------- | ------------ | | Centralized | Config version change on heartbeat | \~30 seconds | | Distributed | File system change detected | \~1 second | For deployment guides, see [Deploy Centralized](/gateway/guides/getting-started/deploy-control-plane) and [Deploy Distributed](/gateway/guides/getting-started/deploy-hybrid-mode). ## When to Deploy Multiple Gateways Just as organizations deploy multiple API gateways for different domains and audiences, Golf Gateway supports multi-gateway architectures. Each gateway can serve a specific purpose while reporting to the same Control Plane for unified visibility. **Separate gateways for different business domains** Each team or department gets its own gateway with tailored policies: * **Engineering Gateway** - Company-built agents accessing internal APIs * **HR Gateway** - Employee-facing agents with strict PII controls * **Finance Gateway** - Agents accessing financial systems with enhanced audit requirements **Benefits**: Teams manage their own configurations. Domain-specific security policies. Clear ownership boundaries. **Different gateways for different user populations** Separate internal users from external access: * **Internal Gateway** - Employees accessing all approved MCP servers * **Partner Gateway** - External partners with limited server access * **Public Gateway** - Public-facing MCP servers with strict rate limits **Benefits**: Different trust levels. Tailored rate limits. Isolated blast radius if one gateway is compromised. **Isolated gateways per deployment environment** Standard environment separation: * **Development Gateway** - Relaxed policies for testing * **Staging Gateway** - Production-like policies for validation * **Production Gateway** - Full security controls enabled **Benefits**: Safe testing without affecting production. Gradual policy rollout. Environment-specific MCP servers. ### Benefits | Benefit | Description | | -------------------------- | ---------------------------------------------------------------------- | | **Blast Radius Isolation** | Issues in one gateway don't affect others | | **Tailored Policies** | Different security requirements per domain or audience | | **Independent Scaling** | Scale high-traffic gateways without over-provisioning others | | **Team Autonomy** | Teams can manage their own gateway configuration (in Distributed mode) | | **Unified Visibility** | Single Control Plane for cross-gateway analytics and audit | Start with a single gateway and add more as your requirements grow. The Control Plane makes it easy to manage any number of gateways from one place. ## Deployment Golf Gateway is available as a Docker image for Kubernetes and container deployments. ### Image | Variant | Tag | Size | Use Case | | ------- | -------- | -------- | -------------------------- | | Default | `v1.0.0` | \~1.5 GB | Production gateway runtime | ### Hardware Requirements **Recommended**: * 4 vCPU * 8 GB RAM **AWS example**: `c7a.xlarge` ### Required Dependencies Golf Gateway requires the following external services: | Service | Purpose | Notes | | --------- | ------------------------------------------------------------------------ | -------------------------------- | | **Redis** | Session management, rate limiting, replay protection, auth token caching | Required. Redis 7.x recommended. | Redis is essential for Golf Gateway operation. ### Container Orchestration Golf can provide example Helm charts for Kubernetes deployments. Contact the Golf team for access to deployment templates and configuration examples tailored to your infrastructure. For production deployment configuration, see [Environment Variables Reference](/gateway/reference/environment-variables) and [YAML Schema](/gateway/reference/yaml-schema). # Overview Source: https://docs.golf.dev/gateway/overview/index Govern how AI tools connect to your systems Your engineers are using Claude, Cursor, ChatGPT, and Copilot. Each tool connects to GitHub, Slack, and your internal systems. **You have zero visibility into what's connected to what.** Your security team can't answer basic questions: * Which AI tools are connected to our GitHub? * Who approved those connections? * What data flowed through them last month? * Is PII being sent to model providers? Each AI tool maintains its own integration settings. Five tools means five separate control points, five places to audit, five different permission models. **The control plane is fragmented.** ## The Governance Gap Whether you've blocked AI tools entirely or approved them across teams, you're facing the same problem: Security said no. Too much risk, no visibility, no way to control what connects to what. **The problem**: Your employees are using these tools anyway—on personal devices, personal accounts, outside your network. You don't see it, you can't audit it, and you have zero control over what data flows through. The block didn't reduce risk—it just eliminated your visibility. Meanwhile, your competitors are shipping faster. You said yes to Claude, Cursor, Copilot, ChatGPT, or others. Maybe through official procurement, maybe through a team-level decision, maybe it just happened. **The problem**: These tools are now connecting to your systems—GitHub, Slack, Jira, internal APIs. Each one is a separate authentication flow, separate permissions model, separate audit trail (if there's an audit trail at all). You enabled AI. You're also flying blind. Both paths lead to the same place: **you need a governance layer**. ## What's At Risk These aren't theoretical risks. They're patterns we see repeatedly across enterprises adopting AI tools. Without clear policies, employees connect whatever they find. Someone configures their AI tool to connect to Salesforce. They set it up. It works. They tell their team. Now six people are using an integration that security has never reviewed, IT doesn't know exists, and nobody is monitoring. This is shadow IT, but faster—an employee can connect an AI tool to sensitive systems in five minutes. No ticket, no approval, no audit trail. **How Golf helps**: All connections route through the gateway. You see every integration, every user, every request. An engineer wants to connect their coding assistant to a tool. They find a third-party integration—maybe it has a few hundred stars on GitHub. They download it and run it locally. No security review. No code audit. No verification this is an official integration. And because it's running locally, there's no authentication layer, no access controls, no audit logs. Whoever runs it gets full access to whatever it connects to. **How Golf helps**: Classify and approve integrations. Only approved integrations route through your gateway. You approve an integration today. It looks fine. Next week, the maintainer pushes an update. New capabilities added. Behavior changed. Maybe intentionally malicious, maybe just careless. Your AI tools are now running different code than what you reviewed. There's no versioning enforcement. No change detection. No alert when an integration you depend on modifies its capabilities. **How Golf helps**: Capability versioning detects when integrations change. New capabilities require re-approval. When someone asks Cursor to "summarize this customer file," that data goes to model providers. No inspection, no DLP. If that file contains social security numbers, credit card data, or health records—it's now sitting on a third-party server. For fintechs, healthcare companies, and any regulated industry, this can be a compliance violation. **How Golf helps**: PII scrubbing detects and masks sensitive data before it reaches model providers. When an incident happens, you need to answer: What data was accessed? Which systems were queried? Who initiated the request? What was returned? With fragmented AI tool integrations, you can't answer any of this. There are no logs. There's no central record of what data flowed through which tool to which system. When auditors ask how you govern AI access to sensitive systems, "we don't track that" is not an acceptable answer. **How Golf helps**: Every request logged with cryptographic integrity. Who, what, when, where—all searchable. SIEM-ready (Splunk, Datadog, Sentinel). ## What is Golf? Golf is the single governance layer for all AI tool integrations. It deploys in your environment and sits between your AI tools and your systems—one control point for authentication, permissions, data inspection, and audit logging, regardless of which AI tool an employee uses. Golf Platform connecting AI Agent Ecosystem to MCP Server Ecosystem Register and govern every MCP server your organization exposes to AI tools Role-based permissions via your existing IAM. Least privilege by default. Detect and redact PII before it reaches model providers Every request logged. SIEM-ready (Splunk, Datadog, Sentinel). ## System Architecture Golf provides centralized governance for AI tools connecting to enterprise systems. The architecture has three main layers: ### Platform Overview Golf Gateway architecture: AI Tools connect through Golf Gateway to Integrations, with Control Plane managing configuration and Your IDP/SIEM for auth and logging ### Component Responsibilities | Component | Location | Responsibilities | | --------------------- | ------------------------- | ------------------------------------------------------------------- | | **Control Plane** | Golf Cloud or Self-Hosted | Policy management, integration registration, monitoring, Dev Portal | | **Gateway Runtime** | Your Infrastructure | Security pipeline, audit logging, credential injection | | **Identity Provider** | Your IdP | User authentication, SSO, group membership | | **AI Tools** | Developer Workstations | Claude Desktop, Cursor, Copilot, ChatGPT | | **Integrations** | Your Network or SaaS | GitHub, Slack, Jira, internal tools | ### Deployment Options **Control Plane hosted by Golf.** Zero infrastructure management. Live in under a week. Golf Cloud deployment: Gateway in your VPC connects to Golf Cloud control plane * Gateway connects to `api.golf.dev` * Configuration managed via Admin Portal * Audit logs exportable to your SIEM * Your data never leaves your infrastructure **Full on-premises deployment.** Complete data residency control. Self-hosted deployment: Gateway and Control Plane both in your VPC with PostgreSQL * PostgreSQL + Redis required * Kubernetes deployment via Helm * See [Deploy Self-Hosted](/gateway/guides/getting-started/deploy-control-plane) for setup ## I Am A... Find your starting point based on your role. **Goal**: Understand what Golf is and try it out Understand the value proposition and capabilities Deploy your first gateway in 20 minutes **Goal**: Connect AI tools to integrations through Golf You're using AI tools like Claude, Cursor, or Copilot and need to connect them to your organization's systems through Golf Gateway. Discover available integrations and get connection instructions **Goal**: Configure policies and ensure compliance You're responsible for governing AI tool integrations, managing access control, and ensuring compliance. Manage integrations, policies, and view security incidents Set up identity provider integration Control who can access which integrations Fine-grained access per tool, prompt, and resource **Goal**: Deploy and operate Golf Gateway in production You're responsible for deploying, scaling, and maintaining Golf Gateway infrastructure. Connect to Control Plane for centralized management GitOps workflow with local YAML configuration All configuration options Configuration for distributed mode ## Next Steps [Learn what Golf Gateway does and how it works](/gateway/overview/golf-gateway) [Deploy and verify step-by-step](/gateway/overview/quickstart) [Task-oriented how-to guides](/gateway/guides/getting-started/deploy-control-plane) # Quick Start Source: https://docs.golf.dev/gateway/overview/quickstart Deploy Golf Gateway and start protecting MCP traffic in 20 minutes This guide walks you through deploying and verifying Golf Gateway connected to your Control Plane. By the end, you'll have a working gateway that securely routes MCP traffic between your client and server. ## What you'll learn * How Golf Gateway sits between MCP clients and servers * How to create a gateway in the Golf Control Plane * How to deploy the gateway with Docker * How to verify traffic is flowing through the gateway ## Before You Begin Before starting, make sure you have: * Docker and Docker Compose (optional) installed * An MCP client (Claude Desktop, Cursor, or similar) * Access to your organization's Golf Control Plane * 20 minutes Navigate to your organization's Golf Control Plane and log in with your credentials. Enterprise customers receive their Control Plane URL and credentials during onboarding. If you don't have access yet, contact your organization's administrator. **Checkpoint**: You can see your organization's Control Plane after logging in. From the Control Plane, create a new gateway: 1. Click **Add Gateway** in the top navigation 2. Enter a name for your gateway (e.g., `my-first-gateway`) 3. Select your deployment region 4. Click **Create Gateway** After creation, the Control Plane displays your gateway's credentials: * **Gateway ID**: A unique identifier for your gateway * **API Key**: The secret key used to authenticate the gateway Copy and save your API key now. It is only shown once and cannot be retrieved later. **Checkpoint**: Your gateway appears in the Control Plane with a **Pending** status. Create a `docker-compose.yml` file with the following content: ```yaml title="docker-compose.yml" theme={null} version: "3.8" services: redis: image: redis:7-alpine ports: - "6379:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 5s retries: 3 golf-gateway: image: ghcr.io/golf-mcp/golf-gateway-backend:latest ports: - "8080:8080" environment: GOLF_GATEWAY_ID: GOLF_GATEWAY_API_KEY: GOLF_GATEWAY_CONTROL_PLANE_URL: https://api.golf.dev GOLF_CACHE_REDIS_URL: redis://redis:6379/0 depends_on: redis: condition: service_healthy ``` Replace `` and `` with the values from the previous step. Start the gateway: ```bash title="Terminal" theme={null} docker compose up -d ``` Verify the gateway is healthy: ```bash title="Terminal" theme={null} curl http://localhost:8080/health ``` Expected response: ```json theme={null} {"status": "healthy", "redis": "ok", "redis_circuit_breaker": "closed", "database": "ok", "upstreams": "1 configured", "http_client": "ok"} ``` **Checkpoint**: The health check returns `healthy` and your gateway shows **Active** in the Golf Control Plane. Now configure an MCP server to route traffic through your gateway: 1. In the Control Plane, click **MCP Servers** in the sidebar 2. Click **Add Server** 3. Fill in the server details: * **Name**: A descriptive name (e.g., "Demo Server") * **URL**: The MCP server endpoint (e.g., `https://demo.mcp.run/sse` for testing) * **Description**: Optional description of what the server provides 4. Select which gateway should route to this server 5. Select the **Server Type**: * **In-House**: Your organization's MCP servers * **Third Party**: External vendor MCP servers 6. Click **Save** **Checkpoint**: The server appears in your servers list. The Control Plane generates client-specific connection instructions for you: 1. Navigate to the server you just added 2. Click **Connection Instructions** 3. Select your MCP client (Claude Desktop, Cursor, Windsurf, etc.) 4. Copy the generated configuration 5. Add it to your client's configuration file 6. Restart your MCP client **Checkpoint**: After restarting your client, tools from the MCP server appear in your client's available tools. Now test that traffic flows through your gateway with security analysis: 1. In your MCP client, use one of the tools from the connected server 2. Return to the Control Plane 3. Navigate to **Audit Logs** in the sidebar 4. Find your recent session You'll see: * The request and response details * Authorization and RBAC results * User and session information * Timing and performance data **Checkpoint**: You can see your request in the logs with authorization and scrubbing metadata attached. ## Next Steps Now that you have a working gateway, learn how to enhance its security: Mask sensitive data in logs automatically Control who can access which servers Send logs to your SIEM for compliance Add OAuth/OIDC authentication For a deeper understanding of the concepts: * **[Control Plane](/gateway/overview/control-plane)** - Centralized management and configuration * **[Golf Gateway](/gateway/overview/golf-gateway)** - How the gateway processes traffic # Audit Log Schema Source: https://docs.golf.dev/gateway/reference/audit-log-schema Complete reference for the audit log entry structure and field definitions # Audit Log Schema Golf Gateway generates structured audit logs for all MCP traffic, authentication events, and security analysis. This reference documents the complete schema used for audit log entries. ## Quick Reference | Category | Key Fields | Purpose | | ------------------ | ------------------------------------------------------- | ------------------------------------------------ | | **Core** | `timestamp`, `event_type`, `component` | Event identification and timing | | **Identity** | `session_id`, `gateway_id`, `organization_id` | Session and gateway tracking | | **User** | `user.sub`, `user.email`, `user.authenticated` | User identity (privacy-compliant) | | **Authentication** | `authentication.result`, `authentication.provider_type` | Auth method and result | | **Security** | `security.blocked`, `security.was_scrubbed` | Access control, rate limiting, and PII scrubbing | | **MCP Protocol** | `mcp_method`, `mcp_tool_name`, `mcp_*_payload` | MCP JSON-RPC details | | **Integrity** | `sequence`, `prev_hash`, `integrity_hash` | Tamper-proof hash chain | | **Internal** | `message`, `correlation`, `metadata` | Internal processing (not exported) | *** ## Schema Overview ```json theme={null} { "timestamp": "2024-01-15T10:30:45.123456+00:00", "event_type": "mcp_request", "component": "mcp_parser", "session_id": "sess_abc123def456", "gateway_id": "550e8400-e29b-41d4-a716-446655440000", "gateway_name": "production-gateway", "organization_id": "org_xyz789", "client_info": { "name": "claude-desktop", "version": "1.2.3" }, "authentication": { "method": "oauth2", "result": "success", "completed_at": 1705315845123, "provider_type": "auth0", "provider_name": "Production Auth0", "authorization_result": "granted", "scopes": ["read:mcp", "write:mcp"], "granted_at": 1705315845123, "user_id": "auth0|abc123", "email": "a1b2c3d4e5f6g7h8", "session_created": true, "session_type": "authenticated" }, "security": { "analyzed": true, "blocked": false, "was_scrubbed": false, "entities_redacted": 0, "fields_masked": 0 }, "request": { "method": "POST", "path": "/finance-tools/mcp", "size_bytes": 256, "headers": {} }, "upstream": { "host": "mcp-server.internal", "port": 3001, "url": "http://mcp-server.internal:3001", "name": "finance-tools" }, "user": { "sub": "auth0|abc123", "email": "a1b2c3d4e5f6g7h8", "authenticated": true, "anonymous": false }, "mcp_method": "tools/call", "mcp_tool_name": "get_account_balance", "mcp_request_payload": "{\n \"jsonrpc\": \"2.0\",\n \"method\": \"tools/call\",\n \"params\": {\n \"name\": \"get_account_balance\",\n \"arguments\": {\"account_id\": \"12345\"}\n },\n \"id\": 1\n}", "mcp_request_tokens": 45, "has_error": false, "sequence": 12345, "prev_hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", "integrity_hash": "d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5" } ``` Each audit log entry is a JSON object. The sections below document each field category in detail. ```json theme={null} { "timestamp": "2024-01-15T10:30:45.123456+00:00", "event_type": "mcp_request", "component": "mcp_parser", "session_id": "sess_abc123", "gateway_id": "550e8400-e29b-41d4-a716-446655440000", "gateway_name": "production-gateway", "organization_id": "org_xyz789", "client_info": { ... }, "authentication": { ... }, "security": { ... }, "request": { ... }, "upstream": { ... }, "user": { ... }, "mcp_method": "tools/call", "mcp_tool_name": "get_weather", "mcp_request_payload": "{ ... }", "mcp_request_tokens": 150, "sequence": 12345, "prev_hash": "a1b2c3...", "integrity_hash": "d4e5f6..." } ``` *** ## Core Fields These fields are present on every audit log entry. | Field | Type | Description | | ------------ | ------ | --------------------------------------------------------------------------- | | `timestamp` | string | ISO 8601 timestamp with timezone (e.g., `2024-01-15T10:30:45.123456+00:00`) | | `event_type` | string | Type of audit event (see [Event Types](#event-types)) | | `component` | string | System component that generated the event | ### Event Types | Value | Description | | -------------------------- | --------------------------------------- | | `mcp_request` | Standard MCP JSON-RPC request | | `mcp_response` | Standard MCP JSON-RPC response | | `mcp_sampling_request` | Sampling/createMessage request | | `mcp_sampling_response` | Sampling/createMessage response | | `mcp_elicitation_request` | Server-initiated elicitation request | | `mcp_elicitation_response` | Elicitation response from client | | `mcp_notification` | MCP notification (no response expected) | | `authentication` | Authentication event | | `security` | Security analysis event | ### Component Values | Value | Description | | ------------ | -------------------------------------- | | `mcp_parser` | MCP message parsing | | `auth` | Authentication and authorization | | `security` | Security and policy enforcement events | *** ## Session and Identity | Field | Type | Description | | ----------------- | -------------- | -------------------------------------------- | | `session_id` | string \| null | MCP protocol session identifier | | `gateway_id` | string \| null | Gateway UUID (multi-gateway deployments) | | `gateway_name` | string \| null | Human-readable gateway name | | `organization_id` | string \| null | Organization UUID (multi-tenant deployments) | *** ## Integrity Fields These fields provide tamper-proof audit logging through cryptographic hash chaining. | Field | Type | Description | | ---------------- | --------------- | ------------------------------------------ | | `sequence` | integer \| null | Monotonically increasing sequence number | | `prev_hash` | string \| null | HMAC-SHA256 hash of the previous log entry | | `integrity_hash` | string \| null | HMAC-SHA256 hash of the current entry | The integrity chain allows verification that no log entries have been modified or deleted. Configure the hash key with `GOLF_SECURITY_INTEGRITY_KEY`. *** ## Client Info Information about the MCP client, extracted from the `initialize` request. | Field | Type | Description | | --------------------- | ------ | -------------------------------------------------- | | `client_info.name` | string | MCP client name (e.g., "claude-desktop", "cursor") | | `client_info.version` | string | MCP client version | **Example:** ```json theme={null} { "client_info": { "name": "claude-desktop", "version": "1.2.3" } } ``` *** ## Authentication Authentication and authorization results. | Field | Type | Description | | ------------------------------------- | -------------- | ---------------------------------------------------------- | | `authentication.method` | string | Authentication method (default: `oauth2`) | | `authentication.result` | string | `success`, `failed`, or `anonymous` | | `authentication.completed_at` | integer | Unix timestamp in milliseconds | | `authentication.provider_type` | string \| null | IDP type: `auth0`, `okta`, `microsoft-entra-id`, `descope` | | `authentication.provider_name` | string \| null | Human-readable provider name | | `authentication.authorization_result` | string | `granted`, `denied`, or `anonymous` | | `authentication.scopes` | array | Granted OAuth scopes | | `authentication.granted_at` | integer | Unix timestamp in milliseconds | | `authentication.user_id` | string \| null | User subject identifier | | `authentication.email` | string \| null | User email (hashed before export) | | `authentication.name` | string \| null | User display name (removed before export) | | `authentication.session_created` | boolean | Whether a new session was created | | `authentication.session_type` | string | `authenticated` or `anonymous` | **Example:** ```json theme={null} { "authentication": { "method": "oauth2", "result": "success", "completed_at": 1705315845123, "provider_type": "auth0", "provider_name": "Production Auth0", "authorization_result": "granted", "scopes": ["read:mcp", "write:mcp"], "granted_at": 1705315845123, "user_id": "auth0|abc123", "email": "a1b2c3d4e5f6g7h8", "session_created": true, "session_type": "authenticated" } } ``` *** ## Security Access control, rate limiting, replay protection, and PII scrubbing results. | Field | Type | Description | | ----------------------------- | --------------- | -------------------------------------------- | | `security.analyzed` | boolean | Whether security processing was performed | | `security.skipped_reason` | string \| null | Reason processing was skipped | | `security.blocked` | boolean | Whether the request/response was blocked | | `security.detection_method` | string \| null | `rate_limit`, `replay_protection`, or `rbac` | | `security.content_size_bytes` | integer \| null | Size of processed content in bytes | ### PII Scrubbing Fields | Field | Type | Description | | ----------------------------- | ------------- | --------------------------------------- | | `security.was_scrubbed` | boolean | Whether content was scrubbed for PII | | `security.entities_redacted` | integer | Total PII entities redacted | | `security.fields_masked` | integer | Total fields masked by name | | `security.entities_by_type` | object | Breakdown of redacted entities by type | | `security.redacted_paths` | array | JSON paths where entities were redacted | | `security.masked_field_names` | array | Field names that were masked | | `security.custom_rules_fired` | array | Custom regex rules that matched | | `security.scrub_duration_ms` | float \| null | Scrubbing duration in milliseconds | **Example (request blocked by rate limit):** ```json theme={null} { "security": { "analyzed": true, "blocked": true, "detection_method": "rate_limit", "content_size_bytes": 1024 } } ``` **Example (PII scrubbed):** ```json theme={null} { "security": { "analyzed": true, "blocked": false, "was_scrubbed": true, "entities_redacted": 3, "fields_masked": 1, "entities_by_type": { "email": 2, "phone": 1 }, "redacted_paths": ["result.content[0].text"], "masked_field_names": ["ssn"], "scrub_duration_ms": 12.5 } } ``` *** ## Request Request context information. | Field | Type | Description | | -------------------- | --------------- | -------------------------------------------------- | | `request.method` | string \| null | HTTP or MCP method | | `request.path` | string \| null | Request path or resource | | `request.size_bytes` | integer \| null | Request size in bytes | | `request.headers` | object | Request headers (sanitized to empty before export) | *** ## Upstream Information about the upstream MCP server. | Field | Type | Description | | --------------- | -------------- | ------------------------------ | | `upstream.host` | string | Upstream server hostname | | `upstream.port` | integer | Upstream server port (1-65535) | | `upstream.url` | string \| null | Original URL for display | | `upstream.name` | string \| null | Upstream server name | **Example:** ```json theme={null} { "upstream": { "host": "mcp-server.internal", "port": 3001, "name": "finance-tools" } } ``` *** ## User User identity information. | Field | Type | Description | | -------------------- | -------------- | --------------------------------------------------- | | `user.sub` | string \| null | User subject identifier | | `user.email` | string \| null | User email (hashed to 16-char SHA256 before export) | | `user.name` | string \| null | User display name (removed before export) | | `user.authenticated` | boolean | Whether user is authenticated | | `user.anonymous` | boolean | Whether user is anonymous | For privacy compliance, `user.email` is hashed and `user.name` is removed before export to external systems. *** ## MCP Protocol Fields ### Extracted Fields These fields are extracted from MCP messages for efficient querying and aggregation. | Field | Type | Description | | ------------------ | -------------- | ---------------------------------------------------------- | | `mcp_method` | string \| null | MCP JSON-RPC method (e.g., `tools/call`, `resources/read`) | | `mcp_tool_name` | string \| null | Tool name from `tools/call` or `tools/list` | | `mcp_resource_uri` | string \| null | Resource URI from `resources/read` or `resources/list` | | `mcp_prompt_name` | string \| null | Prompt name from `prompts/get` or `prompts/list` | ### Raw Payloads | Field | Type | Description | | ---------------------- | -------------- | --------------------------------- | | `mcp_request_payload` | string \| null | Raw MCP request JSON (formatted) | | `mcp_response_payload` | string \| null | Raw MCP response JSON (formatted) | ### Token Estimates | Field | Type | Description | | --------------------- | --------------- | ---------------------------------- | | `mcp_request_tokens` | integer \| null | Estimated token count for request | | `mcp_response_tokens` | integer \| null | Estimated token count for response | ### Error Detection | Field | Type | Description | | ----------- | --------------- | -------------------------------------- | | `has_error` | boolean \| null | Whether MCP response contains an error | *** ## Elicitation Fields Fields for server-initiated user input requests (MCP elicitation). | Field | Type | Description | | ------------------------ | -------------- | --------------------------------------------- | | `mcp_elicitation_mode` | string \| null | Elicitation mode: `form` or `url` | | `mcp_elicitation_id` | string \| null | Elicitation ID for URL mode correlation | | `mcp_elicitation_action` | string \| null | User action: `accept`, `decline`, or `cancel` | *** ## Session Statistics Aggregate session statistics (for monitoring events). | Field | Type | Description | | ----------------------------------- | ------- | ---------------------------- | | `session_stats.active_sessions` | integer | Number of active sessions | | `session_stats.total_created` | integer | Total sessions created | | `session_stats.total_authenticated` | integer | Total authenticated sessions | | `session_stats.total_anonymous` | integer | Total anonymous sessions | *** ## Internal Fields These fields are present in audit log entries for internal processing but are excluded from external exports and the GraphQL API. | Field | Type | Description | | ------------- | -------------- | -------------------------------------------------------------------- | | `message` | object \| null | Raw MCP message data for internal processing | | `correlation` | object \| null | Request/response correlation for internal tracking | | `metadata` | object | Additional metadata for legacy compatibility and flexible extensions | These fields are for internal use only. They are not exposed through the GraphQL API and are excluded from export payloads to external systems (Elasticsearch, OpenTelemetry, Sentinel). *** ## Complete Example **MCP Request Event:** ```json theme={null} { "timestamp": "2024-01-15T10:30:45.123456+00:00", "event_type": "mcp_request", "component": "mcp_parser", "session_id": "sess_abc123def456", "gateway_id": "550e8400-e29b-41d4-a716-446655440000", "gateway_name": "production-gateway", "organization_id": "org_xyz789", "client_info": { "name": "claude-desktop", "version": "1.2.3" }, "authentication": { "method": "oauth2", "result": "success", "completed_at": 1705315845123, "provider_type": "auth0", "authorization_result": "granted", "scopes": ["read:mcp", "write:mcp"], "granted_at": 1705315845123, "user_id": "auth0|abc123", "session_type": "authenticated" }, "security": { "analyzed": true, "blocked": false, "content_size_bytes": 256 }, "upstream": { "host": "mcp-server.internal", "port": 3001, "name": "finance-tools" }, "user": { "sub": "auth0|abc123", "authenticated": true, "anonymous": false }, "mcp_method": "tools/call", "mcp_tool_name": "get_account_balance", "mcp_request_payload": "{\n \"jsonrpc\": \"2.0\",\n \"method\": \"tools/call\",\n \"params\": {\n \"name\": \"get_account_balance\",\n \"arguments\": {\"account_id\": \"12345\"}\n },\n \"id\": 1\n}", "mcp_request_tokens": 45, "has_error": false, "sequence": 12345, "prev_hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", "integrity_hash": "d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5" } ``` **Security Blocked Event:** ```json theme={null} { "timestamp": "2024-01-15T10:31:12.789012+00:00", "event_type": "mcp_request", "component": "security", "session_id": "sess_xyz789abc123", "gateway_name": "production-gateway", "security": { "analyzed": true, "blocked": true, "detection_method": "replay_protection", "content_size_bytes": 2048 }, "mcp_method": "tools/call", "mcp_tool_name": "execute_query", "sequence": 12346, "integrity_hash": "f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1" } ``` *** ## Export Destinations Audit logs are exported to configured destinations with automatic schema mapping: | Destination | Index Pattern | Documentation | | ------------------ | --------------------- | ------------------------------------------------------------------------------ | | Elasticsearch | `{prefix}-YYYY.MM.DD` | [Export to Elasticsearch](/gateway/guides/audit-trail/export-to-elasticsearch) | | OpenTelemetry | OTLP logs | [Export to OpenTelemetry](/gateway/guides/audit-trail/export-to-opentelemetry) | | Microsoft Sentinel | Custom DCR table | [Export to Sentinel](/gateway/guides/audit-trail/export-to-sentinel) | Each destination applies field-specific transformations. For example, Elasticsearch uses daily indices while Sentinel transforms fields to PascalCase for KQL compatibility. *** ## Related Documentation Configure Golf Gateway using environment variables Distributed mode configuration for GitOps deployments Set up audit log export to Elasticsearch Set up audit log export to Microsoft Sentinel # Environment Variables Source: https://docs.golf.dev/gateway/reference/environment-variables Configuration reference for Golf Gateway environment variables in Centralized and Distributed modes # Environment Variables Golf Gateway uses environment variables with the `GOLF_` prefix for configuration. This reference covers all variables available when running in **Centralized** or **Distributed** mode. Golf Gateway supports multiple deployment modes. This documentation covers **Centralized** and **Distributed** modes, which are the recommended configurations for production deployments. ## Quick Start ### Centralized Mode Minimal configuration to connect a gateway to Control Plane: ```bash theme={null} # Gateway Identity (Required) # Get these values from the Control Plane when creating a new gateway export GOLF_GATEWAY_ID= export GOLF_GATEWAY_API_KEY= export GOLF_GATEWAY_CONTROL_PLANE_URL=https://your-control-plane.example.com # Redis (Required) export GOLF_CACHE_REDIS_URL=redis://localhost:6379/0 ``` ### Distributed Mode Distributed mode uses a local YAML configuration file for servers while connecting to Control Plane for organization policies and monitoring. Use the same environment variables as Centralized mode, plus a `golf_gateway.yaml` configuration file. ```bash theme={null} # Same as Centralized mode export GOLF_GATEWAY_ID= export GOLF_GATEWAY_API_KEY= export GOLF_GATEWAY_CONTROL_PLANE_URL=https://your-control-plane.example.com export GOLF_CACHE_REDIS_URL=redis://localhost:6379/0 # Plus: Create a golf_gateway.yaml file with your server configurations ``` In Centralized and Distributed modes, server configurations, identity providers, and security policies are managed through the Golf Control Plane or YAML file - not through environment variables. *** ## Complete .env Template Copy this template and customize for your environment: ```bash .env.example theme={null} # ============================================================ # Golf Gateway Configuration - Centralized / Distributed Mode # ============================================================ # -------------------- REQUIRED SETTINGS -------------------- # Gateway Identity [REQUIRED] # Get these from Control Plane when creating a new gateway GOLF_GATEWAY_ID=your-gateway-uuid-here GOLF_GATEWAY_API_KEY=your-gateway-api-key-here GOLF_GATEWAY_CONTROL_PLANE_URL=https://your-control-plane.example.com # Redis [REQUIRED] GOLF_CACHE_REDIS_URL=redis://localhost:6379/0 # -------------------- OPTIONAL SETTINGS -------------------- # Server Binding # GOLF_SERVER_HOST=0.0.0.0 # GOLF_SERVER_PORT=8080 # Security Mode # GOLF_SECURITY_MODE=block # Rate Limiting # GOLF_RATE_LIMIT_ENABLED=true # GOLF_RATE_LIMIT_REQUESTS_PER_MINUTE=1000 # GOLF_RATE_LIMIT_WINDOW_SECONDS=60 # -------------------- EXPORT: ELASTICSEARCH ---------------- # GOLF_ELASTICSEARCH_ENABLED=false # GOLF_ELASTICSEARCH_URL=https://localhost:9200 # GOLF_ELASTICSEARCH_API_KEY= # GOLF_ELASTICSEARCH_INDEX_PREFIX=golf-gateway # -------------------- EXPORT: OPENTELEMETRY ---------------- # GOLF_OTEL_ENABLED=false # GOLF_OTEL_ENDPOINT=http://localhost:4317 # GOLF_OTEL_PROTOCOL=grpc # GOLF_OTEL_SERVICE_NAME=golf-gateway # -------------------- EXPORT: AZURE SENTINEL --------------- # GOLF_SENTINEL_ENABLED=false # GOLF_SENTINEL_DCR_IMMUTABLE_ID= # GOLF_SENTINEL_DCR_ENDPOINT= # GOLF_SENTINEL_TENANT_ID= # GOLF_SENTINEL_CLIENT_ID= # GOLF_SENTINEL_CLIENT_SECRET= # -------------------- TLS / mTLS --------------------------- # GOLF_TLS_SERVER_CERT_FILE= # GOLF_TLS_SERVER_KEY_FILE= # GOLF_TLS_MTLS_ENABLED=false ``` *** ## Gateway Identity These variables connect your gateway to the Control Plane. Get these values when creating a new gateway in the Golf Control Plane. Environment prefix: `GOLF_GATEWAY_` | Variable | Type | Required | Description | | -------------------------------- | ------ | -------- | ----------------------------------------------------------- | | `GOLF_GATEWAY_ID` | UUID | **Yes** | Gateway UUID from Control Plane | | `GOLF_GATEWAY_API_KEY` | string | **Yes** | Gateway API key for authentication | | `GOLF_GATEWAY_CONTROL_PLANE_URL` | string | **Yes** | Control Plane URL (must start with `http://` or `https://`) | Keep your `GOLF_GATEWAY_API_KEY` secure. It authenticates your gateway to the Control Plane. If compromised, regenerate it in the Golf Control Plane. *** ## Security Environment prefix: `GOLF_SECURITY_` ### Settings | Variable | Type | Description | | ----------------------------- | ------ | ----------------------------------------------------------------------- | | `GOLF_SECURITY_INTEGRITY_KEY` | string | **Required.** 64-character hex key for audit log integrity verification | ```bash theme={null} # Generate a security key openssl rand -hex 32 ``` ### Operation Mode | Variable | Type | Default | Description | | -------------------- | -------------------- | ------- | -------------------------------------------------------------------------------- | | `GOLF_SECURITY_MODE` | `monitor` \| `block` | `block` | `monitor`: log policy violations only; `block`: enforce RBAC and security blocks | *** ## Cache (Redis) Environment prefix: `GOLF_CACHE_` | Variable | Type | Default | Description | | ---------------------- | ------ | -------------------------- | ---------------------------------- | | `GOLF_CACHE_REDIS_URL` | string | `redis://localhost:6379/0` | **Required.** Redis connection URL | *** ## Rate Limiting Environment prefix: `GOLF_RATE_LIMIT_` | Variable | Type | Default | Description | | ------------------------------------- | ---- | ------- | ------------------------------------- | | `GOLF_RATE_LIMIT_ENABLED` | bool | `true` | Enable rate limiting | | `GOLF_RATE_LIMIT_REQUESTS_PER_MINUTE` | int | `1000` | Requests per minute per user (1-5000) | | `GOLF_RATE_LIMIT_WINDOW_SECONDS` | int | `60` | Rate limit window (10-300 seconds) | The per-user limit applies to authenticated users (and falls back to per-IP for anonymous requests). System-wide (**global**) and **per-server** limits exist but are managed through the Control Plane in Centralized mode — they are not configurable via environment variables. See [Configure Rate Limiting](/gateway/guides/operations/configure-rate-limiting) for the full model. *** ## Privacy Environment prefix: `GOLF_PRIVACY_` | Variable | Type | Default | Description | | -------------------------------- | ---- | ------- | ------------------------------------ | | `GOLF_PRIVACY_SCRUBBING_ENABLED` | bool | `true` | Enable/disable PII scrubbing in logs | *** ## TLS/mTLS Environment prefix: `GOLF_TLS_` ### Server TLS | Variable | Type | Default | Description | | ------------------------------ | ------ | ------- | --------------------------------- | | `GOLF_TLS_SERVER_CERT_FILE` | string | - | Path to server certificate (PEM) | | `GOLF_TLS_SERVER_KEY_FILE` | string | - | Path to server private key (PEM) | | `GOLF_TLS_SERVER_KEY_PASSWORD` | string | - | Password for encrypted server key | ### CA Certificate | Variable | Type | Default | Description | | ----------------------- | ------ | ------- | ------------------------------------------------------ | | `GOLF_TLS_CA_CERT_FILE` | string | - | Path to CA certificate for verifying internal services | ### Mutual TLS (mTLS) | Variable | Type | Default | Description | | ------------------------------ | ------ | ------- | ------------------------------------------ | | `GOLF_TLS_MTLS_ENABLED` | bool | `false` | Enable mutual TLS with client certificates | | `GOLF_TLS_CLIENT_CERT_FILE` | string | - | Path to client certificate (PEM) for mTLS | | `GOLF_TLS_CLIENT_KEY_FILE` | string | - | Path to client private key (PEM) for mTLS | | `GOLF_TLS_CLIENT_KEY_PASSWORD` | string | - | Password for encrypted client key | When `GOLF_TLS_MTLS_ENABLED=true`, both `client_cert_file` and `client_key_file` are required. *** ## Export: Elasticsearch Environment prefix: `GOLF_ELASTICSEARCH_` | Variable | Type | Default | Description | | --------------------------------- | ------ | -------------- | ------------------------------------ | | `GOLF_ELASTICSEARCH_ENABLED` | bool | `false` | Enable Elasticsearch export | | `GOLF_ELASTICSEARCH_URL` | string | - | Elasticsearch URL (for self-hosted) | | `GOLF_ELASTICSEARCH_CLOUD_ID` | string | - | Elastic Cloud ID (for Elastic Cloud) | | `GOLF_ELASTICSEARCH_API_KEY` | string | - | Elasticsearch API key | | `GOLF_ELASTICSEARCH_INDEX_PREFIX` | string | `golf-gateway` | Index name prefix | | `GOLF_ELASTICSEARCH_TIMEOUT` | int | `30` | Request timeout (5-120 seconds) | Use either `url` (self-hosted) or `cloud_id` (Elastic Cloud), not both. *** ## Export: OpenTelemetry Environment prefix: `GOLF_OTEL_` ### Basic Configuration | Variable | Type | Default | Description | | ------------------------ | ---------------------------------------- | -------------- | --------------------------------------- | | `GOLF_OTEL_ENABLED` | bool | `false` | Enable OTEL export | | `GOLF_OTEL_ENDPOINT` | string | - | OTLP endpoint URL (required if enabled) | | `GOLF_OTEL_PROTOCOL` | `grpc` \| `http/protobuf` \| `http/json` | `grpc` | OTLP protocol | | `GOLF_OTEL_SERVICE_NAME` | string | `golf-gateway` | Service name in OTEL | | `GOLF_OTEL_TIMEOUT` | int | `30` | Export timeout (5-120 seconds) | | `GOLF_OTEL_COMPRESSION` | `gzip` \| `none` | `gzip` | Compression method | | `GOLF_OTEL_INSECURE` | bool | `false` | Allow insecure connections | ### Export Targets | Variable | Type | Default | Description | | -------------------------- | ---- | ------- | ----------------- | | `GOLF_OTEL_EXPORT_LOGS` | bool | `true` | Export audit logs | | `GOLF_OTEL_EXPORT_METRICS` | bool | `false` | Export metrics | | `GOLF_OTEL_EXPORT_TRACES` | bool | `false` | Export traces | ### Batching | Variable | Type | Default | Description | | ---------------------------- | ---- | ------- | ----------------------------------------- | | `GOLF_OTEL_BATCH_SIZE` | int | `512` | Items per batch (1-2048) | | `GOLF_OTEL_BATCH_TIMEOUT_MS` | int | `5000` | Batch timeout in milliseconds (100-30000) | ### Headers and Attributes | Variable | Type | Default | Description | | ------------------------------- | ---- | ------- | ------------------------------------- | | `GOLF_OTEL_HEADERS` | JSON | `{}` | Additional headers for authentication | | `GOLF_OTEL_RESOURCE_ATTRIBUTES` | JSON | `{}` | Additional resource attributes | ```bash theme={null} # Example: OTEL with authentication header GOLF_OTEL_HEADERS='{"Authorization": "Bearer YOUR_TOKEN"}' GOLF_OTEL_RESOURCE_ATTRIBUTES='{"environment": "production", "region": "us-west-2"}' ``` *** ## Export: Azure Sentinel Environment prefix: `GOLF_SENTINEL_` ### Data Collection Rule (DCR) | Variable | Type | Default | Description | | -------------------------------- | ------ | ----------------------- | ----------------------------------- | | `GOLF_SENTINEL_ENABLED` | bool | `false` | Enable Sentinel export | | `GOLF_SENTINEL_DCR_IMMUTABLE_ID` | string | - | Data Collection Rule immutable ID | | `GOLF_SENTINEL_DCR_ENDPOINT` | string | - | DCR logs ingestion endpoint (HTTPS) | | `GOLF_SENTINEL_DCR_STREAM_NAME` | string | `Custom-GolfGateway_CL` | DCR stream name | ### Azure AD Authentication | Variable | Type | Default | Description | | ----------------------------- | ------ | ------- | --------------------------- | | `GOLF_SENTINEL_TENANT_ID` | string | - | Azure tenant ID | | `GOLF_SENTINEL_CLIENT_ID` | string | - | Service principal client ID | | `GOLF_SENTINEL_CLIENT_SECRET` | string | - | Service principal secret | ### Performance | Variable | Type | Default | Description | | -------------------------------- | ---- | ------- | ----------------------------------------- | | `GOLF_SENTINEL_BATCH_SIZE` | int | `100` | Batch size (1-500) | | `GOLF_SENTINEL_BATCH_TIMEOUT_MS` | int | `10000` | Batch timeout in milliseconds (100-30000) | | `GOLF_SENTINEL_TIMEOUT` | int | `30` | Request timeout (5-120 seconds) | | `GOLF_SENTINEL_MAX_RETRIES` | int | `3` | Maximum retry attempts (1-10) | *** ## Better Stack Logging Environment prefix: `GOLF_BETTERSTACK_` | Variable | Type | Default | Description | | ------------------------------- | ------ | ------------------------ | --------------------------------------------------------- | | `GOLF_BETTERSTACK_SOURCE_TOKEN` | string | - | Better Stack source token (required to enable) | | `GOLF_BETTERSTACK_HOST` | string | `https://in.logtail.com` | Better Stack ingestion host | | `GOLF_BETTERSTACK_LOG_LEVEL` | string | `INFO` | Minimum log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) | *** ## Related Documentation YAML configuration schema for Distributed mode deployments Complete audit log entry structure reference Learn about Golf Gateway's security features Deploy Golf Gateway to production # YAML Config Schema Source: https://docs.golf.dev/gateway/reference/yaml-schema YAML configuration reference for Golf Gateway Distributed mode # YAML Configuration Schema Golf Gateway supports YAML configuration for **Distributed mode** deployments, where server configurations are defined locally in a YAML file while organization policies and monitoring are managed through the Control Plane. This reference documents the complete YAML schema with all fields, types, and validation rules. ## When to Use YAML Configuration Use YAML configuration when you want to: * **Version control** your MCP server configurations alongside your infrastructure code * **GitOps workflows** where server definitions are managed through pull requests * **Local server definitions** while still benefiting from Control Plane's centralized policy management and monitoring YAML configuration works in **Distributed mode** only. The mode is auto-detected: when a `control_plane` section is present in the YAML, the gateway runs in Distributed mode. For fully managed deployments without local configuration files, use **Centralized mode** where all settings are managed through the Golf Control Plane. *** ## Quick Start Example Here's a complete, annotated configuration showing the most common settings: ```yaml golf-gateway.yaml theme={null} # ============================================================ # Golf Gateway Configuration - Distributed Mode # ============================================================ # Schema version (required, must be "1.0") version: "1.0" # -------------------- Control Plane Connection --------------- # Required for distributed mode - get these values from Control Plane # Mode is auto-detected: control_plane present = distributed mode control_plane: url: https://control-plane.example.com api_key: ${GOLF_CP_API_KEY} gateway_id: 550e8400-e29b-41d4-a716-446655440000 # -------------------- Identity Providers -------------------- # Configure OAuth/OIDC providers for authentication identity_providers: - name: auth0 # Unique name (referenced by servers) type: auth0 # auth0, microsoft-entra-id, descope issuer: https://myorg.auth0.com/ jwks_uri: https://myorg.auth0.com/.well-known/jwks.json api_identifiers: - https://api.example.com # Must match JWT audience # Management API credentials (optional, for group sync) client_id: ${AUTH0_MGMT_CLIENT_ID} # Environment variable substitution client_secret: ${AUTH0_MGMT_CLIENT_SECRET} # -------------------- MCP Servers --------------------------- # Configure upstream MCP servers with RBAC servers: - name: github-mcp # Unique server name url: http://github-mcp:3001 # Server URL description: "GitHub integration" server_type: third_party # third_party or inhouse enabled: true # RBAC: Control who can access this server rbac_enabled: true rbac_mode: allow # allow (whitelist) or deny (blacklist) allowed_groups: - engineering - devops # Link to identity provider for group resolution idp: auth0 # Per-server PII scrubbing overrides (merged with gateway defaults) security: enabled: true sensitive_fields: [token, password] # Additional fields to mask whitelist_fields: [cursor, tool_name] # Fields to never scrub - name: internal-tools url: http://tools-mcp:3002 server_type: inhouse # auto-maps to visibility: internal rbac_enabled: false # No RBAC for internal tools # -------------------- Gateway Policy ------------------------- gateway_policy: scrubbing: enabled: true sensitive_fields: [password, api_key] server_rbac: rbac_enabled: true rbac_mode: allow allowed_groups: [gateway-users] # -------------------- Security Engine ------------------------- security: replay_protection: enabled: true rate_limiting: enabled: true requests_per_minute: 100 # Per-user limit window_seconds: 60 # -------------------- Audit Log Export ---------------------- exporters: elasticsearch: - name: primary enabled: true url: ${ELASTICSEARCH_URL} # Self-hosted URL api_key: ${ELASTICSEARCH_API_KEY} index_prefix: golf-gateway # Creates: golf-gateway-YYYY.MM.DD ``` Use `${VAR}` for required environment variables or `${VAR:default}` for optional ones with defaults. Scroll down for detailed documentation of each section. *** ## File Location The gateway searches for configuration files in this order: 1. `GOLF_CONFIG_FILE` environment variable (explicit path) 2. `/etc/golf-gateway/config.yaml` 3. `/etc/golf-gateway/config.yml` 4. `./golf-gateway.yaml` (current directory) 5. `./golf-gateway.yml` (current directory) ```bash theme={null} # Explicit path export GOLF_CONFIG_FILE=/path/to/config.yaml ``` *** ## Environment Variable Interpolation YAML configuration supports environment variable substitution: | Syntax | Behavior | | ---------------- | --------------------------------------------- | | `${VAR}` | Required - fails if `VAR` is not set | | `${VAR:default}` | Optional - uses `default` if `VAR` is not set | ```yaml theme={null} # Required variable (fails if not set) api_key: ${GOLF_API_KEY} # Optional with default timeout: ${GOLF_TIMEOUT:30} # In nested structures servers: - name: github-mcp url: ${MCP_SERVER_URL:http://localhost:3001} ``` *** ## Root Configuration ```yaml theme={null} version: "1.0" # Required, only "1.0" supported control_plane: # Presence activates distributed mode url: https://control-plane.example.com api_key: ${GOLF_CP_API_KEY} gateway_id: 550e8400-e29b-41d4-a716-446655440000 # Optional sections identity_providers: [] servers: [] gateway_policy: {} security: {} oauth_server: {} exporters: {} ``` ### Root Fields | Field | Type | Required | Default | Description | | -------------------- | ------ | -------- | ------- | ------------------------------------------------------------------------------------------------------ | | `version` | string | Yes | - | Schema version, must be `"1.0"` | | `control_plane` | object | No | - | Control Plane connection settings. Presence activates Distributed mode; absence means Standalone mode. | | `identity_providers` | array | No | `[]` | Identity provider configurations | | `servers` | array | No | `[]` | MCP server configurations | | `gateway_policy` | object | No | `{}` | Gateway-level policy defaults | | `security` | object | No | `{}` | Security engine settings (replay protection, rate limiting) | | `oauth_server` | object | No | `{}` | Gateway's MCP OAuth authorization server configuration | | `exporters` | object | No | `{}` | Log export destinations | The deployment mode is **auto-detected**: if `control_plane` is present, the gateway runs in **Distributed mode**. If absent, it runs in **Standalone mode**. No explicit `mode` field is needed. *** ## Identity Providers Configure OAuth/OIDC identity providers for authentication. ```yaml theme={null} identity_providers: - name: auth0-primary type: auth0 issuer: https://myorg.auth0.com/ jwks_uri: https://myorg.auth0.com/.well-known/jwks.json api_identifiers: - https://api.example.com client_id: ${AUTH0_CLIENT_ID} client_secret: ${AUTH0_CLIENT_SECRET} - name: descope-corp type: descope project_id: ${DESCOPE_PROJECT_ID} management_key: ${DESCOPE_MANAGEMENT_KEY} # issuer and jwks_uri auto-generated for Descope ``` ### Identity Provider Fields | Field | Type | Required | Description | | ------------------- | ------ | ----------- | ---------------------------------------------------------------------------------------------------- | | `name` | string | Yes | Unique provider name (1-255 chars) | | `type` | enum | Yes | `auth0`, `microsoft-entra-id`, `descope` | | `issuer` | string | Conditional | OIDC issuer URL (auto-generated for Descope) | | `jwks_uri` | string | Conditional | JWKS endpoint URL (auto-generated for Descope) | | `userinfo_endpoint` | string | No | Userinfo endpoint URL | | `api_identifiers` | array | No | API audience identifiers | | `timeout` | int | No | Request timeout in seconds (default: 10, range: 1-60) | | `client_id` | string | No | Management API client ID (for group sync) | | `client_secret` | string | No | Management API client secret | | `tenant_id` | string | Conditional | Tenant ID. Required for Entra ID (Azure AD tenant). Optional for Descope (tenant-scoped operations). | ### Descope-Specific Fields | Field | Type | Required | Description | | ---------------- | ------ | ------------- | ------------------------------------- | | `project_id` | string | Yes (Descope) | Descope Project ID | | `management_key` | string | No | Descope Management Key for group sync | *** ## Servers Configure MCP upstream servers with RBAC and security settings. ```yaml theme={null} servers: - name: github-mcp url: http://github-mcp:3001 description: "GitHub integration server" server_type: third_party enabled: true # RBAC rbac_enabled: true rbac_mode: allow allowed_groups: - engineering - devops # Capability RBAC capability_rbac_enabled: true capability_overrides: - capability: "tools/delete_repo" rbac_enabled: true rbac_mode: allow allowed_groups: [repo-admins] # Per-server PII scrubbing overrides (merged with gateway defaults) security: enabled: true sensitive_fields: [password, token] whitelist_fields: [cursor, tool_name] recognizers: - entity_type: EMAIL_ADDRESS enabled: true replacement: "[PII_EMAIL]" # Identity provider reference idp: auth0-primary ``` ### Server Schema List of upstream MCP server configurations. Unique server name (1-255 characters). Used as identifier in logs and routing. Server URL (e.g., `http://mcp-server:3001`). Human-readable server description. Server classification: `inhouse` or `third_party`. Enable or disable this server. Visibility level: `third_party`, `internal`, or `public`. Authentication type for upstream: `oauth`, `none`, or `api_key`. Maintain session affinity to the same upstream instance. Reference to an identity provider name for group resolution. Enable server-level role-based access control. RBAC mode: `allow` (whitelist) or `deny` (blacklist). Groups with access when `rbac_mode: allow`. Groups denied access when `rbac_mode: deny`. Log RBAC access decisions to audit log. Enable per-capability RBAC overrides. Per-capability RBAC rules that override server-level settings. Capability pattern (e.g., `tools/*`, `resources/file`, `tools/delete_repo`). Enable RBAC for this specific capability. RBAC mode for this capability: `allow` or `deny`. Groups with access to this capability. Pre-registered OAuth client ID for this server (bypasses Dynamic Client Registration). Pre-registered OAuth client secret for this server. OAuth issuer URL override. Set when the upstream doesn't publish discovery metadata at its resource origin. Space-separated OAuth scopes to request, replacing those advertised in discovery. Per-server PII scrubbing overrides. These settings are merged on top of gateway-level defaults using union merge. Enable PII scrubbing for this server's traffic. Additional field names to mask (e.g., `password`, `api_key`). Merged via union with gateway-level fields. Field names that should never be scrubbed, even if they match PII patterns (e.g., `cursor`, `tool_name`). Custom regex-based scrubbing rules. Regex pattern to match sensitive content. Masking method: `mask`, `remove`, `hash`, or `replace`. Custom replacement text (required when method is `replace`). Toggle and configure built-in PII recognizers. When merging across layers, `enabled: true` wins over `enabled: false` (most-restrictive doctrine). Entity type (e.g., `EMAIL_ADDRESS`, `CREDIT_CARD`, `US_SSN`). Enable or disable this recognizer. Custom replacement text for this entity type (e.g., `[PII_EMAIL]`). Per-server replacements override gateway defaults. *** ## Gateway Policy Gateway-level policy defaults that apply to all servers unless overridden. In distributed mode, these are merged with organization policies from the Control Plane. ```yaml theme={null} gateway_policy: scrubbing: enabled: true sensitive_fields: - password - api_key whitelist_fields: - connection_id - session_id - cursor custom_rules: - pattern: "sk-[a-zA-Z0-9]+" method: mask recognizers: - entity_type: EMAIL_ADDRESS enabled: true - entity_type: URL enabled: false # Disable URL scrubbing server_rbac: rbac_enabled: true rbac_mode: allow allowed_groups: [gateway-users] denied_groups: [] capability_rbac_enabled: false capability_rbac: read_only: default_groups: [all-users] destructive: default_groups: [power-users] unspecified: default_groups: [all-users] ``` ### Scrubbing Policy The scrubbing configuration uses the same schema at both gateway and server levels. All fields are merged using union — if any layer adds a field or rule, it applies. | Field | Type | Default | Description | | ------------------ | ----- | ------- | ------------------------------------------------------------------------------- | | `enabled` | bool | `false` | Enable PII scrubbing | | `sensitive_fields` | array | `[]` | Field names to always mask as `[MASKED]` | | `whitelist_fields` | array | `[]` | Field names that should never be scrubbed (protects operational data) | | `custom_rules` | array | `[]` | Custom regex-based scrubbing rules (see [server security](#servers) for schema) | | `recognizers` | array | `[]` | Toggle and configure built-in PII recognizers | When recognizer configs are merged across layers (org → gateway → server), **`enabled: true` wins** over `enabled: false` (most-restrictive doctrine). Server-specific `replacement` text overrides gateway defaults. ### Server RBAC Policy | Field | Type | Default | Description | | ------------------------- | ----- | ------- | ------------------------------------ | | `rbac_enabled` | bool | `false` | Default RBAC enabled for new servers | | `rbac_mode` | enum | `allow` | Default RBAC mode | | `allowed_groups` | array | `[]` | Default allowed groups | | `denied_groups` | array | `[]` | Default denied groups | | `capability_rbac_enabled` | bool | `false` | Default capability RBAC enabled | ### Capability RBAC Policy | Field | Type | Description | | ---------------------------- | ----- | ------------------------------------- | | `read_only.default_groups` | array | Default groups for read-only tools | | `destructive.default_groups` | array | Default groups for destructive tools | | `unspecified.default_groups` | array | Default groups for unclassified tools | ### Local Servers Policy Controls the gateway-level blocking policy for locally-defined servers. | Field | Type | Default | Description | | --------- | ----- | ------- | ----------------------------------- | | `enabled` | bool | `false` | Enable local server blocking policy | | `mode` | enum | `allow` | Blocking mode: `allow` or `deny` | | `groups` | array | `null` | Groups affected by this policy | *** ## Security The security section controls replay protection and rate limiting. This is **operational configuration**, not policy — it does not participate in the org → gateway → server policy merge cascade. ```yaml theme={null} security: replay_protection: enabled: true rate_limiting: enabled: true requests_per_minute: 100 window_seconds: 60 ``` ### Replay Protection | Field | Type | Default | Description | | --------- | ---- | ------- | ------------------------------- | | `enabled` | bool | `true` | Enable replay attack protection | ### Rate Limiting | Field | Type | Default | Range | Description | | --------------------- | ---- | ------- | ------ | ---------------------------- | | `enabled` | bool | `true` | - | Enable rate limiting | | `requests_per_minute` | int | `1000` | 1-5000 | Requests per minute per user | | `window_seconds` | int | `60` | 10-300 | Rate limit window | YAML configures the **per-user** limit only. System-wide (**global**) and **per-server** limits are managed through the Control Plane. See [Configure Rate Limiting](/gateway/guides/operations/configure-rate-limiting) for the full model. *** ## OAuth Server Configure the gateway's MCP OAuth authorization server for third-party server authentication flows. ```yaml theme={null} oauth_server: token_ttl: 3600 refresh_token_ttl: 604800 authorization_code_ttl: 60 idp_client_id: ${GOLF_OAUTH_SERVER_IDP_CLIENT_ID} idp_client_secret: ${GOLF_OAUTH_SERVER_IDP_CLIENT_SECRET} ``` | Field | Type | Default | Range | Description | | ------------------------ | ------ | ----------- | ------------ | ----------------------------------------- | | `issuer` | string | gateway URL | - | OAuth issuer URL | | `token_ttl` | int | `3600` | 300-86400 | Access token TTL in seconds | | `refresh_token_ttl` | int | `604800` | 3600-2592000 | Refresh token TTL in seconds | | `authorization_code_ttl` | int | `60` | 30-600 | Authorization code TTL in seconds | | `idp_client_id` | string | - | - | IdP client ID for the OAuth server | | `idp_client_secret` | string | - | - | IdP client secret (supports `${ENV_VAR}`) | *** ## Exporters Configure multiple export destinations for audit logs. You can configure multiple exporters of each type. ```yaml theme={null} exporters: elasticsearch: - name: primary-es enabled: true url: ${ELASTICSEARCH_URL} api_key: ${ELASTICSEARCH_API_KEY} index_prefix: golf-gateway timeout: 30 otel: - name: primary-otel enabled: true endpoint: ${OTEL_ENDPOINT} protocol: grpc service_name: golf-gateway export_logs: true sentinel: - name: azure-sentinel enabled: true dcr_immutable_id: ${SENTINEL_DCR_ID} dcr_endpoint: ${SENTINEL_DCR_ENDPOINT} tenant_id: ${AZURE_TENANT_ID} client_id: ${AZURE_CLIENT_ID} client_secret: ${AZURE_CLIENT_SECRET} ``` ### Exporter Schema Configure audit log export destinations. Elasticsearch export configurations. Unique exporter name. Enable this exporter. Elasticsearch URL for self-hosted deployments (e.g., `https://localhost:9200`). Elastic Cloud ID (alternative to `url`). API key for authentication. Index name prefix. Creates indices like `golf-gateway-2024.01.15`. Request timeout in seconds (5-120). OpenTelemetry export configurations. Unique exporter name. Enable this exporter. OTLP endpoint URL (e.g., `http://localhost:4317`). OTLP protocol: `grpc`, `http/protobuf`, or `http/json`. Service name in OpenTelemetry. Export timeout in seconds (5-120). Export audit logs as OTLP logs. Export gateway metrics. Export request traces. Additional HTTP headers (e.g., `Authorization: Bearer TOKEN`). Microsoft Sentinel export configurations. Unique exporter name. Enable this exporter. Data Collection Rule immutable ID. DCR logs ingestion endpoint (HTTPS URL). DCR stream name for the custom table. Azure AD tenant ID. Service principal client ID. Service principal client secret. Request timeout in seconds (5-120). For Elasticsearch, use either `url` (self-hosted) or `cloud_id` (Elastic Cloud), not both. *** ## Control Plane Connection Connects the gateway to the Control Plane for centralized policy management and monitoring. The presence of this section activates **Distributed mode**. ```yaml theme={null} control_plane: url: https://control-plane.example.com api_key: ${GOLF_CP_API_KEY} gateway_id: 550e8400-e29b-41d4-a716-446655440000 timeout: 30 cache_ttl: 300 ``` | Field | Type | Required | Default | Description | | ------------ | ------ | -------- | ---------------------- | -------------------------------------------------- | | `url` | string | Yes | `https://api.golf.dev` | Control Plane URL | | `api_key` | string | Yes | - | API key for authentication (supports `${ENV_VAR}`) | | `gateway_id` | UUID | Yes | - | Gateway UUID | | `timeout` | int | No | `30` | Request timeout (5-120 seconds) | | `cache_ttl` | int | No | `300` | Policy cache TTL in seconds (60-3600) | *** ## Complete Example A complete Distributed mode configuration with Control Plane connection, identity providers, servers, security, and exporters: ```yaml theme={null} version: "1.0" # Control Plane connection (activates distributed mode) control_plane: url: https://control-plane.example.com api_key: ${GOLF_CP_API_KEY} gateway_id: 550e8400-e29b-41d4-a716-446655440000 # Identity providers for authentication identity_providers: - name: auth0 type: auth0 issuer: https://myorg.auth0.com/ jwks_uri: https://myorg.auth0.com/.well-known/jwks.json api_identifiers: - https://api.example.com client_id: ${AUTH0_MGMT_CLIENT_ID} client_secret: ${AUTH0_MGMT_CLIENT_SECRET} # MCP servers (YAML is source of truth for servers in distributed mode) servers: - name: github-mcp url: http://github-mcp:3001 server_type: third_party rbac_enabled: true allowed_groups: [engineering] idp: auth0 security: enabled: true sensitive_fields: [token] - name: internal-tools url: http://tools-mcp:3002 server_type: inhouse rbac_enabled: false # OAuth authorization server for third-party server auth flows oauth_server: idp_client_id: ${GOLF_OAUTH_SERVER_IDP_CLIENT_ID} idp_client_secret: ${GOLF_OAUTH_SERVER_IDP_CLIENT_SECRET} # Local policy (merged with org policy from Control Plane) gateway_policy: scrubbing: enabled: true sensitive_fields: [ssn, account_number] whitelist_fields: [connection_id, session_id] server_rbac: rbac_enabled: true allowed_groups: [gateway-users] # Security engine settings security: replay_protection: enabled: true rate_limiting: enabled: true requests_per_minute: 100 # Audit log exporters exporters: elasticsearch: - name: primary url: ${ELASTICSEARCH_URL} api_key: ${ELASTICSEARCH_API_KEY} ``` *** ## Validation Rules ### Version * Must be exactly `"1.0"` * Required field ### Identity Providers * Names must be unique across all providers * For non-Descope providers: `issuer` and `jwks_uri` are required * For Descope: `project_id` is required; `issuer` and `jwks_uri` are auto-generated * For Entra ID: `tenant_id` is required ### Servers * Names must be unique across all servers * `idp` references must match an existing identity provider name * `url` must be a valid URL * When gateway and server both enable RBAC, their `rbac_mode` must be consistent (cannot mix `allow` and `deny` across policy levels) ### Exporters * Names must be unique within each exporter type * Elasticsearch: use `url` OR `cloud_id`, not both * OTEL: `endpoint` required when enabled * Sentinel: all DCR and auth fields required when enabled ### Security * `rate_limiting.requests_per_minute` must be between 1 and 5000 when rate limiting is enabled * `rate_limiting.window_seconds` must be between 10 and 300 when rate limiting is enabled ### Control Plane * When present, `url`, `api_key`, and `gateway_id` are required * `organization_id` is optional — resolved from Control Plane during activation if not set * Mode is auto-detected: `control_plane` present = Distributed mode *** ## Configuration Validation CLI Validate configuration files before deployment: ```bash theme={null} # The gateway validates config on startup GOLF_CONFIG_FILE=/path/to/config.yaml python -m golf_gateway.main --validate # Check for undefined environment variables GOLF_CONFIG_FILE=/path/to/config.yaml python -c " from golf_gateway.config.yaml_loader import validate_yaml_config errors = validate_yaml_config('/path/to/config.yaml') for error in errors: print(error) " ``` *** ## Related Documentation Configure Golf Gateway using environment variables Complete audit log entry structure reference Set up role-based access control Deploy Golf Gateway to production # Changelog Source: https://docs.golf.dev/gateway/support/changelog Golf Gateway releases and updates All notable changes to Golf Gateway are documented here. Golf follows [Semantic Versioning](https://semver.org). ## Version 5.2.0 ### Bug Fixes * Authorization redirects now use the gateway address clients already discovered, so sign-in succeeds when that address differs from the Golf API. ## Version 5.1.0 This release adds support for the sessionless MCP `2026-07-28` specification while preserving compatibility with handshake-based MCP clients and servers. ### Features * **Dual-era MCP compatibility**: Golf negotiates the sessionless `2026-07-28` protocol through `server/discover` and falls back to the legacy `initialize` handshake when required. * **Sessionless requests**: Modern MCP requests carry their protocol version, client identity, and capabilities as per-request metadata without relying on `Mcp-Session-Id`. * **Multi-round-trip input**: The gateway recognizes `input_required` results and correlates follow-up requests through opaque `requestState` values. * **Routable transport metadata**: `Mcp-Method` and `Mcp-Name` headers are preserved across the gateway and Golf Local so infrastructure can route modern MCP traffic without parsing JSON-RPC bodies. ### Authentication and Observability * Updated OAuth authorization and client registration behavior for the `2026-07-28` MCP specification, including issuer-bound responses and OAuth client application types. * Added W3C trace context propagation through MCP `_meta` fields for improved request tracing. ### Compatibility * Existing MCP `2025-11-25` and earlier integrations continue to use the established initialization and session flow. * Compatibility is validated against FastMCP `4.0.0` across standalone, centralized, and distributed gateway modes. ## Version 5.0.5 ### Bug Fixes * Restored OAuth authorization for upstream MCP servers that publish their client metadata via discovery. ## Version 5.0.4 ### Bug Fixes * Lowered alerting noise from routine session-expired and CSRF-mismatch events. ## Version 5.0.3 ### Features * Admins can now point Golf at a separate OAuth issuer URL and override the requested scopes per server. ## Version 5.0.2 Patch release focused on observability and UI refinements. ### Features * **Unified MCP Server Request Workflow**: The flow for requesting access to new MCP servers is unified across member-facing surfaces ### Bug Fixes * Fixed JWKS fetch flakiness with retry logic, stale-cache fallback, and thundering-herd protection * Fixed transient infrastructure failures firing user-facing notifications ## Version 5.0.0 Golf Gateway v5.0.0 is a major release introducing local MCP server security, OAuth client credentials support, an MCP server for the Control Plane, and a lightweight default Docker image. ### ⚠ Breaking Changes * **Docker images restructured**: The default Docker image (without `-gpu` suffix) is now a lightweight build containing only the gateway runtime. * **API versioning**: Gateway lifecycle endpoints moved from `/api/gateways/...` to `/api/v1/gateways/...`. Legacy paths still work with deprecation warnings and will be removed in a future release. ### Features #### Golf Local — Local MCP Server Security (Beta) A new Go CLI binary (`golf-local`) extends Golf Gateway's security pipeline to locally-running MCP servers on developer workstations. It intercepts messages between clients and local MCP server processes, forwarding them to the gateway for policy evaluation, PII scrubbing, and audit logging. * **Setup**: OAuth Device Authorization Grant (RFC 8628) flow with interactive gateway selection * **Add**: TUI-based multi-select for AI clients (Cursor, Claude Code, Warp) and MCP servers with environment variable prompts * **Distribution**: Published via Homebrew (`golf-mcp/tap/golf-local`) with cross-platform releases (macOS, Linux, Windows) #### OAuth Client Credentials & CIDM (Beta) * **Pre-registered OAuth client credentials**: Configure a static OAuth `client_id` and `client_secret` per MCP server for upstream Authorization Servers that don't support DCR or CIDM. Secrets are encrypted at rest. * **CIDM (Client ID Metadata Document)**: Support per `draft-ietf-oauth-client-id-metadata-document-00`. The gateway can both serve its own CIDM document and consume CIDM-formatted client IDs from connecting MCP clients. * **Client resolution priority**: Follows MCP spec (2025-11-25) — pre-registered credentials → CIDM → existing DCR client → dynamic client registration. * **`private_key_jwt` authentication**: For CIDM clients with JWKS-based JWT assertion validation. #### MCP Server for Control Plane A new member-facing MCP server runs on the Control Plane, allowing AI assistants to guide users through discovering, authorizing, and configuring MCP server connections. * **Six tools**: `setup` (onboarding wizard), `list_servers`, `get_server`, `generate_client_config`, `authorize_server`, and `report_issue` * **RBAC-aware**: Users only see servers their groups have access to * **OAuth-secured**: Uses the Control Plane's own OAuth Authorization Server * **Issue reporting**: Users can report bugs directly to our team through the MCP server #### Docker Image Changes * **Default image changed**: The default image (without `-gpu` suffix) is now a lightweight gateway-only build for faster pull and startup * **GPU image unchanged**: The `-gpu` image continues to bundle CUDA dependencies for specialized workloads #### YAML Declarative Configuration Full declarative YAML configuration for gateways supporting three modes: standalone, distributed, and centralized. #### API & Authentication * **API versioning**: `/api/v1/` prefix with protocol version tracking for version-aware gateway behavior * **Device Authorization Grant (RFC 8628)**: CLI-based setup with user-facing verification codes and browser-based authentication ### Bug Fixes * Fixed invalid memory check causing death spiral on constrained nodes * Fixed RBAC policy propagation bugs causing divergent access decisions * Fixed OAuth token caching after CP fetch with 429 handling * Fixed OAuth popup window handling race conditions ## Version 4.10.4 ### Features * **Structured Error Codes**: The gateway now returns machine-parseable error codes (`AUTH_TOKEN_EXPIRED`, `UPSTREAM_RBAC_DENIED`, `CONN_UPSTREAM_TIMEOUT`, etc.) in all error responses, organized by connection lifecycle phase. Each error includes a human-readable message and optional diagnostic details, making it easier to programmatically handle failures and troubleshoot issues. ### Improvements * Increased default API rate limits and improved monitoring for rate limit events ### Bug Fixes * Fixed Redis connection pool exhaustion caused by individual auth status queries firing per MCP server on page navigation * Fixed WorkOS authentication version compatibility issue * Improved log severity levels in WorkOS and Platform IDP services ## Version 4.10.3 ### Features * **CIDM (Client ID Metadata Document) Support**: The gateway now implements the MCP 2025-11-25 authorization specification for Client ID Metadata Documents. The Control Plane detects URL-formatted `client_id` values, fetches and validates metadata documents with SSRF protection, and caches results in Redis. Organization-level trust policies (domain allowlists, enable/disable) control which CIDM clients are accepted. The gateway also hosts its own CIDM document at `/.well-known/golf-gateway/oauth/client-metadata.json` for upstream server registration. * **Pre-registered OAuth Client Credentials**: Configure a static OAuth `client_id` and `client_secret` per MCP server to bypass Dynamic Client Registration with stable, pre-provisioned credentials. Secrets are encrypted at rest and the gateway automatically prefers pre-registered credentials over DCR when configured. * **Kubernetes runtimeClassName Support**: Helm charts now support an optional `runtimeClassName` field for both `golf-gateway` and `golf-gateway-centralized`, enabling pod scheduling on specialized runtime classes such as `nvidia` for GPU workloads. ### Improvements * Analytics now excludes MCP protocol overhead methods and notification events, providing more accurate tool usage metrics and call counts ### Bug Fixes * Fixed member portal showing an empty server list for non-admin users caused by an overly strict permission check on the `gatewayAssignmentsRequired` resolver * Fixed race conditions in inventory navigation that caused premature redirects away from the inventory page * Fixed OAuth popup state tracking race conditions during authentication flows * Fixed DCR placeholder being incorrectly treated as authorized upstream connections * Fixed `external_url` propagation in the gateway activation flow for gateways running behind a reverse proxy ## Version 4.10.2 ### Features * **Gateway Degraded Mode**: Gateways automatically cache configuration from the Control Plane and continue operating with cached config during outages, with automatic recovery * **Server Discovery Endpoint**: The `/.well-known/golf-gateway` endpoint now includes upstream MCP server discovery with names, URLs, and descriptions ### Improvements * Mobile layout improvements for the dev portal and MCP server pages ### Bug Fixes * Fixed internal hostnames being exposed in OAuth metadata when gateway runs behind a reverse proxy * Fixed path normalization for upstream servers * Fixed session validation error handling ## Version 4.10.1 ### Bug Fixes * **Fixed gateway startup crash on Apple Silicon**: Resolved a crash during startup of the Golf Gateway on certain Apple Silicon architectures when running in Docker * **Fixed PII whitelist fields not applied in policies**: Whitelist fields configured for PII scrubbing were not being included in organization and gateway policy configurations ## Version 4.10.0 ### Features * **Microsoft Sentinel Integration**: Full Azure Sentinel support as an audit log exporter with DCR-based ingestion, comprehensive schema mapping, and feature parity with Elasticsearch * **Whitelist Fields for PII Scrubbing**: Protect critical operational data (file paths, tool names, cursor tokens) from being inadvertently scrubbed by adding them to a configurable whitelist * **Descope M2M Support**: Service-to-service authentication via Descope Machine-to-Machine tokens for automated integrations * **Resource & Prompt Analytics**: New pie charts showing resource and prompt usage distribution on the analytics dashboard ### Security * **Mobile OAuth Improvements**: Enabled OAuth flow for mobile devices with CSRF protection and redirect-based authentication ### Improvements * Improved PII detection accuracy * Enhanced capability discovery with fallback tokens and improved RBAC defaults for non-tool capabilities * Analytics dashboard improvements with better error rate calculations and latency handling * Simplified identity provider UI with clearer terminology for MCP server authentication * Claude Code CLI option added to "Add to Client" dropdown for easier gateway configuration ### Bug Fixes * Fixed OAuth redirect URI handling in Warp * Fixed resource leaks and race conditions in Sentinel integration * Fixed capability discovery concurrent request handling with per-server locks * Fixed identity provider configuration loops and state management issues * Fixed organization switching to properly refresh sessions on org change * Fixed various UI issues in policy editors and button components ## Version 4.9.0 ### Features * **WorkOS Platform SSO**: Migrated to WorkOS AuthKit for enterprise single sign-on, providing improved authentication reliability and expanded IdP compatibility * **Dynamic Security Mode**: Configure security mode (monitor or block) directly from the Control Plane UI with real-time gateway updates—no restarts required * **Per-Gateway Data Exporters**: Each gateway can now have its own exporter configuration, enabling flexible data routing to different destinations per environment * **Organization License Tiers**: Support for free and licensed organization tiers with tier-specific feature availability * **Centralized Analytics Export**: Analytics data is now exported through the Control Plane, providing unified observability across all gateways ### Security * **Enhanced Redirect URI Validation**: Improved validation to block dangerous URI schemes and enforce HTTPS for non-localhost callbacks, aligned with RFC 8252 security recommendations * **Improved OAuth Error Handling**: Structured error codes and user-friendly notifications for Dynamic Client Registration (DCR) failures ### Improvements * Cursor-based pagination for security incidents page for better performance with large datasets * Unified console logging format across all components * Organization-scoped MCP server names allow different organizations to use the same server names ### Bug Fixes * Fixed RBAC policy inheritance to correctly apply organization-level access policies at runtime * Fixed empty allowlist now correctly interpreted as "deny all" instead of "no policy" * Fixed group intersection logic when multiple RBAC levels are configured * Fixed monitor mode to allow sessions to continue while logging policy violations * Fixed various authentication and invitation flow issues * Fixed exporter configuration and analytics timing issues ## Version 4.8.0 ### Features * **Interactive Onboarding**: New guided onboarding experience with step-by-step tour overlay, progress checklist, and replay functionality for new users * **Single Upstream Mode**: Simplified configuration option for gateways with a single MCP server, including UI toggle, modals for enabling/disabling, and server swap functionality * **Multi-Architecture Builds**: Docker images now support multiple CPU architectures for broader deployment compatibility ### Security * **Enhanced PII Scrubbing**: Fixed conflicts between entity detectors for more accurate PII detection * **API Key Detection**: Added standard API key pattern recognition to the privacy scrubber * **Organization Isolation**: Fixed cross-organization MCP server access issues and improved security for race conditions ### Bug Fixes * Fixed capability-level RBAC configuration propagation in centralized mode * Fixed capability fetching for API key authenticated servers * Resolved server name and URL validation issues in the UI * Fixed bulk server assignment bypassing single upstream mode validation * Fixed invitation system issues * Corrected routing and mutation issues in single upstream mode * Resolved stale cache issues affecting UI performance ### Improvements * Optimized session management and data loading for faster UI responsiveness ## Version 4.7.0 ### Features * **Microsoft Entra ID Support**: Full Azure Active Directory integration for enterprise SSO with group synchronization and automatic role mapping * **Per-Organization Identity Providers**: Each organization can now configure its own IdP, enabling true multi-tenant deployments with isolated authentication * **MCP Server Catalog**: Browse and add from 20+ pre-configured MCP servers * **User Onboarding Flow**: New guided onboarding experience with domain configuration and organization selection for first-time users ### Security * **Encryption Key Rotation**: Gateways now receive automatic key rotation notifications * **Service-to-Service Authentication**: Added security key authentication between RBAC-admin and Golf API * **Exporter Access Control**: Separate read-only and read-write configurations for audit log exporters * Fixed Elasticsearch adapter resource leak ### Bug Fixes * Fixed organization switching and JIT role fetching issues * Fixed Control Plane not updating IdPs/exporters correctly * Fixed critical navigation and state issues in the UI * Fixed circuit breaker issues when fetching roles * Fixed user provisioning when logging into new organizations via Platform SSO * Fixed OAuth resource indicator in single upstream mode ### Breaking Changes * Global admin roles removed in favor of organization-scoped administration ## Version 4.6.0 ### Features * **Multi-Organization Support**: Manage multiple organizations from a single Control Plane with isolated analytics, policies, and configurations * **Cursor Integration**: Connect Golf Gateway directly to Cursor IDE * **Simplified Gateway Setup**: Streamlined "Add to Client" experience with auto-generated connection instructions ### Security * Enhanced credential encryption and token storage * Improved isolation between organizations ### Improvements * Various stability and performance improvements ## Version 4.5.0 ### Features * **Mutual TLS**: Secure communication between gateways and MCP servers * **Simplified Certificates**: Easier deployments with automatic certificate generation ### Improvements * Improved API key authentication for third-party servers * Various stability and deployment improvements ## Version 4.4.0 ### Features * **Gateway Visibility**: See which gateways are assigned to each MCP server * **Server Capabilities**: View MCP server capabilities and annotations directly in the portal * **Multi-Gateway Management**: Improved admin experience for managing multiple gateways ### Improvements * Better display of gateway URLs across deployment modes * Various UI polish and stability fixes ## Version 4.3.1 ### Initial Release First stable release with automated versioning and release management. ### Notes * GPU-accelerated builds available with `-gpu` suffix (e.g., `v4.3.1-gpu`) *** # Authentication Source: https://docs.golf.dev/golf-mcp-framework/authentication Implement JWT, development, and API key authentication in your GolfMCP servers. GolfMCP provides flexible authentication mechanisms to secure your MCP servers: 1. **JWT Authentication** - Enterprise-grade authentication with JWKS support for production 2. **Development Authentication** - Simple token-based authentication for development and testing 3. **OAuth Server** - Full OAuth 2.0 authorization server functionality 4. **Remote Authentication** - Distributed authentication across multiple resource servers 5. **API Key Authentication** - Pass-through authentication to upstream APIs Authentication is configured using a dedicated `auth.py` file in your project root, providing clean separation from other build logic. ## JWT authentication ### Overview JWT authentication provides enterprise-grade security with JWKS (JSON Web Key Set) support. This is the recommended approach for production environments where you need standards-compliant token validation. ### Configuration Configure JWT authentication in your project's `auth.py`: ```python theme={null} # auth.py from golf.auth import configure_auth, JWTAuthConfig configure_auth( JWTAuthConfig( jwks_uri_env_var="JWKS_URI", issuer_env_var="JWT_ISSUER", audience_env_var="JWT_AUDIENCE", required_scopes=["read:user"] ) ) ``` ### Environment variables Set these environment variables in your `.env` file: ```bash theme={null} JWKS_URI=https://your-provider.com/.well-known/jwks.json JWT_ISSUER=https://your-provider.com/ JWT_AUDIENCE=your-api-audience # Alternative: PEM-encoded public key (instead of JWKS_URI) JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEF..." # Multiple audiences (comma-separated) JWT_AUDIENCE=https://api.production.com,https://api2.production.com ``` ### How it works 1. **Token Validation**: Golf validates JWTs against the JWKS endpoint 2. **Standards Compliance**: Full RFC 7519 JWT validation 3. **Scope Verification**: Ensures tokens have required scopes ## Development authentication ### Overview Development authentication provides a simple token-based system perfect for development and testing environments. You can define custom tokens with specific client IDs and scopes. ### Configuration Configure development authentication in your project's `auth.py`: ```python theme={null} # auth.py from golf.auth import configure_auth, StaticTokenConfig configure_auth( StaticTokenConfig( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"] }, "test-token-456": { "client_id": "test-client", "scopes": ["read"] } }, required_scopes=["read"] ) ) ``` ### Using development tokens Pass tokens via the Authorization header: ```bash theme={null} curl -H "Authorization: Bearer dev-token-123" http://localhost:3000/mcp ``` ## OAuth server configuration ### Overview Golf v0.2.0 can act as a complete OAuth 2.0 authorization server, not just validate tokens. This mode allows your MCP server to issue JWT tokens to clients and provide full OAuth 2.0 endpoints for authorization, token issuance, and revocation. ### Configuration Configure OAuth server mode in your project's `auth.py`: ```python theme={null} # auth.py from golf.auth import configure_auth, OAuthServerConfig configure_auth( OAuthServerConfig( base_url="https://auth.example.com", # Public URL of your server issuer_url="https://auth.example.com", # OAuth issuer URL service_documentation_url="https://docs.example.com", # Optional # Scope configuration valid_scopes=["read", "write", "admin"], # Scopes clients can request default_scopes=["read"], # Default scopes for new clients required_scopes=["read"], # Scopes required for all requests # Environment variable support base_url_env_var="OAUTH_BASE_URL" # Runtime URL override ) ) ``` ### Environment variables Configure runtime URL overrides in your `.env` file: ```bash theme={null} # .env file OAUTH_BASE_URL=https://auth.production.com ``` ## Remote authentication configuration ### Overview Remote authentication allows you to distribute authentication across multiple resource servers while maintaining centralized token validation. This is useful for microservices architectures where multiple services need to validate tokens from the same authorization servers. ### Configuration ```python theme={null} # auth.py from golf.auth import configure_auth, RemoteAuthConfig, JWTAuthConfig configure_auth( RemoteAuthConfig( # Static configuration authorization_servers=["https://auth1.example.com"], resource_server_url="https://api.example.com", # Environment variable resolution (NEW in v0.2.0) authorization_servers_env_var="AUTH_SERVERS", # Comma-separated server URLs resource_server_url_env_var="RESOURCE_URL", # This resource server's URL token_verifier_config=JWTAuthConfig(jwks_uri_env_var="JWKS_URI") ) ) ``` ### Environment variables ```bash theme={null} # .env file for Remote Auth AUTH_SERVERS=https://auth1.prod.com,https://auth2.prod.com,https://backup-auth.prod.com RESOURCE_URL=https://api.production.com JWKS_URI=https://auth1.prod.com/.well-known/jwks.json ``` ## API key authentication ### Overview Golf provides a simple API key pass-through authentication mechanism that allows MCP servers to extract API keys from request headers and forward them to upstream services. The actual authentication happens at the destination API level, not within the MCP server. ### Configuration Configure API key extraction in your project's `auth.py`: ```python theme={null} # auth.py from golf.auth import configure_api_key # Configure which header contains the API key configure_api_key( header_name="Authorization", # Header to extract from header_prefix="Bearer " # Optional prefix to strip ) ``` ### Using API keys in tools Tools access the API key with a simple import: ```python theme={null} from golf.auth import get_api_key async def my_tool(): api_key = get_api_key() if not api_key: return {"error": "No API key provided"} # Use the key with your API response = await client.get( "https://api.example.com/endpoint", headers={"Authorization": f"Bearer {api_key}"} ) ``` ## Using authentication tokens in tools ### Overview Golf provides a utility function for extracting authentication tokens from reqest context within your MCP tools: `get_auth_token()`. ### Token extraction functions #### get\_auth\_token() ```python theme={null} from golf.auth import get_auth_token async def secure_api_tool(data: str): # Extract authentication token auth_token = get_auth_token() if not auth_token: return {"error": "JWT/OAuth token required"} # Forward token to upstream API import httpx async with httpx.AsyncClient() as client: response = await client.post( "https://api.example.com/secure-endpoint", headers={"Authorization": f"Bearer {auth_token}"}, json={"data": data} ) return { "data": data, "response": response.json(), "authenticated": True } ``` ## Enhanced environment variable support ### Overview Golf v0.2.0 significantly expanded environment variable support across all auth providers. ### JWT authentication environment variables All JWT fields now support environment variable resolution: ```python theme={null} # All JWT fields now support environment variables configure_auth( JWTAuthConfig( # Direct values (still supported) jwks_uri="https://auth.example.com/.well-known/jwks.json", # Environment variable resolution (preferred for deployment) public_key_env_var="JWT_PUBLIC_KEY", # PEM-encoded public key jwks_uri_env_var="JWKS_URI", # JWKS endpoint URL issuer_env_var="JWT_ISSUER", # Expected issuer audience_env_var="JWT_AUDIENCE", # Expected audience(s) required_scopes=["read:user"] # Scopes are part of the config object ) ) ``` ### Migration from v0.1.x Breaking changes from previous versions: ```python theme={null} # ❌ BROKEN - These will cause TypeError in v0.2.0 configure_jwt_auth( jwks_uri_env_var="JWKS_URI", required_scopes=["read:user"] # This parameter was removed ) configure_dev_auth( tokens={"dev-token": {"client_id": "dev"}}, required_scopes=["read"] # This parameter was removed ) # ✅ CORRECT - v0.2.0 syntax from golf.auth import configure_auth, JWTAuthConfig, StaticTokenConfig # JWT Auth - scopes are part of the config object configure_auth( JWTAuthConfig( jwks_uri_env_var="JWKS_URI", required_scopes=["read:user"] # Scopes are part of the config object ) ) # Development Auth configure_auth( StaticTokenConfig( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"] } }, required_scopes=["read"] # Scopes are part of the config object ) ) ``` # CLI Source: https://docs.golf.dev/golf-mcp-framework/cli-commands Reference for the GolfMCP command-line interface. The `golf` command-line interface is your primary tool for managing GolfMCP projects. ## Commands ### `golf init` Initializes a new GolfMCP project directory with Golf branding and modern authentication setup. ```bash Basic theme={null} golf init my_awesome_server ``` ```bash With options theme={null} golf init my-api-project --output-dir ./projects ``` The name of the project and the directory to be created. Specifies a different directory to create the project in. Defaults to a new directory named `project_name` in the current location. Alias: `-o` ### `golf build` Builds your GolfMCP project into a runnable MCP server. The build process includes enhanced authentication handling and validation. ```bash Development theme={null} golf build dev ``` ```bash Production theme={null} golf build prod ``` The build environment parameter is required and must be either `dev` or `prod`:
Development (`dev`) Production (`prod`)
• Copies `.env` file to `dist/` directory
• Environment variables loaded from local file
• Optimized for local development and testing
• No `.env` file copied
• Environment variables expected at runtime
• Optimized for production deployment
### `golf run` Runs a previously built GolfMCP server with enhanced runtime features. ```bash theme={null} golf run ``` Make sure to run golf build prod or golf build dev before using golf run. # Component specification Source: https://docs.golf.dev/golf-mcp-framework/component-specification Learn how to define GolfMCP components (tools, resources, prompts). ### 1. Description The primary source for a component's description is its **module-level docstring**. ```python theme={null} # tools/my_tool.py """This is the description for 'my_tool'. It can span multiple lines and will be used to generate tool description. """ # ... rest of the tool code ``` * This docstring is **mandatory**. If missing, the build will fail. * The function docstring of the exported function is generally ignored if a module docstring is present. It might be used as a fallback if the module docstring is missing, but relying on this is not recommended. ### 2. Entry function (`export`) GolfMCP needs to know which function within your Python file is the main entry point for the component. This is primarily done by assigning the function to a module-level variable named `export`. ```python theme={null} # tools/calculator.py """A simple calculator tool.""" async def add_numbers(a: int, b: int) -> int: return a + b async def subtract_numbers(a: int, b: int) -> int: return a - b # 'add_numbers' is the designated tool function export = add_numbers ``` If an `export` variable is not found, GolfMCP build will fail. ### 3. Function signature requirements The signature of your exported function must adhere to certain rules: * **Tools:** * Parameters **must** have type hints (e.g., `param: str`, `count: int`). * The return value **must** have a type hint (e.g., `-> str`, `-> Dict[str, Any]`). * Can be `async def` or `def`. * **Resources:** * If defined as a function, it follows similar rules to tools. * Resource functions typically do not take arguments unless they are part of a resource template (where arguments come from URI path parameters). * The URI for the resource is defined by a module-level variable `resource_uri: str`. * Example: `resource_uri = "data://config"` * Can also be a simple module-level constant (JSON-serializable). * **Prompts:** * The function should return either a `str` (which becomes a single user message) or a `List[Dict]`. * Parameters should have type hints. **Pydantic for Input/Output Schemas (Tools):** For tools, Pydantic `BaseModel` is highly recommended for defining complex input argument structures and output shapes, enabling clear schemas and validation. * **Input Parameters & Schema:** Tool inputs are **always** defined by the parameters of your exported tool function. These parameters **must** have type hints and descriptions. * **Direct Function Parameters:** You define inputs directly in the tool function's signature. ```python theme={null} # tools/hello.py """Hello World tool example.""" from typing import Annotated from pydantic import BaseModel, Field class Output(BaseModel): message: str async def hello( name: Annotated[str, Field(description="The name of the person to greet")] = "World", greeting: Annotated[str, Field(description="The greeting phrase to use")] = "Hello" ) -> Output: # 'name' and 'greeting' are direct input parameters. # Golf's parser creates an inputSchema in the manifest based on these. return Output(message=f"{greeting}, {name}!") export = hello ``` * **Output Structure & Schema:** The structure of your tool's output should be defined by its return type hint. It is strongly recommended to use a Pydantic `BaseModel` for this return type to ensure a clear and validated output schema. ```python theme={null} # tools/user_profile_tool.py """Tool to fetch user profile information.""" from pydantic import BaseModel from typing import Optional class Output(BaseModel): # Explicit Pydantic model for the output user_id: int username: str email: Optional[str] is_active: bool async def fetch_user_profile(user_id: int) -> Output: # We use the 'Output' return type hint for its # runtime behavior and schema exposure to clients. return Output( user_id=user_id, username="example_user", email="user@example.com", is_active=True ) export = fetch_user_profile ``` ### 4. Parameter annotations (recommended) While simple type hints are sufficient, using `Annotated` with Pydantic `Field` provides rich descriptions and validation that significantly improves how AI agents understand and use your tools. #### Basic parameter annotations ```python theme={null} from typing import Annotated from pydantic import BaseModel, Field async def hello( name: Annotated[str, Field(description="The name of the person to greet")] = "World", greeting: Annotated[str, Field(description="The greeting phrase to use")] = "Hello" ) -> Output: """Say hello to the given name.""" return Output(message=f"{greeting}, {name}!") ``` #### Parameter validation Field annotations support various validation constraints: ```python theme={null} from typing import Annotated, Optional from pydantic import BaseModel, Field class ChargeOutput(BaseModel): success: bool charge_id: str message: str async def charge_payment( # Numeric constraints amount: Annotated[float, Field( description="Amount to charge in USD", gt=0, # Must be greater than 0 le=10000 # Maximum charge limit )], # Pattern validation card_token: Annotated[str, Field( description="Tokenized payment card identifier", pattern=r"^tok_[a-zA-Z0-9]+$" # Regex validation )], # String length constraints description: Annotated[str, Field( description="Optional payment description", max_length=200, min_length=0 )] = "", # Optional parameters with constraints customer_email: Annotated[Optional[str], Field( description="Customer's email address", pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$", default=None )] = None ) -> ChargeOutput: """Process a payment charge with validation.""" # Implementation here pass ``` ### 5. Tool annotations (MCP behavioral hints) Tool annotations provide behavioral hints about your tools to MCP clients, following the official MCP specification. These hints help clients understand how to interact with your tools safely and efficiently. #### Overview Add an `annotations` dictionary at the module level to specify behavioral hints: ```python theme={null} """Delete file tool.""" from typing import Annotated from pydantic import BaseModel, Field # Tool annotations - MCP behavioral hints annotations = { "readOnlyHint": False, # Tool modifies state "destructiveHint": True, # Tool may delete/mutate data irreversibly "idempotentHint": False, # Repeated calls have side effects "openWorldHint": False # Tool operates on local state only } class Output(BaseModel): success: bool message: str async def delete_file( path: Annotated[str, Field(description="Path to file to delete")] ) -> Output: """Delete a file from the filesystem.""" return Output(success=True, message="File deleted") export = delete_file ``` #### Supported annotation types `true` → tool cannot change state (pure "GET-style" call) **Note**: When `true`, other hints are ignored by MCP clients. `true` → tool may delete or irreversibly mutate data Only meaningful when `readOnlyHint` is `false`. `true` → repeated calls with identical arguments are safe and side-effect-free Helps MCP clients add caching and deduplication. `true` → behavior depends on external mutable state (e.g., live web, clock) Signals lower reproducibility to MCP clients. #### Common patterns **Read-only tool:** ```python theme={null} # Tool that only reads data annotations = { "readOnlyHint": True # Other hints ignored when this is true } ``` **Web search tool:** ```python theme={null} # Tool that searches the internet annotations = { "readOnlyHint": True, # Doesn't modify local state "openWorldHint": True # Depends on external web services } ``` **Idempotent tool:** ```python theme={null} # Tool safe to retry annotations = { "readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, # Safe to call multiple times "openWorldHint": False } ``` **File operations tool:** ```python theme={null} # Tool that modifies files annotations = { "readOnlyHint": False, "destructiveHint": True, # May delete files "idempotentHint": False, # Multiple calls may have different effects "openWorldHint": False # Works on local filesystem } ``` # Configuration reference Source: https://docs.golf.dev/golf-mcp-framework/configuration The `golf.json` file is the main configuration file for your Golf project. Place this file in your project root directory to configure your MCP server. The name of your MCP server instance. ```json theme={null} { "name": "MyProject" } ``` A brief description of your Golf project. ```json theme={null} { "description": "A GolfMCP project" } ``` The network interface the server will bind to. ```json theme={null} { "host": "localhost" } ``` The port number the server will listen on. ```json theme={null} { "port": 3000 } ``` The transport protocol for client-server communication. **Options:** * `"sse"` - Server-Sent Events * `"streamable-http"` - HTTP with streaming support * `"stdio"` - Standard input/output ```json theme={null} { "transport": "sse" } ``` Enable OpenTelemetry distributed tracing for your MCP server. For detailed configuration and features, see [Telemetry](/golf-mcp-framework/telemetry-monitoring). ```json theme={null} { "opentelemetry_enabled": true } ``` The default exporter to use for OpenTelemetry traces when enabled. **Options:** * `"otlp_http"` - OTLP HTTP exporter (for Jaeger, Grafana Tempo, etc.) * `"console"` - Console exporter (for debugging) ```json theme={null} { "opentelemetry_default_exporter": "otlp_http" } ``` When using `otlp_http`, you must set the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable. See the environment variables section below. ## Health check configuration (deprecated) The following health check configuration options are **deprecated** as of v0.2.11. Use custom `health.py` and `readiness.py` files instead for modern, flexible health checks with Kubernetes compatibility. See [Telemetry & Monitoring](/golf-mcp-framework/telemetry-monitoring) for the new approach. **Deprecated**: Enable basic health check endpoint. Use custom `health.py` file instead. ```json theme={null} { "health_check_enabled": true } ``` **Deprecated**: Health check endpoint path. Custom `health.py` files automatically create `/health` endpoint. ```json theme={null} { "health_check_path": "/health" } ``` **Deprecated**: Static health check response text. Use custom `health.py` for dynamic responses with proper status codes. ```json theme={null} { "health_check_response": "Service is healthy" } ``` # Golf utilities Source: https://docs.golf.dev/golf-mcp-framework/golf-utilities Built-in utilities for elicitation, sampling, and context management in Golf v0.2.0. Golf v0.2.0 introduces powerful built-in utilities that enhance your tool development experience. ## Overview Golf utilities provide four core capabilities: 1. **Context Access** - Direct access to FastMCP context without manual parameter passing 2. **Elicitation** - Interactive user prompting and input collection 3. **Sampling** - LLM interactions and text generation with multiple modes 4. **Authentication Integration** - Seamless token extraction All utilities automatically handle context management using Python's `contextvars` for thread-safe, async-aware access to FastMCP features. ## Context access ### Get current context The `get_current_context()` function provides direct access to the FastMCP context without requiring explicit context parameter passing. ```python theme={null} from golf.utilities import get_current_context async def context_aware_tool(): # Get the current FastMCP context context = get_current_context() # Access request information request_id = getattr(context, 'request_id', None) return { "request_id": request_id, "context_available": True } ``` ### Context with logging ```python theme={null} from golf.utilities import get_current_context async def logging_tool(message: str): context = get_current_context() # Use context for structured logging context.logger.info(f"Processing message: {message}") return {"status": "logged", "message": message} ``` ### Error handling ```python theme={null} from golf.utilities import get_current_context async def safe_context_tool(): try: context = get_current_context() return {"context_available": True} except RuntimeError as e: # Context not available (e.g., called outside MCP tool) return { "context_available": False, "error": str(e) } except ImportError as e: # FastMCP not available or incompatible version return { "context_available": False, "error": "FastMCP >=2.11.0 required" } ``` ## Elicitation utilities Elicitation utilities enable your tools to interact with users, collect additional information, and create dynamic conversational experiences. ### Basic elicitation ```python theme={null} from golf.utilities import elicit async def interactive_tool(): # Simple text prompt color = await elicit("What's your favorite color?") # Use the response in your tool logic return {"message": f"Great choice! {color} is a beautiful color."} ``` ### Type-safe elicitation ```python theme={null} from golf.utilities import elicit from pydantic import BaseModel class UserInfo(BaseModel): name: str email: str age: int async def user_registration_tool(): # Collect structured data with validation user_info = await elicit("Please provide your information:", UserInfo) return { "name": user_info.name, "email": user_info.email, "age": user_info.age } ``` ### Confirmation dialogs ```python theme={null} from golf.utilities import elicit_confirmation async def deletion_tool(file_path: str): # Ask for confirmation before destructive action confirmed = await elicit_confirmation( f"Are you sure you want to delete {file_path}?" ) if confirmed: # Perform deletion return {"status": "deleted", "file": file_path} else: return {"status": "cancelled", "file": file_path} ``` ### Advanced elicitation with error handling ```python theme={null} from golf.utilities import elicit, elicit_confirmation async def configuration_tool(): try: # Collect multiple pieces of information name = await elicit("What's your name?") email = await elicit("What's your email address?") # Confirm before saving confirmed = await elicit_confirmation( f"Save configuration for {name} ({email})?" ) if confirmed: config = {"name": name, "email": email} return {"configuration": config, "saved": True} else: return {"configuration": None, "saved": False} except RuntimeError as e: # User declined or cancelled return {"error": f"Configuration failed: {str(e)}"} ``` ## Sampling utilities Sampling utilities provide direct access to LLM capabilities within your tools, enabling text generation, analysis, and AI-powered processing with multiple modes. ### Basic sampling ```python theme={null} from golf.utilities import sample async def explanation_tool(topic: str): # Generate an explanation using the default model explanation = await sample(f"Explain {topic} in simple terms") return {"topic": topic, "explanation": explanation} ``` ### Structured sampling The `sample_structured()` function uses a lower temperature (0.1) for more consistent, formatted outputs. ```python theme={null} from golf.utilities import sample_structured async def entity_extraction_tool(text: str): # Use structured sampling for formatted outputs entities = await sample_structured( f"Extract entities from this text: {text}", format_instructions="Return as JSON with keys: persons, organizations, locations" ) return {"text": text, "entities": entities} ``` ### Context-enhanced sampling The `sample_with_context()` function automatically appends context data to prompts. ```python theme={null} from golf.utilities import sample_with_context async def personalized_report_tool(data: str): # Sample with automatic context enhancement report = await sample_with_context( f"Generate a personalized report based on this data: {data}", context_data={ "user_preferences": "detailed analysis", "report_format": "executive summary" } ) return {"data": data, "report": report} ``` ### Advanced sampling with parameters ```python theme={null} from golf.utilities import sample async def creative_writing_tool(prompt: str, style: str): # Advanced sampling with custom parameters story = await sample( f"Write a short story in {style} style based on: {prompt}", model="gpt-4", max_tokens=500, temperature=0.8 ) return { "prompt": prompt, "style": style, "story": story } ``` ### Sampling error handling ```python theme={null} from golf.utilities import sample, sample_structured async def robust_analysis_tool(text: str): try: # Attempt structured analysis analysis = await sample_structured( f"Analyze the sentiment and themes in: {text}", format_instructions="Return JSON with sentiment and themes" ) return {"analysis": analysis, "method": "structured"} except RuntimeError as e: # Fall back to basic sampling try: analysis = await sample(f"Analyze: {text}") return {"analysis": analysis, "method": "basic"} except RuntimeError: return { "error": "Analysis failed", "text": text } ``` ## Authentication integration Golf utilities seamlessly integrate with the authentication system for secure API forwarding. ### Basic token forwarding ```python theme={null} from golf.utilities import sample from golf.auth import get_auth_token async def api_analysis_tool(data: str): # Get authentication token auth_token = get_auth_token() if not auth_token: return {"error": "Authentication required"} # Use token for upstream API call import httpx async with httpx.AsyncClient() as client: response = await client.post( "https://api.example.com/analyze", headers={"Authorization": f"Bearer {auth_token}"}, json={"data": data} ) # Enhance results with LLM sampling summary = await sample( f"Summarize this API response: {response.text}" ) return { "api_response": response.json(), "summary": summary } ``` ### Combined context and auth ```python theme={null} from golf.utilities import get_current_context, sample from golf.auth import get_auth_token async def secure_personalized_tool(request: str): # Get both context and auth context = get_current_context() auth_token = get_auth_token() if not auth_token: return {"error": "Authentication required"} # Log request with context context.logger.info(f"Processing request: {request}") # Generate personalized response response = await sample( f"Respond to this request personally: {request}", context_data={ "user_authenticated": True, "request_id": getattr(context, 'request_id', None) } ) return { "request": request, "response": response, "authenticated": True } ``` ## Error handling best practices ### Comprehensive error handling ```python theme={null} from golf.utilities import get_current_context, sample, elicit from golf.auth import get_auth_token async def production_ready_tool(task: str): try: # Verify context availability context = get_current_context() # Check authentication auth_token = get_auth_token() if not auth_token: confirmation = await elicit_confirmation( "No authentication found. Continue with limited functionality?" ) if not confirmation: return {"error": "Authentication required"} # Perform main task result = await sample(f"Complete this task: {task}") # Log success context.logger.info(f"Task completed: {task}") return { "task": task, "result": result, "authenticated": bool(auth_token) } except ImportError: return { "error": "FastMCP >=2.11.0 required", "task": task } except RuntimeError as e: if "Context" in str(e): return { "error": "Must be called from MCP tool context", "task": task } elif "declined" in str(e): return { "error": "User declined operation", "task": task } else: return { "error": f"Operation failed: {str(e)}", "task": task } ``` # Introduction to GolfMCP Source: https://docs.golf.dev/golf-mcp-framework/introduction Learn about the GolfMCP framework, designed to simplify MCP server development. GolfMCP is a framework designed to simplify the development of Model Context Protocol (MCP) servers. It allows you to define tools, resources, and prompts as simple Python files. GolfMCP then discovers these components and compiles them into a runnable MCP server with minimal boilerplate. The core philosophy is to let you focus on the logic of your components, while Golf handles the complexities of MCP server setup, authentication and telemetry. # Project structure Source: https://docs.golf.dev/golf-mcp-framework/project-structure Understand GolfMCP project layout and component naming conventions. GolfMCP uses a convention-based project structure. ``` / ├── golf.json ├── auth.py # Authentication configuration (v0.2.0) ├── startup.py # Optional initialization script (v0.2.10) ├── health.py # Optional health check endpoint (v0.2.11) ├── readiness.py # Optional readiness check endpoint (v0.2.11) ├── prompts/ │ └── example_prompt.py ├── resources/ │ └── example_resource.py │ └── sub_category/ │ └── nested_resource.py │ └── common.py └── tools/ └── example_tool.py └── payments/ └── common.py └── get_balance.py └── transaction/ └── submit.py ``` * **`golf.json`**: The main configuration file (see [Configuration](/golf-mcp-framework/configuration)). * **`auth.py`**: Dedicated authentication configuration file (see [Authentication](/golf-mcp-framework/authentication)). * **`startup.py`**: Optional initialization script for environment setup and server startup configuration. * **`health.py`**: Optional custom health check endpoint with sophisticated monitoring logic (see [Telemetry & Monitoring](/golf-mcp-framework/telemetry-monitoring)). * **`readiness.py`**: Optional custom readiness check endpoint for Kubernetes-style probes (see [Telemetry & Monitoring](/golf-mcp-framework/telemetry-monitoring)). * **`tools/`**: Contains Python files defining your server's tools (see [Component Specification](/golf-mcp-framework/component-specification)). * **`resources/`**: Contains Python files defining data resources the LLM can read (see [Component Specification](/golf-mcp-framework/component-specification)). * **`prompts/`**: Contains Python files defining reusable prompt templates (see [Component Specification](/golf-mcp-framework/component-specification)). **Deprecated:** Authentication configuration in `pre_build.py` is deprecated. Use the dedicated `auth.py` file instead for cleaner organization and better maintainability. ### Component discovery * Each `.py` file within `tools/`, `resources/`, or `prompts/` (and their subdirectories) is treated as a single component. * Files named `__init__.py` are ignored for direct component definition but are essential for Python's packaging if you structure your components as modules. * Files named `common.py` are special and used for shared code (see [Shared Logic documentation](/golf-mcp-framework/shared-logic-common-py)). * The `auth.py` file is treated specially for authentication configuration and is not considered a component. * The `startup.py` file is treated specially for server initialization and is not considered a component. * The `health.py` and `readiness.py` files are treated specially for health check endpoints and are not considered components. ### Component ID derivation The unique ID for each component is derived from its file path relative to the category directory (`tools`, `resources`, `prompts`). **Examples:** * `tools/hello.py` -> ID: `hello` * `tools/payments/transaction/submit.py` -> ID: `submit-transaction-payments` * `resources/weather/current.py` -> ID: `current-weather` ID collisions will result in a build-time error. ## Authentication configuration ### The `auth.py` file (new in v0.2.0) Golf v0.2.0 introduces a dedicated `auth.py` file for authentication configuration, providing better organization and cleaner separation from other build logic. **Example `auth.py` configurations** (for full details, see [Authentication](/golf-mcp-framework/authentication)): ```python theme={null} # auth.py - API Key Authentication from golf.auth import configure_api_key configure_api_key( header_name="Authorization", header_prefix="Bearer " ) ``` ```python theme={null} # auth.py - JWT Authentication from golf.auth import configure_auth, JWTAuthConfig configure_auth( JWTAuthConfig( jwks_uri_env_var="JWKS_URI", issuer_env_var="JWT_ISSUER", audience_env_var="JWT_AUDIENCE", required_scopes=["read:user"] ) ) ``` ```python theme={null} # auth.py - Development Authentication from golf.auth import configure_auth, StaticTokenConfig configure_auth( StaticTokenConfig( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"] } }, required_scopes=["read"] ) ) ``` ## Runtime initialization ### The `startup.py` file (optional) The `startup.py` file is an **optional initialization script** that allows projects to execute custom code before the FastMCP server starts. It's designed for setting environment variables, loading secrets, and performing project-specific setup. **Key characteristics:** * **Optional**: Projects work without it * **Runtime execution**: Runs when the server starts, not during build * **Environment focused**: Primarily used for secrets, API keys, and configuration #### Core implementation The startup script functionality is automatically detected during build and executed at server runtime with robust error handling. #### Common usage patterns **Basic Environment Setup:** ```python theme={null} # startup.py import os os.environ.setdefault("GOLF_DEBUG", "true") os.environ["DATABASE_URL"] = "sqlite:///app.db" print("Startup script executed successfully") ``` **API Key and Secrets Loading:** ```python theme={null} # startup.py import os # Configure API keys os.environ["OPENAI_API_KEY"] = "test-openai-key" os.environ["ANTHROPIC_API_KEY"] = "test-anthropic-key" print("Environment configured successfully") ``` # GolfMCP quickstart Source: https://docs.golf.dev/golf-mcp-framework/quickstart Get started with your first GolfMCP project from scratch. Let's get you started with your first GolfMCP project from scratch. Install the Golf MCP framework using pip: ```bash theme={null} pip install golf-mcp ``` Create a new GolfMCP project using the `init` command: ```bash theme={null} golf init my_awesome_server cd my_awesome_server ``` This will create a new directory named `my_awesome_server` with the following structure: ``` my_awesome_server/ ├── golf.json # Main project configuration ├── auth.py # Authentication configuration (new in v0.2.0) ├── prompts/ # Directory for prompt components │ └── welcome.py ├── resources/ # Directory for resource components │ ├── current_time.py │ └── info.py │ └── weather/ │ ├── common.py │ ├── current.py │ └── forecast.py └── tools/ # Directory for tool components ├── github_user.py ├── hello.py └── payments/ ├── charge.py ├── common.py └── refund.py ``` * **`golf.json`**: Configures your server's name, port, transport, etc. (see [Configuration](/golf-mcp-framework/configuration)) * **`auth.py`**: Dedicated file for authentication setup (see [Authentication](/golf-mcp-framework/authentication)) * **`tools/`**, **`resources/`**, **`prompts/`**: Directories where you'll define your server's capabilities (see [Component Specification](/golf-mcp-framework/component-specification)) The boilerplate example includes a tool that requires authentication. Golf v0.2.0 offers three authentication methods (for complete details, see [Authentication](/golf-mcp-framework/authentication)): 1. **Configure API key authentication** in `auth.py`: ```python theme={null} from golf.auth import configure_api_key # Extract API key from Authorization header configure_api_key( header_name="Authorization", header_prefix="Bearer " ) ``` 2. **Pass the token** when connecting your MCP client 3. **Access the API key in your tools** using: ```python theme={null} from golf.auth import get_api_key api_key = get_api_key() ``` 1. **Configure development tokens** in `auth.py`: ```python theme={null} from golf.auth import configure_auth, StaticTokenConfig configure_auth( StaticTokenConfig( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"] } }, required_scopes=["read"] ) ) ``` 2. **Use the development token** when connecting: ```bash theme={null} # Pass token via Authorization header Authorization: Bearer dev-token-123 ``` 3. **No additional setup required** - perfect for development and testing 1. **Set up your JWT provider** (Auth0, Okta, etc.) 2. **Configure JWT authentication** in `auth.py`: ```python theme={null} from golf.auth import configure_auth, JWTAuthConfig configure_auth( JWTAuthConfig( jwks_uri_env_var="JWKS_URI", issuer_env_var="JWT_ISSUER", audience_env_var="JWT_AUDIENCE", required_scopes=["read:user"] ) ) ``` 3. **Set environment variables**: ```bash theme={null} JWKS_URI=https://your-provider.com/.well-known/jwks.json JWT_ISSUER=https://your-provider.com/ JWT_AUDIENCE=your-api-audience ``` 4. **Enterprise-grade security** with standards-compliant JWT validation Let's modify the example "hello" tool. Open `tools/hello.py`: ```python theme={null} """Hello World tool for {{project_name}}.""" from typing import Annotated from pydantic import BaseModel, Field class Output(BaseModel): """Response from the hello tool.""" message: str async def hello( name: Annotated[str, Field(description="The name of the person to greet")] = "World", greeting: Annotated[str, Field(description="The greeting phrase to use")] = "Hello" ) -> Output: """Say hello to the given name. This is a simple example tool that demonstrates the basic structure of a tool implementation in GolfMCP. """ # The framework will add a context object automatically # You can log using regular print during development print(f"{greeting} {name}...") # Create and return the response return Output(message=f"{greeting}, {name}!") # Designate the entry point function export = hello ``` For more details on tool structure, parameters, and advanced patterns, see the [Component Specification](/golf-mcp-framework/component-specification). Compile your project for development: ```bash theme={null} golf build dev ``` This command builds the actual MCP server. Execute the built server: ```bash theme={null} golf run ``` Congratulations! You've built and run your first GolfMCP server. ## Next Steps Now that you have a working MCP server, learn how to test it comprehensively: * **[Test your server](/mcp-testing/getting-started/quickstart)** - Use mcp-t to validate your implementation * **[Set up automated testing](/mcp-testing/concepts/test-suites)** - Create test suites for CI/CD * **[Learn testing philosophy](/mcp-testing/concepts/testing-philosophy)** - Understand why traditional testing fails for MCP # Shared logic Source: https://docs.golf.dev/golf-mcp-framework/shared-logic-common-py The `common.py` pattern is **deprecated**. Use standard Python module and package structures instead. Multiple components often need to share utility functions, client initializations, or Pydantic models. GolfMCP supports standard Python repository structures for organizing shared code. You can create properly named modules, packages, and organize your code using normal Python conventions. The build system will handle imports correctly regardless of your chosen structure. **Example:** `tools/payments/common.py`: ```python theme={null} # tools/payments/common.py import httpx # Shared HTTP client for payment operations payment_client = httpx.AsyncClient(base_url="https://api.payments.example.com") DEFAULT_CURRENCY = "USD" class PaymentError(Exception): pass # Mock payment processing functions for examples async def create_charge(amount: float, token: str, description: str = "") -> dict: # In a real implementation, this would call the payment API return {"id": f"ch_{token[:8]}", "amount": amount, "currency": DEFAULT_CURRENCY} async def create_refund(charge_id: str, amount: float = None, reason: str = "") -> dict: # In a real implementation, this would call the payment API return {"id": f"re_{charge_id[3:11]}", "charge_id": charge_id, "amount": amount} ``` `tools/payments/charge.py`: ```python theme={null} # tools/payments/charge.py """Tool to process a payment charge.""" from typing import Annotated from pydantic import BaseModel, Field from .common import payment_client, create_charge, PaymentError class ChargeOutput(BaseModel): success: bool charge_id: str message: str async def charge( amount: Annotated[float, Field( description="Amount to charge in USD", gt=0, # Must be greater than 0 le=10000 # Maximum charge limit )], card_token: Annotated[str, Field( description="Tokenized payment card identifier", pattern=r"^tok_[a-zA-Z0-9]+$" # Validate token format )], description: Annotated[str, Field( description="Optional payment description", max_length=200 )] = "" ) -> ChargeOutput: """Process a payment charge.""" try: # Use the shared payment client from common.py charge_result = await create_charge( amount=amount, token=card_token, description=description ) return ChargeOutput( success=True, charge_id=charge_result["id"], message=f"Successfully charged ${amount:.2f}" ) except Exception as e: raise PaymentError(f"Charge failed: {e}") export = charge ``` The GolfMCP build system understands these relative imports and ensures that the `common.py` modules are correctly packaged and accessible in the final `dist/` output. The `ImportTransformer` in `golf.core.transformer` handles rewriting these imports to be absolute paths relative to the generated `components` directory structure. # Telemetry & monitoring Source: https://docs.golf.dev/golf-mcp-framework/telemetry-monitoring Health checks, OpenTelemetry integration, and monitoring capabilities in Golf. Golf provides comprehensive monitoring capabilities including configurable health check endpoints for containerized deployments and OpenTelemetry integration for distributed tracing. ## Health check endpoints **New in v0.2.11**: Golf now supports sophisticated health and readiness check endpoints with custom logic, Kubernetes compatibility, and flexible response formats. Golf provides built-in health check endpoints designed for containerized deployments, Kubernetes health probes, and load balancers. The framework supports both liveness (`/health`) and readiness (`/ready`) endpoints with customizable logic. ### Modern approach (recommended) Create custom health and readiness check files in your project root to implement sophisticated monitoring logic. #### Custom health check Create `health.py` in your project root for liveness probes: ```python theme={null} from starlette.responses import JSONResponse def check(): """Health check function for liveness probe.""" try: # Check critical dependencies database_ok = check_database_connection() external_apis_ok = check_external_apis() if database_ok and external_apis_ok: return JSONResponse( { "status": "pass", "timestamp": "2025-09-26T13:01:10Z", "version": "1.0.0", "services": { "database": "healthy", "external_apis": "healthy" } }, status_code=200 # Healthy - Kubernetes won't restart ) else: return JSONResponse( { "status": "fail", "timestamp": "2025-09-26T13:01:10Z", "error": "Critical services unavailable", "services": { "database": "healthy" if database_ok else "failed", "external_apis": "healthy" if external_apis_ok else "failed" } }, status_code=503 # Unhealthy - Kubernetes will restart container ) except Exception as e: return JSONResponse( { "status": "fail", "timestamp": "2025-09-26T13:01:10Z", "error": f"Health check exception: {str(e)}" }, status_code=503 ) ``` **Generated endpoint**: `GET /health` #### Custom readiness check Create `readiness.py` in your project root for readiness probes: ```python theme={null} from starlette.responses import JSONResponse def check(): """Readiness check function for readiness probe.""" try: # Check if ready to serve traffic (can be more strict than health) database_ready = check_database_connection_pool() cache_ready = check_redis_connection() queue_ready = check_message_queue() if database_ready and cache_ready and queue_ready: return JSONResponse( { "status": "pass", "timestamp": "2025-09-26T13:01:10Z", "services": { "database": "ready", "cache": "ready", "message_queue": "ready" }, "ready_since": "2025-09-26T12:00:00Z" }, status_code=200 # Ready - Kubernetes will send traffic ) else: return JSONResponse( { "status": "fail", "timestamp": "2025-09-26T13:01:10Z", "error": "Services not ready for traffic", "services": { "database": "ready" if database_ready else "not_ready", "cache": "ready" if cache_ready else "not_ready", "message_queue": "ready" if queue_ready else "not_ready" } }, status_code=503 # Not Ready - Kubernetes removes from load balancer ) except Exception as e: return JSONResponse( { "status": "fail", "timestamp": "2025-09-26T13:01:10Z", "error": f"Readiness check failed: {str(e)}" }, status_code=503 ) ``` **Generated endpoint**: `GET /ready` ### Response format options #### 1. JSONResponse with status codes (recommended) ```python theme={null} from starlette.responses import JSONResponse def check(): return JSONResponse( {"status": "pass", "timestamp": "2025-09-26T13:01:10Z"}, status_code=200 # Explicit control over HTTP status ) ``` #### 2. Structured dictionary (auto-converted) ```python theme={null} def check(): return { "status": "pass", # or "fail" "timestamp": "2025-09-26T13:01:10Z", "additional_data": "value" } # Automatically becomes JSONResponse with HTTP 200 ``` ### HTTP status code guidelines **For Kubernetes health probes:** * **HTTP 200**: Service is healthy/ready - continue normal operation * **HTTP 503**: Service is unhealthy/not ready - restart container or remove from load balancer ```python theme={null} # ✅ Healthy - HTTP 200 return JSONResponse({"status": "pass"}, status_code=200) # ❌ Unhealthy - HTTP 503 (triggers restart/removal) return JSONResponse({"status": "fail"}, status_code=503) # ⚠️ Degraded - HTTP 200 (still serving traffic) return JSONResponse({ "status": "pass", "degraded": True, "message": "Running with reduced functionality" }, status_code=200) ``` ### Default behavior When custom files don't exist but health checks are enabled via configuration: * **Readiness endpoint**: `GET /ready` returns `{"status": "pass"}` (HTTP 200) * **Health endpoint**: `GET /health` returns plain text "OK" (configurable) ### Legacy configuration (deprecated) The `golf.json` configuration approach is deprecated in favor of custom `health.py` and `readiness.py` files. This legacy approach will be removed in a future version. ```json theme={null} { "health_check_enabled": true, "health_check_path": "/health", "health_check_response": "OK" } ``` ### Troubleshooting #### Common issues **Files not copied to build:** * Ensure `health.py`/`readiness.py` are in project root, same level as `golf.json` **Import errors:** * Verify files have valid Python syntax and include a `check()` function **Wrong status codes:** * Use `JSONResponse` objects for explicit status code control ## Telemetry Golf introduces comprehensive telemetry capabilities through automatic OpenTelemetry integration and enhanced instrumentation. ## Overview Golf's telemetry system provides: * **OpenTelemetry integration** - Configurable distributed tracing * **Detailed tracing** - For tools, resources, prompts, and Golf utilities * **Input/output capture** - Safe serialization of request and response data * **Configurable detail levels** - Control what gets traced and monitored ## OpenTelemetry configuration ### Basic configuration Configure OpenTelemetry in your `golf.json`: ```json theme={null} { "name": "my-project", "opentelemetry_enabled": true, "opentelemetry_default_exporter": "otlp_http" } ``` ### Detailed tracing (optional) By default, Golf captures basic telemetry like execution timing, success/failure rates, and error information. You can optionally enable detailed tracing to capture input and output data: ```json theme={null} { "name": "my-project", "opentelemetry_enabled": true, "detailed_tracing": true // Enable input/output capture } ``` **What detailed tracing captures:** * **Tool Input/Output** - Function parameters and return values * **Resource Content** - Resource parameters and returned data * **Golf Utilities** - Full elicitation prompts/responses and sampling conversations * **Request Context** - Complete request metadata and session information **Security considerations:** * Detailed tracing may capture sensitive user data * Recommended only for development and testing environments * Uses safe serialization with size limits to prevent issues * Can be disabled in production while keeping basic telemetry active ```json theme={null} // Production configuration - basic telemetry only { "detailed_tracing": false, // Disable for production "opentelemetry_enabled": true // Keep basic telemetry active } ``` ### Advanced configuration For custom telemetry setups, use environment variables: ```bash theme={null} # OTLP HTTP Exporter (recommended) OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces OTEL_SERVICE_NAME=my-mcp-server OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer your-token # Console Exporter (for debugging) OTEL_TRACES_EXPORTER=console ```