Skip to main content

Availability

Edge Gateway plugins provide middleware hooks in the LLM proxy request/response pipeline using the Unified Plugin SDK. Use them for custom authentication, request/response transformation, content filtering, and data collection to external systems. All Edge Gateway plugins now use pkg/plugin_sdk. The SDK automatically detects the Edge Gateway runtime. It gives access to universal services (KV storage, logging) and to services specific to the Edge Gateway (app management, budget status).

Plugin Capabilities

Edge Gateway plugins implement one or more of these capability interfaces:

1. PreAuthHandler

Interface: PreAuthHandler Method: HandlePreAuth(ctx Context, req *pb.EnrichedRequest) (*pb.PluginResponse, error) Executes before authentication. Use for:
  • Request validation and early rejection
  • Request enrichment with metadata
  • Header modification
  • Logging and auditing
Working Example: examples/plugins/gateway/request_enricher/

2. AuthHandler

Interface: AuthHandler Method: HandleAuth(ctx Context, req *pb.AuthRequest) (*pb.AuthResponse, error) Replaces App key authentication on the endpoints that it is attached to. Use for:
  • Custom authentication schemes (OAuth, JWT, API keys)
  • Integration with external identity providers
  • Multi-factor authentication
Return Authenticated: true with the AppId that the caller acts as. The gateway treats a response without a valid AppId as a rejection. The gateway uses the grants of that App to decide what the request can reach. You can also return identity information for audit. The gateway records these values with the request:
  • UserId: The user that the call is for, for example the subject of a delegated token. The proxy log stores it as on_behalf_of.
  • Claims["auth_actor"]: The agent that acts for the user, for example the act or azp claim of the token. The proxy log stores it as acting_agent.
  • Other Claims: Other values for audit.
The gateway sends these values to post-auth plugins and custom endpoints. The proxy logs on the App and LLM pages show them as For and Agent. These values are for audit only. The plugin does not decide what the request can reach.

Where Auth Plugins Run

Every endpoint of the Edge Gateway has an ordered list of auth plugins: When an endpoint has auth plugins, the gateway uses only these plugins to authenticate its requests:
  • The gateway asks the plugins in order. The first plugin that authenticates the request wins. Put the plugin that authenticates the most requests first, to make fewer plugin calls.
  • If all plugins refuse the request, the gateway returns 401 with invalid credential. The gateway logs the reason of the plugin, but does not send it to the caller.
  • The gateway refuses App keys on that endpoint. AI Studio OAuth access tokens for MCP still work on tools.
  • If the gateway cannot load any of the attached plugins, it returns 503. It does not use App keys instead.
An endpoint without auth plugins uses App keys as usual.
  • Auth plugin lists apply on Edge Gateways only. The embedded gateway in AI Studio does not run auth plugins. It accepts App keys and refuses plugin tokens on every endpoint. Serve plugin-authenticated traffic through an Edge Gateway. If an endpoint must accept only plugin tokens, do not make the embedded gateway available to its clients.
  • If you deactivate an attached auth plugin, its endpoints accept App keys again. An endpoint is protected only while its plugin is active. To stop access to an endpoint, deactivate the endpoint or remove its grants. Do not remove only its plugin.
  • The auth plugins of an LLM run on /llm/, /ai, /v1, /anthropic, and /router. For an LLM with an auth plugin, clients on these endpoints need tokens that the plugin accepts.
Note: Unified SDK provides credential validation via ctx.Services.Gateway().ValidateCredential()

3. PostAuthHandler

Interface: PostAuthHandler Method: HandlePostAuth(ctx Context, req *pb.EnrichedRequest) (*pb.PluginResponse, error) Executes after authentication. Most common capability for gateway plugins. Use for:
  • Enriching requests with user-specific data
  • Per-user request transformation
  • Access control enforcement
  • Usage quota checks
Working Example: examples/plugins/gateway/request_enricher/

4. ResponseHandler

Interface: ResponseHandler Methods:
  • OnBeforeWriteHeaders(ctx Context, req *pb.ResponseWriteRequest) (*pb.ResponseWriteResponse, error)
  • OnBeforeWrite(ctx Context, req *pb.ResponseWriteRequest) (*pb.ResponseWriteResponse, error)
Modifies LLM responses before returning to client. Two-phase processing:
  • OnBeforeWriteHeaders: Modify response headers
  • OnBeforeWrite: Modify response body
OnBeforeWriteHeaders returns the full header set, and on the Edge Gateway it also runs on streamed responses. OnBeforeWrite runs only on buffered responses. For the rules, refer to ResponseHandler. Use for:
  • Response filtering and content moderation
  • Response transformation and formatting
  • Injecting additional metadata
  • Response validation
Working Example: examples/plugins/gateway/response_modifier/

5. DataCollector

