plugin

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT, MIT Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

plugin-sdk

Go Reference

The plugin contract, in two halves. A universal Go SDK for building plugins that talk to a host application over JSON-RPC stdio, and a TypeScript companion (ts/) for both the browser registry/loader and a TS server SDK (@hollis-labs/plugin-sdk) running the same stdio contract on Node 22+ and Deno.

Both halves are host-neutral: neither has a dependency on any specific host product, and host applications extend them with their own registration surfaces in their own packages. They live in one repository so the registry wire contract is defined once, with a Go view and a TypeScript view of the same thing.

Status

Pre-1.0 (v0.x). The wire protocol (subprocess.ProtocolVersion = 2) and exported interfaces are stable in practice but the API may still shift between minor versions; treat any minor bump as potentially breaking and read the CHANGELOG before upgrading. Patch bumps (v0.x.y) are documentation, examples, and internal hardening only.

Install

go get github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk

What's in the box

  • The Plugin contract and core base types (Host, CRUDHandler, EventHook, UIComponent, Connector, ConfigFieldDef).
  • Typed plugin errors (Error / PluginError) with HTTP-friendly status codes, and the ErrCancelled sentinel for pre-hook cancellation.
  • EnvelopeOut / MessageOut wire types for envelope emission.
  • subprocess — JSON-RPC 2.0 wire protocol, subprocess.Serve entry point (handles stdin/stdout, dispatch, concurrency, panic recovery, signal-driven shutdown), capability interfaces (CommandHandler, EventHandler, CRUDHandler, MCPHandler, HTTPHandler, Migrator, HealthChecker, IdentityAware), config / data / cache helpers, and a stderr JSON-lines logger with secret redaction. An optional, opaque Identity value rides through InitParams/CommandExecParams/EventHandleParams/MCPCallRequest/ HTTPRequest unparsed — plugin-sdk carries it, never verifies it.
  • subprocess.CapabilityRequest and InitParams.Grants — a capability declaration mechanism with an open vocabulary: a plugin declares what ambient access it needs, and the host reports back what it allowed. The SDK validates grant structure; descriptor policy and execution enforcement belong to the host. See docs/security-model.md.
  • capability — shared descriptors, exact scope narrowing, typed host failures and strict Grant/RuntimeIdentity DTOs. capability/host owns non-plugin scoped credentials, selective revocation and payload-free audit helpers. Hosts supply authentication and reviewed policy; see host credentials. Host-owned opaque descriptors and opt-in acknowledged discovery renewal are documented in grant scopes and renewal.
  • subprocess/subprocesstest — in-process test harness for driving plugins without spawning a real subprocess, with optional JSON roundtripping to catch wire-format bugs.
  • manifest — a shared subprocess declaration with host extension objects, config/secrets, capabilities, tools, hooks, server/UI artifacts and inclusive host/engine ranges. It requires protocol 2, as does Serve. Its dependency-free encoder emits JSON for plugin.yaml; decoding rejects legacy dialects, unknown fields and duplicate keys. Helpers check semantic version bounds and verify immutable bundle inventories. See the manifest contract.
  • registry — the Go view of the plugin registry wire contract: the registry-v2 catalog of owner-qualified declarative, component, and handler contributions, with host kind/region admission, runtime and digest verification, revision publication, and reverse-order disposal scopes. See the registry wire and lifecycle contract.
  • ts/packages/plugin-sdk — zero-runtime-dependency Node/Deno stdio runtime, capability interfaces, config and redacting logger, plus the /test harness. See the server package and the protocol 2 handshake.
  • ts/packages/plugin-registry — @hollis-labs/plugin-registry, the browser half. The TypeScript view of the same contract, and a loader that dynamic-imports each plugin's ES module, resolves the named exports the registry names, and isolates load failures per plugin. The core entry point has no dependencies; @hollis-labs/plugin-registry/react adds the React adapter behind an optional peer.

Quickstart

A minimum-viable plugin is roughly fifty lines:

package main

import (
    "context"
    "os"

    "github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk/subprocess"
)

type hello struct{}

func (hello) Init(ctx context.Context, p subprocess.InitParams) (subprocess.InitResult, error) {
    return subprocess.InitResult{
        ID:       "hello",
        Name:     "Hello",
        Version:  "0.1.0",
        Protocol: subprocess.ProtocolVersion,
        CapabilityContract: 1,
    }, nil
}

