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
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
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 ason_behalf_of.Claims["auth_actor"]: The agent that acts for the user, for example theactorazpclaim of the token. The proxy log stores it asacting_agent.- Other
Claims: Other values for audit.
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
401withinvalid 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.
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
4. ResponseHandler
Interface:ResponseHandler
Methods:
OnBeforeWriteHeaders(ctx Context, req *pb.ResponseWriteRequest) (*pb.ResponseWriteResponse, error)OnBeforeWrite(ctx Context, req *pb.ResponseWriteRequest) (*pb.ResponseWriteResponse, error)
- 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
5. DataCollector
Interface:DataCollector
Methods:
HandleProxyLog(ctx Context, log *pb.ProxyLogData) errorHandleAnalytics(ctx Context, analytics *pb.AnalyticsData) errorHandleBudgetUsage(ctx Context, usage *pb.BudgetUsageData) error
- Exporting proxy logs to external systems
- Sending analytics to data warehouses
- Custom budget tracking
- Real-time monitoring and alerting
- examples/plugins/data-collectors/file-analytics-collector/ (unified SDK)
- examples/plugins/data-collectors/file-budget-collector/ (unified SDK)
- examples/plugins/data-collectors/file-proxy-collector/ (unified SDK)
- examples/plugins/gateway/legacy-collectors/elasticsearch_collector/
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
/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
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.
- 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-*andX-RateLimit-*headers that plugins set, on buffered and streamed responses. Other plugin headers stay on the internal hop.
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_SOURCESrefuses - An internal host that is not allowed
- A registry or
grpc://host that the gateway cannot reach
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:
/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 withBasePlugin 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: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.
Configuration Schema
Provide JSON Schema for plugin configuration using theConfigSchemaProvider interface:
config.schema.json:
Expandable
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 asllm-firewall and llm-cache.
Expandable
Example 2: Elasticsearch Data Collector
Expandable
Plugin Context
ThePluginContext provides contextual information about the request:
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 examplegoverned_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 thegoverned_metadataJSON instead.
Testing Your Plugin
Unit Testing
Expandable
Integration Testing
Usefile:// 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
Plugin Not Loading
Plugin Not Loading
- 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_SOURCESand the internal host rules. Refer to Plugin Security. - Check logs for initialization errors
- Ensure plugin implements all required interfaces
Plugin Crashes
Plugin Crashes
- Check plugin logs for panics
- Verify external service connectivity
- Test with minimal configuration
- Use defensive error handling
Performance Issues
Performance Issues
- 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 viactx.Services.Gateway():
Sending Data to Control Plane
Gateway plugins can send data back to AI Studio (the control plane) using theSendToControl 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
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