Interface: DataCollector Methods:
  • HandleProxyLog(ctx Context, log *pb.ProxyLogData) error
  • HandleAnalytics(ctx Context, analytics *pb.AnalyticsData) error
  • HandleBudgetUsage(ctx Context, usage *pb.BudgetUsageData) error
Intercepts data before database storage. Use for:
  • Exporting proxy logs to external systems
  • Sending analytics to data warehouses
  • Custom budget tracking
  • Real-time monitoring and alerting
Working Examples:

6. CustomEndpointHandler

Interface: CustomEndpointHandler Methods:
  • GetEndpointRegistrations() ([]*pb.EndpointRegistration, error)
  • HandleEndpointRequest(ctx Context, req *pb.EndpointRequest) (*pb.EndpointResponse, error)
  • HandleEndpointRequestStream(ctx Context, req *pb.EndpointRequest, stream grpc.ServerStreamingServer[pb.EndpointResponseChunk]) error
Registers and serves custom HTTP endpoints under /plugins/{slug}/. Plugins have full control over the response. Use for:
  • Custom APIs (OAuth endpoints, webhooks, health checks)
  • MCP Streamable HTTP proxy servers
  • Protocol-specific proxies
  • Any endpoint that doesn’t fit the LLM/Tool/Datasource model
Supports both unary responses and streaming (SSE) via the stream_response flag on endpoint registrations. Full Guide: Custom Endpoints Guide

Where Request Plugins Run

Pre-auth, post-auth and response plugins run on the /llm/ endpoints, which take requests in the native API of the vendor. The /ai/{slug}, unified /v1, /router/{slug} and /anthropic/{slug} endpoints translate each request into the API of the vendor. Then they send it through an internal /llm/ hop:
  • The plugin chain runs once, on the vendor-native request and response.
  • A failover waterfall makes one attempt on each rung. Each attempt runs the chain again with the same request ID.
  • Auth plugins run once, on the endpoint that the client called. The internal hop runs no auth plugin.
From the internal hop, these items reach the client:
  • Blocks: A plugin block keeps its status and message, in the error format of the endpoint that the client called. A 4xx block does not fail over to the next rung. A 5xx or 429 block fails over.
  • Headers: The gateway passes on the X-Cache*, X-Tyk-Compression*, X-LB-* and X-RateLimit-* headers that plugins set, on buffered and streamed responses. Other plugin headers stay on the internal hop.
Edge Gateways run the plugins of an LLM in the order set in AI Studio. Before Tyk AI Studio 2.3.0, they used the install order.

Plugins on Bedrock

From Tyk AI Studio 2.3.0, every plugin attached to a Bedrock LLM runs on /ai/, /v1, routers and /anthropic/, as for other vendors. Before 2.3.0, only auth plugins ran on these endpoints for Bedrock. A plugin on a Bedrock LLM sees the Bedrock Converse API on every endpoint: To read the model, the streaming flag and the token usage for any vendor, use the SDK helpers plugin_sdk.RequestModel, plugin_sdk.IsStreamingRequest and plugin_sdk.ResponseUsage. Do not parse the bodies yourself. Refer to Reading Model, Streaming and Usage. When a plugin refuses a Bedrock runtime call with a status of 400 or more, the gateway answers in the AWS error format. It sets X-Amzn-ErrorType from the status, for example ThrottlingException for 429, and returns the message of the plugin. AWS SDK clients show this message.

When a Plugin Cannot Be Loaded

From Tyk AI Studio 2.3.0, an Edge Gateway refuses requests to an LLM while one of its pre-auth or post-auth plugins cannot load. The missing plugin can enforce a policy, such as a firewall or a rate limiter. For this reason, the gateway does not run the rest of the chain or forward the request. Before 2.3.0, the gateway skipped every plugin of the LLM and sent the request to the vendor. A load fails for these causes:
  • A missing binary, or a plugin that does not start
  • An unsigned plugin, or a failed signature or transparency log check
  • A source that PLUGINS_ALLOWED_SOURCES refuses
  • An internal host that is not allowed
  • A registry or grpc:// host that the gateway cannot reach
The client gets 503 with Retry-After: 30 and the error code plugin_load_failed. The message names the LLM. It does not name the plugin or the cause:
On /ai/, /v1, /anthropic/ and /router/, the refusal uses the error format of that endpoint. A failover waterfall moves to its next rung. To find the cause, look for this log line on the gateway: Plugin could not be loaded; requests to the LLMs it is attached to are refused until it loads. The gateway logs it once when the failure starts or its cause changes. The health of the plugin is failed. The gateway caches a failed load for 30 seconds and refuses requests during that time. The next request after that time, or a configuration push from AI Studio, tries the load again. Other LLMs on the gateway are not affected. No setting lets requests through without the plugin. Fix the plugin, or detach or deactivate it in AI Studio and push the configuration. Auth plugins follow their own rule: the gateway returns 503 only when it cannot load any of the auth plugins of the endpoint. Refer to Where Auth Plugins Run. A response plugin that cannot load does not stop a response.

