Availability
Tyk AI Studio provides a Unified Plugin SDK that works seamlessly in both AI Studio and Edge Gateway contexts with a single API. This guide covers the core SDK concepts, capabilities, and patterns.
Unified SDK Overview
The Unified SDK (pkg/plugin_sdk) is the modern, recommended approach for all plugin development. It provides:
- Single Import: One SDK works in both AI Studio and Edge Gateway
- Automatic Runtime Detection: SDK detects the execution environment
- Capability-Based Design: Implement only what you need
- Type-Safe: Clean Go types, no manual proto handling
- Service Access: Built-in KV storage, logging, events, and management APIs
- Context-Rich: Access to app, user, LLM metadata in every call
Installation
go 1.26.5 directive with toolchain go1.26.6. Build plugins with Go 1.26.6 or later. If your plugin module uses a replace directive for the AI Studio module, update its go directive to match.
Changes for Go plugin authors in 2.3.0:
- Rebuild request-path plugins (
pre_auth,auth,post_auth) on the 2.3.0 SDK. Refer to Message Size Limit. - Use the new helpers
RequestModel,IsStreamingRequestandResponseUsageto read requests and responses in the format of each vendor, Bedrock included. Refer to Reading Model, Streaming and Usage. - The module graph of the SDK resolves from the public Go proxy. If you added a placeholder
replacedirective forgithub.com/TykTechnologies/ai-studio-enterprise/v2to yourgo.mod, remove it after you upgrade the SDK. You do not need to rebuild existing binaries for this change. - The host refuses Service API calls outside the approved scopes. Refer to Scopes and Administrator Approval.
- Plugins do not inherit the host environment. Refer to Plugin Environment.
Basic Plugin Structure
Expandable
Plugin Capabilities
Plugins implement one or more capability interfaces. The SDK supports 15 distinct capabilities:Multi-Capability Plugins
A single plugin can implement multiple capabilities. For example, a rate limiter can implement these capabilities:PostAuthHandler- Check limits before requestResponseHandler- Update counters after responseUIProvider- Provide management UI
Expandable
Core Interfaces
1. PreAuthHandler
Process requests before authentication. Useful for IP filtering, request validation, etc.2. AuthHandler
Custom authentication with credential lookup. This interface requires three methods to fully integrate with the access control system.Why App Linking Is Critical
A valid credential alone is not enough. The system requires an associated App object because Apps provide the access control context:- Policy enforcement - Rate limits, usage quotas, and restrictions
- Tool/Datasource permissions - Which tools and datasources the credential can access
- LLM restrictions - Which LLMs the credential is allowed to use
- Budget controls - Cost tracking and spending limits
Authentication Flow
HandleAuth()- Validates the credential and returns an App ID and User IDGetAppByCredential()- System calls this to fetch the full App object for access controlGetUserByCredential()- System calls this to fetch the User object for identity context
Example Implementation
Expandable
Delegated Identity
ReturnAuthenticated: true with the AppId that the caller acts as. The gateway refuses an authenticated response without a valid AppId.
You can also set these values for audit:
UserId: The user that the call is for. For example, the subject of a delegated token.Claims["auth_actor"]: The agent that acts for the user, for example theactorazpclaim of the token
on_behalf_of and acting_agent in the proxy log and chat record. The App and LLM proxy logs show them as For and Agent. They are for audit only. The grants of the App control what the request can reach.
Where Auth Plugins Run
Every gateway endpoint has an ordered list of auth plugins:- When an endpoint has auth plugins, only these plugins authenticate its requests. The gateway asks them in order, and the first plugin that authenticates the request wins. Each plugin that refuses adds its time to the request, so put the plugin that accepts most requests first. If all plugins refuse, the request gets
401 invalid credential. The gateway logs the plugin’s reason, but does not send it to the caller. - The endpoint refuses App keys. Studio OAuth access tokens for MCP still work on tools.
- If none of the attached plugins can load, the request gets
503. The gateway does not fall back to App keys. - An endpoint without auth plugins authenticates with App keys, and no auth plugin sees its traffic.
- Auth plugin lists apply on Edge Gateways only. The embedded gateway in AI Studio does not run gateway auth plugins.
Common Pitfalls
See the working example at
examples/plugins/studio/custom-auth-ui/ for a complete implementation.
3. PostAuthHandler
Process requests after authentication. Most common capability for request enrichment, policy enforcement, etc.Expandable
4. ResponseHandler
Modify response headers and body. Two methods allow phased processing:Expandable
OnBeforeWriteHeadersreturns the full header set. The host removes a header that the plugin leaves out.- On the Edge Gateway,
OnBeforeWriteHeadersalso runs on streamed responses, before the first event. It has 2 seconds. After that time, the stream goes out with the upstream headers. - On a stream, the plugin cannot change
Content-Type,Content-LengthorTransfer-Encoding. OnBeforeWriteruns only on buffered responses.- The
LLMSlugof the context is the route slug of the LLM, as inHandlePostAuth.
5. DataCollector
Collect telemetry data (analytics, budgets, proxy logs).Expandable
6. AgentPlugin
Conversational AI agent with streaming support. See Agent Plugins Guide for details.7. ObjectHookHandler
Intercept CRUD operations on AI Studio objects (LLMs, Datasources, Tools, Users). See Object Hooks Guide for complete details.llm, datasource, tool, user, and (Enterprise Edition) governed_metadata. For governed_metadata:
- The object JSON is the metadata record (
object_type,object_id,values, and so on). - Only
before_update,after_update,before_delete, andafter_deletefire. - A rejection blocks the metadata save.
- A modification can change
values. AI Studio validates the new values against the schema again.
8. UIProvider
Serve web UI assets for AI Studio plugins. See UI Plugins Guide for details.UserAwareRPCHandler. The user context includes the RBAC permissions of the caller:
plugin:<manifest id>: read, write, execute). To declare more rows and the permission of each method, use the rbac block of the manifest. To register resources at runtime, use RegisterPermissionResources. Refer to Permissions (RBAC) Block and Permission Resources.
9. ConfigProvider
Provide JSON Schema for plugin configuration.Expandable
10. ManifestProvider
Provide plugin manifest for gateway-only plugins (no UI).11. SchedulerPlugin
Execute tasks on cron-based schedules.12. EdgePayloadReceiver
Receive data from edge (Edge Gateway) plugins. This enables the hub-and-spoke communication pattern where edge plugins can send data back to the control plane. See Edge-to-Control Communication for complete details.Expandable
Context and Services
Every handler receives aContext that provides access to runtime information and services.
Context Fields
Runtime Detection
Plugins can adapt behavior based on runtime:Reading Model, Streaming and Usage
Vendors put the model, the streaming flag and the token usage in different places. For example, a Bedrock Converse body has nomodel field, because the model ID is in the path. Bedrock streams by path (converse-stream), and reports usage in camelCase. From Tyk AI Studio 2.3.0, the SDK has helpers that read these values for every vendor. Pass ctx.Vendor and the path and body that the hook received:
The helpers are plain functions in your plugin binary. They do not call the host, so they work on any host version.
Model and Stream Metadata
From Tyk AI Studio 2.3.0, the Edge Gateway also sets two keys inctx.Metadata on post-auth calls and on each response hook call, for every vendor:
Hosts before 2.3.0 do not set these keys. If your plugin must run on older hosts, use the helpers above.
Request Kind (Decision Models)
ctx.RequestKind is "decision" when the request goes to a decision model, and empty for chat, completion and embedding traffic. ctx.IsDecision() tests it.
- Decision bodies are not chat-shaped. To read them, use
plugin_sdk.ParseDecisionRequest(path, body)andplugin_sdk.ParseDecisionResponse(body, req). - A Studio agent plugin can call a decision model through the governed gateway path with
plugin_sdk.CallDecision(ctx, llmID, req). This call needs thellms.proxyscope. - Data collectors receive
request_kind,decision_questionsanddecision_refusalson each analytics record.
Service Broker
The context provides access to services throughctx.Services:
Universal Services (Both Runtimes)
KV Storage:- Studio: PostgreSQL-backed, shared across hosts, durable
- Gateway: Local database, per-instance, ephemeral
Expandable
- Events enable real-time communication between plugins and across the hub-spoke architecture
- Direction controls routing:
DirLocal(stays local),DirUp(edge→control),DirDown(control→edge) - See Event Service for complete documentation
Runtime-Specific Services
Gateway Services (ctx.Services.Gateway()):
Expandable
ctx.Services.Studio()):
Expandable
Initialization Pattern
Plugins should extract the service broker ID during initialization for Service API access:Expandable
BasePlugin Convenience Struct
The SDK providesBasePlugin to reduce boilerplate:
Expandable
BasePlugin provides default implementations for common methods, which you can override as needed.
Message Size Limit
Each hook call is one gRPC message between the host and your plugin. ForHandlePostAuth, the message holds the request body, the headers and the context. For OnBeforeWrite, it holds the complete buffered response. For OnStreamComplete, it holds the accumulated stream and the request body.
From Tyk AI Studio 2.3.0, plugin_sdk.Serve accepts messages up to 64 MiB. When the administrator sets PLUGIN_GRPC_MAX_MSG_BYTES on the host, the plugin uses that value.
Plugins built on an SDK before 2.3.0 accept only 4 MiB. Rebuild request-path plugins (pre_auth, auth, post_auth) on the 2.3.0 SDK. For what the gateway does with larger messages, refer to Plugin Message Size.
Error Handling
Blocking Requests
Return a response withBlock: true:
StatusCode, Headers, and Body, for example for a cache hit. The gateway sets Content-Length and Transfer-Encoding from the body that it writes, and ignores the plugin’s values for these headers. It also ignores the connection headers (Connection, Keep-Alive, Trailer, and Upgrade). Set Content-Type to match the body.
Non-Blocking Errors
Log the error and continue:Agent Errors
Send ERROR chunks for streaming agents:Complete Example: Multi-Capability Plugin
Expandable
Testing Plugins
Unit Testing
Expandable
Integration Testing
See working examples in examples/plugins/ for integration test patterns.Best Practices
Configuration
- Validate configuration in
Initialize() - Extract broker ID for Service API access
- Set sensible defaults
- Return errors for invalid config
Service API Usage
- Always check runtime before calling runtime-specific services
- Use context timeouts for external calls
- Cache frequently accessed data in KV storage
- Handle service errors gracefully
- Use Events for cross-plugin and edge-to-control communication
- Unsubscribe from events in
Shutdown()to prevent leaks
Performance
- Minimize Service API calls in request path
- Use KV storage for caching
- Avoid blocking operations in handlers
- Use goroutines for async work (clean up in Shutdown)
Resource Management
- Clean up resources in
Shutdown()method - Close connections and file handles
- Cancel background goroutines
- Clear caches
Security
- Validate all inputs
- Sanitize log output (no secrets)
- Read credentials from
$SECRET/references in the plugin configuration. Refer to Plugin Configuration and Secrets. - Document each host environment variable that your plugin reads. The administrator must add it to
PLUGIN_ENV_PASSTHROUGH. - Use secure defaults
- Follow least privilege principle
Session-Based Broker Pattern
Plugins running in AI Studio use a session-based broker pattern for Service API access. Understanding this pattern is critical for plugins that call host APIs (such asai_studio_sdk.CreateLLM(), ai_studio_sdk.ListApps(), etc.).
How It Works
- Plugin loads: The host creates a long-lived gRPC broker connection
- Session opens: The host calls
OpenSessionon the plugin, providing the broker ID - OnSessionReady callback: For plugins implementing
SessionAware, this signals the broker is ready - Service API available: The plugin can now dial the broker and call host APIs
The SessionAware Interface
Plugins that need early access to Service APIs should implementSessionAware:
Connection Warmup Pattern (Critical!)
Important: The go-plugin broker only accepts ONE connection per broker ID. If your plugin uses both the Event Service and the Management Service API, whichever dials first will succeed, and the connection must be shared. The SDK handles this automatically, but you should warm up the connection early inOnSessionReady to ensure it’s established before any RPC calls come in:
Expandable
Why Warmup Is Important
Without warmup, you may encounter “timeout waiting for connection info” errors when your plugin tries to use the Service API during an RPC call. This happens because:- The broker connection is time-sensitive
- Dialing late (during RPC) may fail if the broker has timed out
- Event subscriptions and Service API calls share the same connection
Complete Example: Plugin with Service API and Events
Expandable
Troubleshooting Connection Issues
Error: “timeout waiting for connection info”- Plugin is trying to dial the broker too late
- Solution: Implement
SessionAwareand warm up the connection inOnSessionReady
- The broker ID wasn’t extracted from config
- Solution: The SDK handles this automatically via
OpenSession, but verify your plugin isn’t overriding the broker setup
ai_studio_sdk.Initialize()wasn’t called or failed- Solution: Check logs for initialization errors during plugin startup