> ## Documentation Index
> Fetch the complete documentation index at: https://tyk.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Tyk AI Studio Plugin Event Service

> Reference for the plugin Event Service in Tyk AI Studio: event directions, reserved topics, publish and subscribe calls, and the system events that AI Studio emits when objects change.

## Availability

| Edition | Deployment Type |
| :- | :- |
| [Community](https://tyk.io/docs/ai-management/ai-studio/overview.md#community-edition) & [Enterprise](https://tyk.io/docs/ai-management/ai-studio/overview.md#enterprise-edition) | Self-Managed |

The Event Service is available to plugins in AI Studio and on Edge Gateways.

Plugins publish and subscribe to events on the event bus through `ctx.Services.Events()`. An event can stay on one node, or flow between the Edge Gateways and AI Studio. The SDK removes the subscriptions of a plugin when the plugin disconnects. Event subscriptions use the same broker connection as the other services, so warm up the connection first. Refer to [Initialization and Connection Warmup](https://tyk.io/docs/ai-management/ai-studio/plugins/service-api.md#initialization-and-connection-warmup).

## Event Directions

Events have a direction that controls routing:

| Direction | Constant | Description |
| - | - | - |
| Local | `plugin_sdk.DirLocal` | Stays on local bus only, never forwarded |
| Up | `plugin_sdk.DirUp` | Flows from edge (Edge Gateway) to control (AI Studio) |
| Down | `plugin_sdk.DirDown` | Flows from control (AI Studio) to edge(s) |

Topics that start with `system.` are reserved for the object change events of AI Studio. The control plane drops `system.*` events that come from an edge. Gateway plugins must publish events under their own topics.

From Tyk AI Studio 2.3.0, topics that start with `guardrail.alert.` and `guardrail.outcome.` are also reserved. AI Studio raises them for guardrail alerts and for guardrail outcomes: a block, a quarantine or a softening by the judge. The host refuses a plugin publish on these topics, on AI Studio and on an Edge Gateway. A Studio plugin can subscribe to them, with one topic for each subscription:

```go theme={null}
for _, topic := range []string{"guardrail.outcome.blocked", "guardrail.outcome.quarantined", "guardrail.outcome.judge_softened"} {
    ctx.Services.Events().Subscribe(topic, func(ev plugin_sdk.Event) {
        // ev.Payload: {"object_type":"guardrail","action":"blocked","object_id":<compliance event id>,"object":{...}}
    })
}
```

AI Studio raises these events locally (`DirLocal`). For Edge Gateway traffic, it raises them when the analytics pulse of the edge arrives. Gateway plugins do not receive them. For the events, refer to [Guardrails](https://tyk.io/docs/ai-management/ai-studio/guardrails.md).

## Publish Event

Publish an event with a JSON-serializable payload:

```go theme={null}
err := ctx.Services.Events().Publish(ctx, "my.topic", payload, plugin_sdk.DirUp)
```

Example:

```go Expandable expandable theme={null}
// Publish a cache hit event to the local bus only
cacheEvent := map[string]interface{}{
    "key":       "user:123",
    "hit":       true,
    "timestamp": time.Now().Unix(),
}
err := ctx.Services.Events().Publish(ctx, "cache.hit", cacheEvent, plugin_sdk.DirLocal)
if err != nil {
    ctx.Services.Logger().Error("Failed to publish cache event", "error", err)
}

// Publish metrics from edge to control
metrics := map[string]interface{}{
    "requests_per_second": 1500,
    "avg_latency_ms":      25,
    "error_rate":          0.02,
}
err = ctx.Services.Events().Publish(ctx, "metrics.report", metrics, plugin_sdk.DirUp)
```

## Publish Raw Event

Publish an event with pre-serialized JSON payload (avoids double-serialization):

```go theme={null}
err := ctx.Services.Events().PublishRaw(ctx, "my.topic", jsonBytes, plugin_sdk.DirUp)
```

Example:

```go theme={null}
// When you already have JSON bytes
jsonPayload := []byte(`{"status": "ready", "version": "1.0.0"}`)
err := ctx.Services.Events().PublishRaw(ctx, "plugin.status", jsonPayload, plugin_sdk.DirLocal)
```

## Subscribe to Events

Subscribe to events on a specific topic:

```go theme={null}
subscriptionID, err := ctx.Services.Events().Subscribe("my.topic", func(ev plugin_sdk.Event) {
    // Handle event
    fmt.Printf("Received: %s from %s\n", ev.Topic, ev.Origin)
})
```

Example:

```go Expandable expandable theme={null}
// Subscribe to configuration updates
subID, err := ctx.Services.Events().Subscribe("config.updated", func(ev plugin_sdk.Event) {
    ctx.Services.Logger().Info("Configuration updated",
        "event_id", ev.ID,
        "origin", ev.Origin,
    )

    // Parse payload
    var config map[string]interface{}
    if err := json.Unmarshal(ev.Payload, &config); err != nil {
        ctx.Services.Logger().Error("Failed to parse config", "error", err)
        return
    }

    // Apply new configuration
    p.applyConfig(config)
})
if err != nil {
    ctx.Services.Logger().Error("Failed to subscribe", "error", err)
}

// Store subscription ID to unsubscribe later
p.configSubID = subID
```

## Subscribe to All Events

Subscribe to all events regardless of topic:

```go theme={null}
subscriptionID, err := ctx.Services.Events().SubscribeAll(func(ev plugin_sdk.Event) {
    // Handle all events
})
```

Example:

```go theme={null}
// Monitor all events for debugging
subID, err := ctx.Services.Events().SubscribeAll(func(ev plugin_sdk.Event) {
    ctx.Services.Logger().Debug("Event observed",
        "id", ev.ID,
        "topic", ev.Topic,
        "origin", ev.Origin,
        "direction", ev.Dir,
    )
})
```

## Unsubscribe

Remove a subscription:

```go theme={null}
err := ctx.Services.Events().Unsubscribe(subscriptionID)
```

Example:

```go theme={null}
// Clean up subscription in Shutdown
func (p *MyPlugin) Shutdown(ctx plugin_sdk.Context) error {
    if p.configSubID != "" {
        if err := ctx.Services.Events().Unsubscribe(p.configSubID); err != nil {
            ctx.Services.Logger().Warn("Failed to unsubscribe", "error", err)
        }
    }
    return nil
}
```

**Note:** Subscriptions are automatically cleaned up when the plugin process terminates, but it's good practice to explicitly unsubscribe in `Shutdown()`.

## Event Structure

Events have the following fields:

```go theme={null}
type Event struct {
    ID      string           // UUID for deduplication and tracing
    Topic   string           // Logical topic name (e.g., "config.update")
    Origin  string           // Node/plugin that created the event
    Dir     Direction        // Routing direction
    Payload json.RawMessage  // JSON payload
}
```

## Example: Event-Driven Cache Invalidation

```go Expandable expandable theme={null}
package main

import (
    "encoding/json"
    "github.com/TykTechnologies/midsommar/v2/pkg/plugin_sdk"
)

type CachePlugin struct {
    plugin_sdk.BasePlugin
    cache           map[string][]byte
    invalidationSub string
}

func (p *CachePlugin) Initialize(ctx plugin_sdk.Context, config map[string]string) error {
    p.cache = make(map[string][]byte)

    // Subscribe to cache invalidation events from control
    subID, err := ctx.Services.Events().Subscribe("cache.invalidate", func(ev plugin_sdk.Event) {
        var req struct {
            Keys []string `json:"keys"`
        }
        if err := json.Unmarshal(ev.Payload, &req); err != nil {
            return
        }

        for _, key := range req.Keys {
            delete(p.cache, key)
        }

        ctx.Services.Logger().Info("Cache invalidated",
            "keys", len(req.Keys),
            "origin", ev.Origin,
        )
    })
    if err != nil {
        return err
    }
    p.invalidationSub = subID

    return nil
}

func (p *CachePlugin) HandlePostAuth(ctx plugin_sdk.Context, req *pb.EnrichedRequest) (*pb.PluginResponse, error) {
    cacheKey := req.Path

    // Check cache
    if data, ok := p.cache[cacheKey]; ok {
        // Publish cache hit event (local only for metrics)
        ctx.Services.Events().Publish(ctx, "cache.hit", map[string]interface{}{
            "key": cacheKey,
        }, plugin_sdk.DirLocal)

        // Return cached response...
    }

    // Cache miss - continue to upstream
    return &pb.PluginResponse{Modified: false}, nil
}

func (p *CachePlugin) Shutdown(ctx plugin_sdk.Context) error {
    if p.invalidationSub != "" {
        ctx.Services.Events().Unsubscribe(p.invalidationSub)
    }
    return nil
}
```

## Best Practices

1. **Use Appropriate Directions**:
   * `DirLocal` for metrics and debugging within a single node
   * `DirUp` for edge plugins sending data to control
   * `DirDown` for control pushing updates to edges

2. **Handle Payload Parsing Errors**: Always validate and handle JSON unmarshaling errors in event handlers.

3. **Avoid Blocking in Handlers**: Event handlers should be fast. For heavy processing, spawn a goroutine or queue work.

4. **Clean Up Subscriptions**: Unsubscribe in `Shutdown()` for explicit cleanup.

5. **Use Meaningful Topics**: Use dot-separated topic names for clarity (for example, `cache.invalidate`, `config.updated`, `metrics.report`).

6. **Include Context in Payloads**: Add timestamps, correlation IDs, or source info to payloads for debugging.

## System CRUD Events

AI Studio emits a system event when an object is created, updated or deleted. AI Studio publishes these events with `DirLocal`, so they stay on the control plane and do not reach Edge Gateways. Any Studio plugin can subscribe to them.

### Available System Events

Each object type has a `created`, an `updated` and a `deleted` topic, for example `system.llm.created`.

| Object Type | Topic Prefix | Extra Topics |
| :- | :- | :- |
| LLM | `system.llm.` | |
| App | `system.app.` | `system.app.approved` (the App credential is activated), `system.app.plugin_resources.changed`, `system.app.prompt_templates.changed`, `system.app.guardrail_exceptions.changed` |
| Datasource | `system.datasource.` | |
| User | `system.user.` | |
| Group | `system.group.` | |
| Tool | `system.tool.` | |
| Filter | `system.filter.` | |
| Plugin | `system.plugin.` | |
| Model price | `system.model_price.` | |
| Model router | `system.model_router.` | |
| Semantic router | `system.semantic_router.` | |
| Embedder | `system.embedder.` | |
| Secret | `system.secret.` | |
| Governed metadata (Enterprise) | `system.governed_metadata.` | Only `updated` and `deleted` |

The payloads of `system.app.prompt_templates.changed`, `system.app.guardrail_exceptions.changed` and `system.secret.*` carry no object, only the object ID.

### Event Payload Structure

All system CRUD events use a consistent payload structure:

```go theme={null}
type ObjectEventPayload struct {
    ObjectType string      `json:"object_type"`  // "llm", "app", "datasource", "user", "group", "tool"
    Action     string      `json:"action"`       // "created", "updated", "deleted", "approved"
    ObjectID   uint        `json:"object_id"`    // ID of the affected object
    UserID     uint        `json:"user_id"`      // User who performed the action (0 if system/unknown)
    Timestamp  time.Time   `json:"timestamp"`    // When the event occurred
    Object     interface{} `json:"object"`       // The full object (for create/update, nil for delete)
}
```

From Tyk AI Studio 2.3.0, literal credentials in the object show as `[redacted]`:

* `system.llm.*`: the API key, and each metadata value whose name contains `key`, `secret` or `token`, such as the AWS keys of a Bedrock LLM
* `system.tool.*`: the auth key of the tool and of its dependencies
* `system.datasource.*`: the connection string, the connection API key and the embedder key (`embed_api_key`, shown as `[REDACTED]`)
* `system.user.*`: the password hash, the API key, and the session, reset and verification tokens
* `system.filter.*`, and the filters in tool and LLM events: the secret connection values of a guardrail, such as an API key
* `system.app.*`: the gateway key of the App, and the credentials of its LLMs, tools and datasources
* `system.group.*`: the credentials of the members, and of the LLMs, datasources and tools in its catalogs

`$SECRET/` and `$ENV/` references show as written. Other AI Studio replicas read the same payload from the cluster event log.

### Subscribing to System Events

> [!NOTE]
>
> Topics must match exactly. The event bus does not support wildcards, so `Subscribe("system.app.*", ...)` never receives an event. Subscribe to each topic that you need (`system.app.created`, `system.app.updated`, and so on), or use `SubscribeAll` and filter on `ev.Topic`. `SubscribeAll` sends every event on the bus to your handler. Check the topic first, before you decode the payload.

```go Expandable expandable theme={null}
// Subscribe to every event and filter by topic prefix
subID, err := ctx.Services.Events().SubscribeAll(func(ev plugin_sdk.Event) {
    if !strings.HasPrefix(ev.Topic, "system.app.") {
        return
    }
    var payload struct {
        ObjectType string      `json:"object_type"`
        Action     string      `json:"action"`
        ObjectID   uint        `json:"object_id"`
        UserID     uint        `json:"user_id"`
        Timestamp  time.Time   `json:"timestamp"`
        Object     interface{} `json:"object"`
    }

    if err := json.Unmarshal(ev.Payload, &payload); err != nil {
        ctx.Services.Logger().Error("Failed to parse event payload", "error", err)
        return
    }

    ctx.Services.Logger().Info("App event received",
        "action", payload.Action,
        "object_id", payload.ObjectID,
        "user_id", payload.UserID,
    )
})

// Or subscribe to a specific event
subID, err := ctx.Services.Events().Subscribe("system.user.created", func(ev plugin_sdk.Event) {
    // Handle new user creation
})
```

### Example: Audit Log Plugin

```go Expandable expandable theme={null}
package main

import (
    "encoding/json"
    "time"

    "github.com/TykTechnologies/midsommar/v2/pkg/plugin_sdk"
)

type AuditLogPlugin struct {
    plugin_sdk.BasePlugin
    subscriptions []string
}

func (p *AuditLogPlugin) OnSessionReady(ctx plugin_sdk.Context) {
    // Subscribe to all system events
    topics := []string{
        "system.llm.created", "system.llm.updated", "system.llm.deleted",
        "system.app.created", "system.app.updated", "system.app.deleted", "system.app.approved",
        "system.datasource.created", "system.datasource.updated", "system.datasource.deleted",
        "system.user.created", "system.user.updated", "system.user.deleted",
        "system.group.created", "system.group.updated", "system.group.deleted",
        "system.tool.created", "system.tool.updated", "system.tool.deleted",
    }

    for _, topic := range topics {
        subID, err := ctx.Services.Events().Subscribe(topic, func(ev plugin_sdk.Event) {
            p.logAuditEvent(ctx, ev)
        })
        if err != nil {
            ctx.Services.Logger().Error("Failed to subscribe to event", "topic", topic, "error", err)
            continue
        }
        p.subscriptions = append(p.subscriptions, subID)
    }
}

func (p *AuditLogPlugin) logAuditEvent(ctx plugin_sdk.Context, ev plugin_sdk.Event) {
    var payload struct {
        ObjectType string    `json:"object_type"`
        Action     string    `json:"action"`
        ObjectID   uint      `json:"object_id"`
        UserID     uint      `json:"user_id"`
        Timestamp  time.Time `json:"timestamp"`
    }

    if err := json.Unmarshal(ev.Payload, &payload); err != nil {
        return
    }

    // Log to external audit system, KV storage, etc.
    ctx.Services.Logger().Info("AUDIT",
        "object_type", payload.ObjectType,
        "action", payload.Action,
        "object_id", payload.ObjectID,
        "user_id", payload.UserID,
        "timestamp", payload.Timestamp,
    )
}

func (p *AuditLogPlugin) OnSessionClosing(ctx plugin_sdk.Context) {
    for _, subID := range p.subscriptions {
        ctx.Services.Events().Unsubscribe(subID)
    }
}
```