func (hello) Load(ctx context.Context) (subprocess.LoadResult, error) {
    return subprocess.LoadResult{}, nil
}

func (hello) Unload(ctx context.Context) error { return nil }

func (hello) Command(ctx context.Context, req subprocess.CommandRequest) (subprocess.CommandResult, error) {
    return subprocess.CommandResult{Action: "message", Content: "hello, " + req.Args}, nil
}

func main() {
    if err := subprocess.Serve(hello{}); err != nil {
        os.Exit(1)
    }
}

A runnable copy lives at examples/hello/. Build it with go build -o hello ./examples/hello; the examples/hello/hello_test.go file demonstrates exercising the same plugin in-process via the test harness.

Layout

github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk
├── doc.go                 package-level overview
├── plugin.go              Plugin, Host, CRUDHandler, EventHook, UIComponent, ...
├── errors.go              Error type, sentinels, constructors
├── envelope.go            EnvelopeOut, MessageOut
├── logger.go              Logger interface
├── docs/
│   ├── security-model.md  trust boundary, guarantees, and the seams
│   ├── best-practices.md  patterns, with worked examples
│   └── proposals/         open design proposals
├── examples/
│   └── hello/             minimum-viable subprocess plugin
└── subprocess/
    ├── protocol.go        JSON-RPC 2.0 wire types, methods, error codes
    ├── types.go           Init / Load / Command / Event / CRUD / MCP / HTTP / Migrate wire types
    ├── types_sdk.go       SDK-level Go types and capability interfaces
    ├── server.go          subprocess.Serve entry point
    ├── config.go          ConfigReader (with secret redaction integration)
    ├── data.go            DataHelper, CacheHelper
    ├── log.go             stderr JSON-lines logger
    └── subprocesstest/
        └── harness.go     in-process test harness

The TypeScript packages, an npm workspace nested one level down so Go tooling and node_modules/ stay out of each other's way:

ts/
├── package.json           private workspace root
└── packages/
    ├── plugin-sdk/        @hollis-labs/plugin-sdk (server runtime and /test harness)
    └── plugin-registry/   @hollis-labs/plugin-registry
        └── src/
            ├── types.ts        the wire contract, TypeScript view
            ├── loader.ts       createPluginRegistry
            ├── stylesheets.ts  the stylesheet sink and its default
            └── react.ts        the React adapter (optional peer)

Security model and best practices

Two documents for anyone building against this SDK:

  • docs/security-model.md — the trust boundary, what the SDK guarantees (panic isolation, credentials that do not travel in the environment, secret redaction in the logger, a pinned wire protocol), what it deliberately leaves to the host (authentication, sandboxing, resource limits, authorization, output filtering), and the seams where those guarantees stop.
  • docs/best-practices.md — patterns that hold up, with worked examples from hosts and plugins built on this SDK.

The one-line version, if you read nothing else: whatever your plugin returns is published — to a terminal, a log, an HTTP response, or an AI model's context window. Never return a vendor SDK type; map it onto your own, treat that mapping as an allow-list, and test that a credential field cannot appear in the output.

Open proposals live in docs/proposals/.

Versioning

Independent release cycle. Consumers pin a tagged version via go.mod. See CHANGELOG.md for per-release notes.

Testing

go test ./...

Both TypeScript packages build and test with npm, from ts/:

cd ts && npm install
npm run typecheck
npm test

For wire-format fidelity, enable JSON roundtripping in the harness so every request and response is marshaled + unmarshaled before the plugin sees it:

PLUGIN_SDK_JSON_ROUNDTRIP=1 go test ./...

The legacy NANITE_PLUGIN_SDK_JSON_ROUNDTRIP env var name is still honored for backward compatibility but is deprecated; prefer PLUGIN_SDK_JSON_ROUNDTRIP in new configurations.

License

MIT — see LICENSE.

HTTP hosts can populate HTTPRequest.RawPath and RawQuery from net/url.URL to preserve escaped path separators and the full query through http/handle. Plugins can parse RawQuery with url.ParseQuery to retain repeated and empty values instead of relying on a scalar query projection. These fields carry URL data; they do not verify a caller or grant route ownership.

SDK log redaction

Go Config.Secret registers values with the connection's existing secret tracker. SDK JSON-line logging redacts registered values in message text, nested data, custom JSON output, and canonical base64 (including JSON-encoded byte slices). Overlapping values match longest first. Registration precedes exposure of a secret; logging an unregistered value cannot redact it.

