events

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2025 License: MIT Imports: 5 Imported by: 0

README

MCPBee Events Package

The events package provides a public API for external tools to publish events to MCPBee's learning system.

Installation

go get mcpbee/pkg/events

Usage

Publishing Tool Events
package main

import (
    "context"
    "log"
    "mcpbee/pkg/events"
)

func main() {
    // Create a publisher
    publisher, err := events.NewRedisPublisher("localhost:6379", "")
    if err != nil {
        log.Fatal(err)
    }
    defer publisher.Close()
    
    // Create and publish a tool execution event
    event := events.NewToolEvent("grep", "search for pattern", "found 5 matches", events.StatusSuccess)
    event.SetProjectID("my-project").
          SetSessionID("session-123").
          SetLanguage("go")
    
    ctx := context.Background()
    if err := publisher.Publish(ctx, event); err != nil {
        log.Printf("Failed to publish event: %v", err)
    }
}
Publishing Error Events
// Create an error event
errorEvent := events.NewErrorEvent("build", "undefined variable: foo")
errorEvent.SetFile("main.go").
           SetMetadata("line", 42)

// Publish the error
publisher.Publish(ctx, errorEvent)

// Later, when the error is fixed, publish a success event
successEvent := events.NewSuccessEvent("build", "go build ./...", "Build successful")
successEvent.SetFile("main.go")

publisher.Publish(ctx, successEvent)

MCPBee will automatically detect the error→fix pattern and learn from it.

Batch Publishing
// Collect multiple events
events := []*events.Event{
    events.NewToolEvent("test", "go test", "PASS", events.StatusSuccess),
    events.NewToolEvent("lint", "golint", "No issues", events.StatusSuccess),
    events.NewToolEvent("build", "go build", "Success", events.StatusSuccess),
}

// Publish as batch for efficiency
publisher.PublishBatch(ctx, events)
Testing with In-Memory Publisher
// Create an in-memory publisher for testing
publisher := events.NewInMemoryPublisher()

// Publish events as normal
event := events.NewToolEvent("test", "input", "output", events.StatusSuccess)
publisher.Publish(ctx, event)

// Retrieve events for assertions
storedEvents := publisher.GetEvents()
if len(storedEvents) != 1 {
    t.Errorf("Expected 1 event, got %d", len(storedEvents))
}

Event Types

  • tool_executed: A tool was executed with input and produced output
  • error: An error occurred during tool execution
  • success: A tool completed successfully
  • warning: A tool completed with warnings

Event Status

  • success: Tool completed without errors
  • error: Tool failed with an error
  • warning: Tool completed but with warnings
  • pending: Tool execution is in progress

Metadata

Events support arbitrary metadata through the SetMetadata method. Common metadata fields include:

  • project_id: The project context
  • session_id: The session identifier
  • user_id: The user identifier
  • language: Programming language context
  • file: File being operated on
  • line: Line number in file
  • framework: Framework being used

Integration with MCPBee

When events are published to MCPBee, they are processed by the ProactiveSuggestionEngine which:

  1. Detects Patterns: Identifies recurring tool usage patterns
  2. Learns Error→Fix Mappings: Tracks how errors are resolved
  3. Generates Suggestions: Creates proactive suggestions based on context
  4. Creates Dynamic Tools: Registers new MCP tools for learned patterns
  5. Stores Knowledge: Persists learnings to the knowledge base

Stream Key

By default, events are published to the claude:tool_events Redis stream. You can customize this:

publisher, err := events.NewRedisPublisher("localhost:6379", "my:custom:stream")

Error Handling

Always check for errors when publishing:

if err := publisher.Publish(ctx, event); err != nil {
    // Handle error - maybe retry or log
    log.Printf("Failed to publish: %v", err)
}

Best Practices

  1. Include Context: Always set project_id and session_id when available
  2. Batch When Possible: Use PublishBatch for multiple related events
  3. Be Specific: Provide detailed input/output for better pattern learning
  4. Track Errors: Always publish both error and success events for the same operation
  5. Add Metadata: Include relevant context like file, line, language

Example: VS Code Extension

const redis = require('redis');
const client = redis.createClient();

// When a command is executed
function onCommandExecuted(command, input, output, success) {
    const event = {
        type: 'tool_executed',
        tool: command,
        input: input,
        output: output,
        status: success ? 'success' : 'error',
        timestamp: Date.now() / 1000,
        metadata: JSON.stringify({
            project_id: workspace.name,
            session_id: sessionId,
            language: detectLanguage()
        })
    };
    
    client.xadd('claude:tool_events', '*', ...Object.entries(event).flat());
}

Contributing

The events package is designed to be language-agnostic. Contributions for client libraries in other languages are welcome!