Quick Start

1. Project Setup

2. Implement Plugin Structure

Use the unified SDK with BasePlugin convenience struct:
Expandable

3. Implement Capability Interfaces

Implement one or more capability interfaces based on your needs:

PostAuthHandler (Most Common)

Expandable

PreAuthHandler

Expandable

ResponseHandler

Expandable

DataCollector

Expandable

4. Build Plugin

5. Deploy Plugin

Create plugin in AI Studio dashboard or via API:

6. Attach to LLM

Associate the plugin with an LLM to activate it:

7. Attach an Auth Plugin to Other Endpoints

Data sources, tools, Model Routers, Semantic Routers, and custom endpoint plugins have their own ordered list of auth plugins. Set the list in the Authentication plugins section of the detail page in the admin UI, or use the API:
The same GET and PUT .../auth-plugins endpoints exist under /api/v1/tools/{id}, /api/v1/model-routers/{id}, /api/v1/semantic-routers/{id}, and /api/v1/plugins/{id}.
  • You can add only plugins that have the auth hook.
  • An empty list removes all the auth plugins.
  • Edges use the new list after the next configuration push. Edges must run v2.2.1 or later. An older edge still accepts App keys on these endpoints.
For a ready-made auth plugin that accepts tokens from Entra ID, Okta, Auth0, and other OIDC providers, refer to OAuth2 Client Credentials.

Configuration Schema

Provide JSON Schema for plugin configuration using the ConfigSchemaProvider interface:
Example config.schema.json:
Expandable
Configuration values are passed to Initialize() and can be updated via the API.

Complete Examples

Example 1: Custom Authentication Plugin

This example uses the Unified SDK for consistency with other gateway plugins such as llm-firewall and llm-cache.
Expandable
Working Example: See plugins/llm-firewall/ for a production-ready content filtering plugin using this pattern.

Example 2: Elasticsearch Data Collector

Expandable

Plugin Context

The PluginContext provides contextual information about the request:
Use this context for logging, tracing, and per-request customization.

Governed Metadata in the Plugin Context

In the Enterprise Edition, Metadata contains the Governed Metadata fields of the LLM that have Sent to gateways turned on:
  • ctx.Metadata["governed_metadata"] contains all the fields as a JSON string.
  • ctx.Metadata["governed_metadata.<key>"] contains one field, for example governed_metadata.data_classification. A list value is a comma-separated string. AI Studio does not escape commas in list items. If an item can contain a comma, read the governed_metadata JSON instead.
The fields of tools and data sources are in the configuration snapshot, but gateway plugins cannot read them at request time.

Testing Your Plugin

Unit Testing

Expandable

Integration Testing

Use file:// deployment to test with real LLM requests:
Expandable

Best Practices

Performance

  • Keep plugin logic lightweight and fast
  • Use timeouts for external API calls
  • Implement connection pooling for external services
  • Cache frequently accessed data
  • Return early for requests that don’t need processing

Error Handling

  • Log errors with context (request ID, LLM ID, etc.)
  • Return descriptive error messages
  • Don’t panic - return errors properly
  • Implement graceful degradation

Security

  • Validate all configuration inputs
  • Sanitize user-provided data
  • Use secure connections for external services
  • Don’t log sensitive data (tokens, PII)
  • Store credentials as $SECRET/ references in the plugin configuration. Refer to Plugin Configuration and Secrets.
  • Implement rate limiting for external calls

Configuration

  • Provide sensible defaults
  • Use JSON Schema for validation
  • Document all configuration options
  • Support configuration updates without restart

Troubleshooting

  • Check plugin command path is absolute with file://
  • Verify plugin binary has execute permissions
  • For oci://, check the signature and the configured keys (Enterprise Edition)
  • Check PLUGINS_ALLOWED_SOURCES and the internal host rules. Refer to Plugin Security.
  • Check logs for initialization errors
  • Ensure plugin implements all required interfaces
  • Check plugin logs for panics
  • Verify external service connectivity
  • Test with minimal configuration
  • Use defensive error handling
  • Profile plugin with Go profiler
  • Check for blocking operations
  • Monitor external service latency
  • Review resource usage (CPU, memory)

Gateway Services

Gateway plugins have access to Gateway-specific services via ctx.Services.Gateway():
For all Gateway Services, refer to Gateway Services.

Sending Data to Control Plane

Gateway plugins can send data back to AI Studio (the control plane) using the SendToControl API. This is useful for:
  • Aggregating statistics from edge instances
  • Synchronizing state across the hub-and-spoke architecture
  • Sending alerts or notifications to central plugins
Expandable
The control plane plugin receives this data via the EdgePayloadReceiver interface. See Edge-to-Control Communication for complete documentation.

Working with Both Runtimes

Plugins using the unified SDK can work in both Gateway and Studio:
Expandable