Go log records are bounded to 64 KiB of JSON, 128 field pairs, 4,096 values and 128 nesting levels. Oversized, cyclic, invalid or unserializable records emit a sanitized fallback with redacted message text and no raw marshal error. A secret snapshot that exceeds its bounded pattern budget drops fields and masks the message instead of using a partial snapshot. Keys in Go field pairs must be strings. SDK bounds cannot preempt author MarshalJSON code. Redaction covers SDK logging, not direct stderr/printf writes or arbitrary transformed encodings.

Request-scoped host service helpers are defined in the host client contract. Go authors obtain the SDK-owned HostClient from subprocess.HostClientFromContext; TypeScript authors use optional Context.host. Explicit ServeOptions.ReverseRPC / reverseRPC opt-in plus a valid host offer and Init acknowledgement enables bound request-scoped clients; base and hook handlers expose none. See negotiation and its merge gate.

Documentation

Overview

Package plugin defines the universal plugin SDK surface that both a host application and its plugins import.

The package is host-neutral: it has zero dependencies on any specific product code path. A host extends the base contract here with host-specific registration methods in its own public package; a plugin imports this package directly.

Layout:

  • github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk Plugin, Host, CRUDHandler, EventHook, UIComponent, errors, EnvelopeOut/MessageOut, Logger.

  • github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk/subprocess Subprocess server library (Serve), JSON-RPC 2.0 wire protocol, plugin-side capability interfaces (CommandHandler, EventHandler, MCPHandler, HTTPHandler, Migrator, ...), and stderr JSON-lines logging.

  • github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk/subprocess/subprocesstest In-process test harness for driving plugins without spawning a subprocess.

See the examples directory for runnable plugins, and the README for versioning and release status.

Index

Constants

This section is empty.

Variables

View Source
var ErrCancelled = errors.New("plugin: action cancelled by hook")

ErrCancelled is returned by an EventHook's Handle method to signal that the pre-hook action should be cancelled. Only meaningful for pre-hook events (e.g., message.sending, tool.executing). Regular post-events ignore this value.

Functions

This section is empty.

Types

type CRUDHandler

type CRUDHandler interface {
	Create(ctx context.Context, resource interface{}) (interface{}, error)
	Read(ctx context.Context, id string) (interface{}, error)
	Update(ctx context.Context, id string, resource interface{}) (interface{}, error)
	Delete(ctx context.Context, id string) error
	List(ctx context.Context, filters map[string]interface{}) ([]interface{}, error)
}

CRUDHandler defines CRUD operations for plugin-provided resources.

type ConfigFieldDef

type ConfigFieldDef struct {
	Key         string   `json:"key"`
	Type        string   `json:"type"` // "string", "bool", "int", "select", "secret"
	Label       string   `json:"label"`
	Description string   `json:"description,omitempty"`
	Default     any      `json:"default,omitempty"`
	Required    bool     `json:"required,omitempty"`
	Options     []string `json:"options,omitempty"`   // for "select" type
	Component   string   `json:"component,omitempty"` // custom React component (requires developer_mode)
}

ConfigFieldDef defines a single configuration field for frontend rendering.

type Connector

type Connector interface {
	Name() string
	Send(ctx context.Context, payload map[string]interface{}) error
	Health(ctx context.Context) error
}

Connector is the interface for outbound integrations (email, webhook, Slack, etc.).

type EnvelopeOut

type EnvelopeOut struct {
	// Type is the envelope type identifier, e.g. "oembed.card" or
	// "support-ticket.created". Must match one of the types declared in
	// the plugin's plugin.yaml registers.envelopes section.
	Type string `json:"type"`

	// Data is the envelope payload. Validated against the schema
	// registered for Type.
	Data map[string]interface{} `json:"data"`

	// SessionID routes the envelope to a specific chat session. Empty
	// means broadcast to all listeners.
	SessionID string `json:"session_id,omitempty"`
}

EnvelopeOut is an envelope emitted by a plugin as the result of a command, event handler, or MCP tool call. Envelopes are validated by the host against the plugin's declared envelope types and their JSON Schemas before being surfaced to the UI.

Envelope-type registration is declarative: plugins declare envelope types in plugin.yaml and return EnvelopeOut values from capability handlers. Plugins do not register envelope types programmatically.

type Error

type Error struct {
	Code    int // HTTP status code (404, 409, 422, etc.)
	Message string
}