Documentation

Overview

Package events provides the public API contract for publishing events to MCPBee

Index

Constants

View Source
const (
	EventTypeToolExecuted = "tool_executed"
	EventTypeError        = "error"
	EventTypeSuccess      = "success"
	EventTypeWarning      = "warning"
)

EventType constants for common event types

View Source
const (
	StatusSuccess = "success"
	StatusError   = "error"
	StatusWarning = "warning"
	StatusPending = "pending"
)

Status constants for event status

Variables

This section is empty.

Functions

This section is empty.

Types

type Event

type Event struct {
	Type      string                 `json:"type"`      // Event type: "tool_executed", "error", "success"
	Tool      string                 `json:"tool"`      // Tool name
	Input     string                 `json:"input"`     // Input provided to the tool
	Output    string                 `json:"output"`    // Output received from the tool
	Status    string                 `json:"status"`    // Status: "success", "error", "warning"
	Error     string                 `json:"error"`     // Error message if status is "error"
	Metadata  map[string]interface{} `json:"metadata"`  // Additional metadata
	Timestamp time.Time              `json:"timestamp"` // When the event occurred
}

Event represents a tool execution event that can be published to MCPBee

func NewErrorEvent

func NewErrorEvent(tool, errorMsg string) *Event

NewErrorEvent creates a new error event

func NewEvent

func NewEvent(eventType, tool string) *Event

NewEvent creates a new event with the specified type and tool

func NewSuccessEvent

func NewSuccessEvent(tool, input, output string) *Event

NewSuccessEvent creates a new success event

func NewToolEvent

func NewToolEvent(tool, input, output string, status string) *Event

NewToolEvent creates a new tool execution event

func (*Event) SetFile

func (e *Event) SetFile(file string) *Event

SetFile sets the file context in metadata

func (*Event) SetLanguage

func (e *Event) SetLanguage(language string) *Event

SetLanguage sets the programming language in metadata

func (*Event) SetMetadata

func (e *Event) SetMetadata(key string, value interface{}) *Event

SetMetadata adds metadata to the event

func (*Event) SetProjectID

func (e *Event) SetProjectID(projectID string) *Event

SetProjectID sets the project ID in metadata

func (*Event) SetSessionID

func (e *Event) SetSessionID(sessionID string) *Event

SetSessionID sets the session ID in metadata

func (*Event) SetUserID

func (e *Event) SetUserID(userID string) *Event

SetUserID sets the user ID in metadata

type InMemoryPublisher

type InMemoryPublisher struct {
	// contains filtered or unexported fields
}

InMemoryPublisher is a simple in-memory publisher for testing

func NewInMemoryPublisher

func NewInMemoryPublisher() *InMemoryPublisher

NewInMemoryPublisher creates a new in-memory publisher

func (*InMemoryPublisher) Clear

func (imp *InMemoryPublisher) Clear()

Clear removes all stored events (for testing)

func (*InMemoryPublisher) Close

func (imp *InMemoryPublisher) Close() error

Close is a no-op for in-memory publisher

func (*InMemoryPublisher) GetEvents

func (imp *InMemoryPublisher) GetEvents() []*Event

GetEvents returns all stored events (for testing)

func (*InMemoryPublisher) Publish

func (imp *InMemoryPublisher) Publish(ctx context.Context, event *Event) error

Publish stores the event in memory

func (*InMemoryPublisher) PublishBatch

func (imp *InMemoryPublisher) PublishBatch(ctx context.Context, events []*Event) error

PublishBatch stores multiple events in memory

type Publisher

type Publisher interface {
	// Publish sends an event to MCPBee for processing
	Publish(ctx context.Context, event *Event) error

	// PublishBatch sends multiple events to MCPBee
	PublishBatch(ctx context.Context, events []*Event) error

	// Close closes the publisher connection
	Close() error
}

Publisher is the interface for publishing events to MCPBee

type RedisPublisher

type RedisPublisher struct {
	// contains filtered or unexported fields
}

RedisPublisher publishes events to Redis streams

func NewRedisPublisher

func NewRedisPublisher(redisAddr string, streamKey string) (*RedisPublisher, error)

NewRedisPublisher creates a new Redis-based event publisher

func (*RedisPublisher) Close

func (rp *RedisPublisher) Close() error

Close closes the Redis connection

func (*RedisPublisher) Publish

func (rp *RedisPublisher) Publish(ctx context.Context, event *Event) error

Publish sends an event to the Redis stream

func (*RedisPublisher) PublishBatch

func (rp *RedisPublisher) PublishBatch(ctx context.Context, events []*Event) error

PublishBatch sends multiple events to the Redis stream

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL