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, which automatically detects the Gateway runtime and provides access to universal services (KV storage, logging) and Gateway-specific services (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
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
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. From v2.2.1, 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
From v2.2.1, 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
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)
- OnBeforeWriteHeaders: Modify response headers
- OnBeforeWrite: Modify response body
- Response filtering and content moderation
- Response transformation and formatting
- Injecting additional metadata
- Response validation
examples/plugins/gateway/response_modifier/
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
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
From v2.2.1, 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 likellm-firewall and llm-cache.
Expandable
plugins/llm-firewall/ for a production-ready content filtering plugin using this pattern.
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)
- 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
- 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