Error is a typed plugin error that carries an HTTP-friendly status code plus a stable code constant for wire-protocol mapping. Plugin CRUD handlers should return these instead of plain errors so the host can translate them into HTTP status codes and JSON-RPC error objects.

PluginError is a backward-compatibility alias retained for callers that imported the type under its older name; new code should use Error directly.

func ErrConflict

func ErrConflict(msg string) *Error

ErrConflict returns a 409 Error.

func ErrNotFound

func ErrNotFound(msg string) *Error

ErrNotFound returns a 404 Error.

func ErrValidation

func ErrValidation(msg string) *Error

ErrValidation returns a 422 Error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type Event

type Event struct {
	Type      string                 `json:"type"`
	Source    string                 `json:"source"`
	Timestamp time.Time              `json:"timestamp"`
	Data      map[string]interface{} `json:"data"`
	SessionID string                 `json:"session_id,omitempty"`
}

Event represents an event in the system.

type EventHook

type EventHook interface {
	// Handle processes an event. Returning ErrCancelled from a pre-hook
	// event (e.g., message.sending) cancels the pending action.
	Handle(ctx context.Context, event Event) error

	// EventTypes returns the list of event types this hook handles.
	EventTypes() []string

	// PluginID returns the ID of the owning plugin. The host uses this to
	// remove all hooks belonging to a plugin during unload.
	PluginID() string
}

EventHook processes events from the host application.

Implementations MUST report the ID of the plugin that owns them via PluginID so the host can cleanly unregister hooks during unload. Hooks without a PluginID cannot be cleanly removed at unload and are a known source of leak bugs.

type Host

type Host interface {
	// GetPlugin retrieves another loaded plugin by ID.
	GetPlugin(id string) (Plugin, bool)

	// RegisterCRUDHandler registers a CRUD handler for a resource type.
	RegisterCRUDHandler(resourceType string, handler CRUDHandler) error

	// RegisterEventHook registers an event hook for specific event types.
	RegisterEventHook(eventTypes []string, hook EventHook) error

	// RegisterUIComponent registers UI components for the frontend.
	RegisterUIComponent(component UIComponent) error

	// GetService provides access to core services (MCP clients, databases, etc.).
	GetService(name string) (interface{}, error)

	// GetConfig returns a plugin configuration value.
	// Resolution order: env var -> DB setting -> config file -> default.
	// Returns an error if the key is required and not found.
	GetConfig(key string) (string, error)

	// SetConfig persists a configuration value for the calling plugin.
	SetConfig(key string, value string) error

	// RegisterConfigSchema registers the config field definitions for the
	// calling plugin. The frontend reads this schema to render settings
	// forms automatically.
	RegisterConfigSchema(fields []ConfigFieldDef) error

	// RegisterConnector registers a named outbound connector (webhook, email, etc.).
	RegisterConnector(name string, connector Connector) error

	// RegisterProvider registers a runtime LLM provider.
	RegisterProvider(name string, provider interface{}) error

	// RegisterCLIAdapter registers a runtime CLI adapter for PTY/subprocess bridges.
	RegisterCLIAdapter(name string, adapter interface{}) error

	// Logger provides a logger instance for the plugin.
	Logger() Logger

	// Context returns the plugin's execution context.
	Context() context.Context
}

Host provides the runtime environment and services available to plugins. This is the base Host contract — host applications may extend it with additional registration methods in their own public package (for example, adding RegisterCommand / RegisterSlot / RegisterKeybinding in a host's own pkg/plugin package).

type Installable

type Installable interface {
	Install(host Host) error
}

Installable is an optional interface plugins implement to run setup logic during first-time installation. If not implemented, Load handles all setup.

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
	Error(msg string, keysAndValues ...interface{})
	With(keysAndValues ...interface{}) Logger
}

Logger provides structured logging capabilities for plugins. Hosts supply an implementation via Host.Logger(); plugins running as subprocesses use the stderr JSON-lines logger from github.com/hollis-labs/libs/mcp/plugin-mcp/plugin-sdk/subprocess.

type MessageOut

type MessageOut struct {
	// SessionID is the chat session to post into.
	SessionID string `json:"session_id"`

	// Role is the message role: "assistant", "system", or "tool".
	Role string `json:"role"`

	// Content is the message body (markdown).
	Content string `json:"content"`

	// Envelopes are optional envelopes to attach alongside the message.
	Envelopes []EnvelopeOut `json:"envelopes,omitempty"`
}

