* feat(plugins): add public Track and Artist DTOs for host services * feat(plugins): add Matcher host-service interface and MatchSong DTO * feat(plugins): generate Matcher host wrappers, PDK clients, and matcher permission * feat(plugins): implement Matcher host service and MediaFile-to-Track converter Also fixes an ndpgen bug where ParseDirectory parsed each host-service file in isolation, so a service method referencing a struct defined in another file of the same package (host.Track in track.go) could not be resolved. ParseDirectory now collects package-wide structs in a first pass, mirroring ParseCapabilities; PDK clients regenerated cleanly via make gen. * feat(plugins): register Matcher host service in the manager * test(plugins): add Matcher host service integration test plugin * refactor(plugins): simplify matcher converter and parser file collection - toTrack: use gg.V for nil-able field derefs and slice.Map for genres/ participants, removing the repeated nil-guard blocks and inner loop - manager_loader: drop the redundant ds==nil guard (loadEnabledPlugins already gates a nil DataStore), matching the other service entries - ndpgen parser: extract collectGoFiles, shared by ParseDirectory and ParseCapabilities instead of duplicating the file-filter loop * fix(plugins): keep nullable Track numerics as pointers ReplayGain values, BitDepth, and BPM are nullable in model.MediaFile, and 0 is a valid measured ReplayGain value. Flattening them to value types with omitempty made a real 0 indistinguishable from absent. Model them as *float64 /*int32 so plugins can tell 'no data' from a measured 0. Regenerated PDK clients; converter passes the model pointers through (RG) or maps *int->*int32 (BitDepth/BPM). * refactor(plugins): trim redundant pass labels in ndpgen ParseDirectory The function doc already explains the two-pass approach; the inline labels restated it. Reduce to bare waypoints. * fix(plugins): gate Track.Path on library filesystem permission MatchSongs copied mf.Path into every result unconditionally, letting a plugin with only the matcher permission enumerate on-disk file paths by matching known songs. Gate Path behind library.filesystem, matching the Library host service. toTrack is now a method carrying the permission flag. * refactor(plugins): align MatchSong JSON casing and parse Go files once - MatchSong: artistMBID/albumMBID JSON tags -> artistMbid/albumMbid so the Go wire format matches the Rust SDK's camelCase serialization (cross-SDK fix) - MatchSongs doc reworded to language-neutral 'empty (absent)' so generated Rust/Python client docs no longer say Go-specific 'nil' - ndpgen: parse each package file once (parseGoFiles) and reuse the ASTs across both passes in ParseDirectory and ParseCapabilities, instead of re-parsing * refactor(plugins): use shared types for Matcher host service Move the Matcher host service onto the shared plugins/types package instead of the host-local MatchSong and Track structs. MatchSongs now takes []types.SongRef and returns []*types.Track, dropping host.MatchSong and moving host.Track (with its host.Artist dependency collapsed onto types.ArtistRef) into plugins/types. ArtistRef gains SortName and SubRole so it can back a track's Participants. SongRef gains a millisecond-precision DurationMs field that supersedes the now deprecated seconds-based Duration, with DurationInMs() resolving the effective value and SetDurationMs() keeping both fields in sync when populating a SongRef to send to a plugin. The ndpgen host-wrapper template only ever imported context, json and extism, so a host service referencing the shared types package produced uncompilable code. Emit the plugins/types import when the service references shared types directly (gated on the existing Service.ImportsSharedTypes), matching the client template, and cover it with GenerateHost tests. This removes the need for host-local re-export aliases. Regenerated the Go/Rust/Python PDK and capability schemas accordingly. * test(plugins): cover SongRef duration and artist conversion Add unit coverage for the new SongRef behavior: SetDurationMs populating both DurationMs and the deprecated seconds field, and the SongRef-to-agents.Song conversion preferring DurationMs over Duration and the Artists list over the scalar Artist/ArtistMBID. Extract the inline SongRef-to-agents.Song closure in MatchSongs into a named toAgentSong function so the conversion can be asserted directly rather than only through the opaque matcher. The end-to-end wire shape of the moved types is already validated by the existing MatcherService integration test, so no new WASM-boundary test is needed. * fix(plugins): harden and unify SongRef-to-agents.Song duration conversion Address findings from a code review of the matcher host service: - DurationInMs now clamps a negative deprecated-seconds value to 0 instead of converting it through uint32, which previously wrapped a value like -1s into a ~49-day duration that corrupted the matcher's duration-proximity tiebreaker. - Replace the unused SetDurationMs(uint32) with SetDuration(seconds float32), which takes the unit callers actually hold (model.MediaFile.Duration is float32 seconds) and centralizes the seconds-to-ms conversion. Wire it into mediaFileToSongRef so outbound SongRefs carry both duration fields in sync. - Make the metadata-agent path use DurationInMs() so every consumer of the shared SongRef honors the DurationMs-over-Duration precedence contract; a plugin sending only DurationMs no longer loses its duration on that path. - Collapse the matcher's duplicate toAgentSong/agentArtists helpers into the existing songRefToAgentSong converter, so there is a single SongRef-to-Song mapping. Tests narrowed to the duration cases, with artist precedence still covered in metadata_agent_test.go. * feat(plugins): allow Matcher host service to scope a match to a user Add an options struct to the Matcher host service so a plugin can run a match as a specific user. When MatchOptions.Username is set, the match is run in that user's context: their favourites and ratings inform the matcher's tiebreaker, and the returned tracks carry that user's per-user annotations (Starred, StarredAt, Rating, PlayCount, PlayDate, added to types.Track). An empty username preserves the previous unscoped behaviour. Cross-user access is gated by the same allowedUsers/allUsers permission the Users and SubsonicAPI host services use: an unknown username, or one the plugin is not permitted to act as, returns an error. User-library access applies automatically once the user is in context (applyLibraryFilter). Independently, results are now restricted to the libraries the plugin itself may access via the precomputed libraryAccess set, dropping any matched track outside that set (the input index stays unmatched) — this applies even without a username and even for an admin-scoped user. core/matcher is unchanged: it already loads and uses annotations and applies user-library filtering from context, so the feature works by deriving the request context and post-filtering by plugin library access in the host adapter. The new opts parameter and the Track annotation fields are propagated to all PDK clients (Go/Rust/Python) by make gen. * fix(plugins): correct Matcher library scope and unify user-access checks Address findings from a code review of the user-scoped Matcher host service: - The plugin-library post-filter previously dropped every match for a plugin that holds only the matcher permission, because library config is tied to the Library permission and a matcher-only plugin has none (empty allowedLibraries, AllLibraries=false). Gate the filter on whether the plugin actually declared the Library permission: matcher-only plugins are no longer library-restricted, while plugins that opt into a library scope are enforced as before. The per-user library filter (applyLibraryFilter) still applies whenever a non-admin user is scoped. - resolveUser collapsed every FindByUsername error (including transient DB failures) into a misleading "not found". Extract a shared userAccess type (alongside libraryAccess) whose resolve() distinguishes model.ErrNotFound from a real backend error and authorizes the user against the allowed set. The Matcher service now uses it, and host_subsonicapi shares the same userAccess type for its permission check (preserving its existing error messages), removing a third divergent copy of the resolve-and-authorize logic. - Document in the matcher tests that the mock MediaFileRepo returns annotations unconditionally, so the unit tests cover the adapter's scoped-flag gating and access checks but not the SQL per-user join. Add tests for the library-permission gating and for surfacing a backend error instead of masking it as not-found. * fix(plugins): require a library scope for Matcher, fail closed Reverse the permissive default introduced when fixing the library post-filter: a Matcher plugin now must be granted a library scope (all libraries, or at least one specific library) and MatchSongs rejects the request with "no libraries configured" when it has none, instead of either silently matching nothing or defaulting to every library. This mirrors how the SubsonicAPI host service requires a user scope (checkPermissions errors with "no users configured" when none is set): the check is a runtime guard via libraryAccess.configured(), needs no manifest changes, and keeps the failure loud rather than silent. The per-match library post-filter then always applies, and the restrictLibraries flag added in the previous commit is removed. * fix(plugins): require library permission for matcher; guard nil user Close the gap where a plugin declaring only the matcher permission loaded successfully but failed every MatchSongs call with "no libraries configured", with no way for an admin to grant a library scope (the library-config UI is gated on the library permission). Add a cross-field manifest rule, mirroring the existing "subsonicapi requires users" rule, so the matcher permission requires the library permission to be declared. A matcher plugin therefore also surfaces the library-config panel and is subject to the existing load/enable-time library configuration gate, making the fail-closed library check reachable and fixable rather than a silent dead end. The test plugin manifest now declares the library permission accordingly. Also restore a defensive nil-user guard in userAccess.resolve: if a DataStore's FindByUsername ever returns (nil, nil) instead of model.ErrNotFound, return a clean "not found" error rather than dereferencing a nil *model.User. * feat(plugins): expose track AverageRating in Matcher results Add AverageRating to the Matcher's Track DTO. Unlike the per-user annotations (Starred, Rating, PlayCount, ...), AverageRating is an aggregate stored on the track itself and is loaded regardless of the request user, so it is populated unconditionally rather than gated on a scoped username. Propagated to the PDK types by make gen. Signed-off-by: Deluan <deluan@navidrome.org> * style(plugins): trim verbose comments in matcher host service Condense the over-long explanatory comments added across the matcher host service to one-liners that state the why, and simplify the ptrInt32/unixPtr helpers to Go 1.26's new(value). No behavior change. * refactor(plugins): pass userAccess into newSubsonicAPIService Move newUserAccess construction to the loader call site so the SubsonicAPI service constructor takes a userAccess value directly, matching newMatcherService. Pure refactor: the service already stored a userAccess internally, so behavior and error messages are unchanged. * fix(plugins): regenerate PDK and drop omitempty from AverageRating Re-run make gen so the generated PDK doc comments match the source comment trimmed in an earlier commit (the source was simplified but the PDK was not regenerated, leaving the committed files stale — a 'generated files up to date' hazard). Also drop omitempty from Track.AverageRating: it is always set (0 when unrated), so it should be present in the payload like the other always-set fields (BirthTime/CreatedAt/UpdatedAt), not dropped at zero. Tag change propagated to the PDK by the same regeneration. * fix(plugins): reject user-scoped match before lookup when plugin has no user scope A matcher plugin requires the library permission but not the users permission, so a matcher-only plugin always has an empty user scope (allUsers=false, no allowed users). MatchSongs still ran FindByUsername for any opts.Username before checking authorization and returned distinguishable errors ('user X not found' vs 'not allowed to act as user X'), letting such a plugin enumerate account names from the error text. Guard userAccess.resolve to reject with a single fixed error before the lookup when the plugin has no user scope, mirroring how the SubsonicAPI service short-circuits with 'no users configured'. The unscoped match path (no username) is unaffected, so matcher-only plugins still match normally. * fix(plugins): run unscoped matcher as admin, not the inherited request user A matcher host call can arrive on a context that already carries a request user (e.g. a plugin capability invoked while serving that user's request — extism propagates the call context into host functions). With no opts.Username, MatchSongs passed that context straight through, so the media-file repository applied the caller's library filter and per-user annotation ranking to an explicitly unscoped match. Set the user context explicitly: a username scopes to that user (overriding any inherited one), and an unscoped match runs under adminContext so only the plugin's own library scope constrains results. Adds tests using a context-capturing DataStore to assert the user the matcher resolves in both cases. * chore(plugins): drop the generated Python matcher PDK The Python plugin PDK is no longer supported (ndpgen generates only Go and Rust clients), so remove the stale generated nd_host_matcher.py rather than leave a client that drifts from the host interface. * docs(plugins): deprecate SongRef.Artist/ArtistMBID in favor of Artists Mark the scalar single-artist fields deprecated; Artists (the ArtistRef list) is the preferred way to supply artist data and already takes precedence for matching. Propagated to the PDK and capability schemas by make gen. * refactor(plugins): flatten Track.Participants and add Role to ArtistRef Change Track.Participants from map[role][]ArtistRef to a flat []ArtistRef, and give ArtistRef a Role field (the participation category: artist/composer/performer/...) alongside SubRole (a specialization within a role, e.g. the instrument for a performer). In the flat list each entry now self-describes its role rather than relying on a map key, matching how SongRef.Artists is already a flat list; the converter tags each entry with its role and emits them in a stable role order. Propagated to the PDK and capability schemas by make gen. --------- Signed-off-by: Deluan <deluan@navidrome.org>
Navidrome Plugin Development Kit for Go
This directory contains the auto-generated Go PDK (Plugin Development Kit) for building Navidrome plugins. The PDK provides both host function wrappers for interacting with Navidrome and capability interfaces for implementing plugin functionality.
⚠️ Auto-Generated Code
Do not edit files in this directory manually. They are generated by the ndpgen tool.
To regenerate:
make gen
Module Structure
This is a consolidated Go module that includes:
host/- Host function wrappers for calling Navidrome services from pluginslifecycle/- Plugin lifecycle hooks (initialization)metadata/- Metadata agent capability for artist/album infoscheduler/- Scheduler callback capability for scheduled tasksscrobbler/- Scrobbler capability for play trackingwebsocket/- WebSocket callback capability for real-time messages
Usage
Add this module as a dependency in your plugin's go.mod:
require github.com/navidrome/navidrome/plugins/pdk/go v0.0.0
replace github.com/navidrome/navidrome/plugins/pdk/go => ../../pdk/go
Then import the packages you need:
package main
import (
"github.com/navidrome/navidrome/plugins/pdk/go/host"
"github.com/navidrome/navidrome/plugins/pdk/go/lifecycle"
"github.com/navidrome/navidrome/plugins/pdk/go/scheduler"
)
func init() {
lifecycle.Register(&myPlugin{})
scheduler.Register(&myPlugin{})
}
type myPlugin struct{}
func (p *myPlugin) OnInit() error {
// Initialize your plugin
return nil
}
func (p *myPlugin) OnCallback(req scheduler.SchedulerCallbackRequest) error {
// Handle scheduled task
return host.WebSocketBroadcast("task-complete", req.ScheduleID)
}
func main() {}
Host Services
The host package provides wrappers for calling Navidrome's host services:
| Service | Description |
|---|---|
Artwork |
Access album and artist artwork |
Cache |
Temporary key-value storage with TTL |
KVStore |
Persistent key-value storage |
Library |
Access the music library (albums, artists, tracks) |
Scheduler |
Schedule one-time and recurring tasks |
SubsonicAPI |
Make Subsonic API calls |
WebSocket |
Send real-time messages to clients |
Example: Using Host Services
package main
import (
"github.com/navidrome/navidrome/plugins/pdk/go/host"
)
func myPluginFunction() error {
// Use the cache service
_, err := host.CacheSetString("my_key", "my_value", 3600)
if err != nil {
return err
}
// Schedule a recurring task
_, err = host.SchedulerScheduleRecurring("@every 5m", "payload", "task_id")
if err != nil {
return err
}
// Access library data with typed structs
resp, err := host.LibraryGetAllLibraries()
if err != nil {
return err
}
for _, lib := range resp.Result {
// Library: %s with %d songs", lib.Name, lib.TotalSongs
}
return nil
}
Capabilities
Capabilities define what functionality your plugin implements. Register your implementations
in the init() function.
Lifecycle
Provides plugin initialization hooks.
import "github.com/navidrome/navidrome/plugins/pdk/go/lifecycle"
func init() {
lifecycle.Register(&myPlugin{})
}
type myPlugin struct{}
func (p *myPlugin) OnInit() error {
// Called once when plugin is loaded
return nil
}
MetadataAgent
Provides artist and album metadata from external sources.
import "github.com/navidrome/navidrome/plugins/pdk/go/metadata"
func init() {
metadata.Register(&myAgent{})
}
type myAgent struct{}
func (a *myAgent) GetArtistBiography(req metadata.ArtistRequest) (*metadata.ArtistBiographyResponse, error) {
return &metadata.ArtistBiographyResponse{
Biography: "Artist biography text...",
}, nil
}
func (a *myAgent) GetArtistImages(req metadata.ArtistRequest) (*metadata.ArtistImagesResponse, error) {
return &metadata.ArtistImagesResponse{
Images: []metadata.ImageInfo{
{URL: "https://example.com/image.jpg", Size: 1000},
},
}, nil
}
Scheduler
Handles callbacks from scheduled tasks.
import (
"github.com/navidrome/navidrome/plugins/pdk/go/host"
"github.com/navidrome/navidrome/plugins/pdk/go/scheduler"
)
func init() {
scheduler.Register(&myScheduler{})
}
type myScheduler struct{}
func (s *myScheduler) OnCallback(req scheduler.SchedulerCallbackRequest) error {
// Handle the scheduled task
if req.Payload == "update-data" {
// Do work...
return host.WebSocketBroadcast("data-updated", "")
}
return nil
}
Scrobbler
Tracks play activity.
import "github.com/navidrome/navidrome/plugins/pdk/go/scrobbler"
func init() {
scrobbler.Register(&myScrobbler{})
}
type myScrobbler struct{}
func (s *myScrobbler) Scrobble(req scrobbler.ScrobbleRequest) error {
// Track the play
return nil
}
func (s *myScrobbler) NowPlaying(req scrobbler.NowPlayingRequest) error {
// Update now playing status
return nil
}
WebSocket
Handles incoming WebSocket messages.
import "github.com/navidrome/navidrome/plugins/pdk/go/websocket"
func init() {
websocket.Register(&myHandler{})
}
type myHandler struct{}
func (h *myHandler) OnWebSocketMessage(req websocket.WebSocketMessageRequest) error {
// Handle incoming message
return nil
}
Building Plugins
Go plugins must be compiled to WebAssembly using TinyGo:
tinygo build -o plugin.wasm -target=wasip1 -buildmode=c-shared .
Or use the provided Makefile targets in plugin examples:
make plugin.wasm
Testing Plugins
The PDK includes testify/mock implementations for all host services, allowing you to unit test your plugin code on non-WASM platforms (your development machine).
PDK Abstraction Layer
The pdk subpackage provides a testable wrapper around the Extism PDK functions. Instead of importing
github.com/extism/go-pdk directly, import the abstraction layer:
import "github.com/navidrome/navidrome/plugins/pdk/go/pdk"
func myFunction() {
// Use pdk functions - same API as extism/go-pdk
config, ok := pdk.GetConfig("my_setting")
if ok {
pdk.Log(pdk.LogInfo, "Setting: " + config)
}
var input MyInput
if err := pdk.InputJSON(&input); err != nil {
pdk.SetError(err)
return
}
output := processInput(input)
pdk.OutputJSON(output)
}
For WASM builds, these functions delegate directly to extism/go-pdk with zero overhead.
For native builds (tests), they use mocks that you can configure:
package myplugin
import (
"testing"
"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)
func TestMyFunction(t *testing.T) {
// Reset mock state before each test
pdk.ResetMock()
// Set up expectations
pdk.PDKMock.On("GetConfig", "my_setting").Return("test_value", true)
pdk.PDKMock.On("Log", pdk.LogInfo, "Setting: test_value").Return()
pdk.PDKMock.On("InputJSON", mock.Anything).Return(nil).Run(func(args mock.Arguments) {
// Populate the input struct
input := args.Get(0).(*MyInput)
input.Name = "test"
})
pdk.PDKMock.On("OutputJSON", mock.Anything).Return(nil)
// Call your function
myFunction()
// Verify expectations
pdk.PDKMock.AssertExpectations(t)
}
Mock Instances
Each host service has an auto-instantiated mock instance:
| Service | Mock Instance |
|---|---|
Artwork |
host.ArtworkMock |
Cache |
host.CacheMock |
Config |
host.ConfigMock |
KVStore |
host.KVStoreMock |
Library |
host.LibraryMock |
Scheduler |
host.SchedulerMock |
SubsonicAPI |
host.SubsonicAPIMock |
WebSocket |
host.WebSocketMock |
Example Test
package myplugin
import (
"testing"
"github.com/navidrome/navidrome/plugins/pdk/go/host"
)
func TestMyPluginFunction(t *testing.T) {
// Set expectations on the mock
host.CacheMock.On("GetString", "my-key").Return("cached-value", true, nil)
host.CacheMock.On("SetString", "new-key", "new-value", int64(3600)).Return(nil)
// Call your plugin code that uses host.CacheGetString / host.CacheSetString
result, err := myPluginFunction()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Assert the result
if result != "expected" {
t.Errorf("unexpected result: %s", result)
}
// Verify all expected calls were made
host.CacheMock.AssertExpectations(t)
}
Running Tests
Since tests run on your development machine (not WASM), use standard Go testing:
go test ./...
The stub files with mocks are only compiled for non-WASM builds (//go:build !wasip1),
so they won't affect your production WASM binary.
Complete Examples
For more comprehensive examples including HTTP requests, Memory handling, and various testing patterns, see pdk/example_test.go.