MessageOut is a chat message produced by a plugin. Typically used by command handlers that want to inject a message into the session rather than emit a rendered envelope.

type Plugin

type Plugin interface {
	// ID returns a unique identifier for this plugin.
	ID() string

	// Name returns the human-readable name of the plugin.
	Name() string

	// Version returns the plugin version.
	Version() string

	// Description returns a brief description of the plugin's purpose.
	Description() string

	// Dependencies returns a list of required plugin IDs this plugin depends on.
	Dependencies() []string

	// Load is called when the plugin is loaded into the host.
	Load(host Host) error

	// Unload is called when the plugin is being removed.
	Unload() error

	// Status returns the current status of the plugin.
	Status() PluginStatus
}

Plugin is the minimum contract a plugin must implement. Optional capability interfaces (CRUDHandler, EventHook, Installable, Uninstallable, Connector) are detected via type assertion at registration time.

type PluginError deprecated

type PluginError = Error

PluginError is a backward-compatible alias for Error.

Deprecated: use Error directly. This alias will be removed in a future release.

type PluginStatus

type PluginStatus struct {
	Loaded    bool      `json:"loaded"`
	Enabled   bool      `json:"enabled"`
	LoadedAt  time.Time `json:"loaded_at"`
	LastError string    `json:"last_error,omitempty"`
}

PluginStatus represents the current state of a plugin.

type UIComponent

type UIComponent struct {
	ID          string                 `json:"id"`
	Type        UIComponentType        `json:"type"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Props       map[string]interface{} `json:"props,omitempty"`
	// Handler is used for server-side rendering (compiled-in plugins only).
	// Subprocess plugins cannot carry an http.Handler across the wire and
	// must leave this nil.
	Handler http.Handler `json:"-"`
}

UIComponent represents a UI component that can be rendered in the frontend.

type UIComponentType

type UIComponentType string

UIComponentType defines the type of UI component.

const (
	UIComponentTypeWidget   UIComponentType = "widget"
	UIComponentTypeEnvelope UIComponentType = "envelope"
	UIComponentTypeAction   UIComponentType = "action"
	UIComponentTypeWorkflow UIComponentType = "workflow"
	UIComponentTypeView     UIComponentType = "view"
)

type Uninstallable

type Uninstallable interface {
	Uninstall(host Host) error
}

Uninstallable is an optional interface plugins implement to clean up artifacts during uninstallation. User-created data is preserved.

Directories

Path Synopsis
Package capability supplies host-neutral capability descriptors, exact-match scope narrowing and safe typed application failures.
Package capability supplies host-neutral capability descriptors, exact-match scope narrowing and safe typed application failures.
host/hosttest
Package hosttest runs behavioral capability conformance through a host's actual admission, dispatcher, lifecycle and non-plugin bridge adapters.
Package hosttest runs behavioral capability conformance through a host's actual admission, dispatcher, lifecycle and non-plugin bridge adapters.
examples
hello command
Hello is the minimum-viable subprocess plugin: a plugin that uses only plugin-sdk imports, fits in roughly fifty lines, and handles a full init / load / unload lifecycle plus a single command.
Hello is the minimum-viable subprocess plugin: a plugin that uses only plugin-sdk imports, fits in roughly fifty lines, and handles a full init / load / unload lifecycle plus a single command.
manifest command
Command manifest emits a generated plugin.yaml declaration on stdout.
Command manifest emits a generated plugin.yaml declaration on stdout.
internal
strictjson
Package strictjson checks JSON tokens before decoding can discard duplicate keys.
Package strictjson checks JSON tokens before decoding can discard duplicate keys.
Package manifest defines the host-neutral declaration emitted by a plugin binary and reviewed before the host starts it.
Package manifest defines the host-neutral declaration emitted by a plugin binary and reviewed before the host starts it.
protocol
v1
Code generated by generate.py; DO NOT EDIT.
Code generated by generate.py; DO NOT EDIT.
Package registry defines the registry-v2 host-authoritative contribution catalog.
Package registry defines the registry-v2 host-authoritative contribution catalog.
Package subprocess carries the JSON-RPC 2.0 wire protocol used for host-to-plugin communication over stdio.
Package subprocess carries the JSON-RPC 2.0 wire protocol used for host-to-plugin communication over stdio.
subprocesstest
Package subprocesstest provides an in-process test harness for subprocess plugins.
Package subprocesstest provides an in-process test harness for subprocess plugins.

Jump to

Keyboard shortcuts

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