roon-mcp (empty) → 0.1.0.0
raw patch · 8 files changed
+1538/−0 lines, 8 filesdep +aesondep +basedep +effectful
Dependencies added: aeson, base, effectful, effectful-core, effectful-mcp, roon-api, roon-mcp, streamly-core, tasty, tasty-hunit, text, time
Files
- CHANGELOG.md +14/−0
- LICENSE +29/−0
- README.md +73/−0
- app/Main.hs +109/−0
- roon-mcp.cabal +99/−0
- src/RoonMcp/Plan.hs +246/−0
- src/RoonMcp/Tools.hs +809/−0
- test/Main.hs +159/−0
+ CHANGELOG.md view
@@ -0,0 +1,14 @@+# Revision history for roon-mcp++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* An MCP server on stdio, for revision 2026-07-28 of the protocol and the+ earlier ones, with twelve tools: `list_zones`, `get_queue`,+ `search_tracks`, `queue_tracks`, `control`, `browse_library`,+ `play_item`, `set_volume`, `seek`, `set_playback_options`,+ `transfer_zone` and `get_image`.+* `roon-mcp register` to enable the extension once.+* Without `ROON_HOST`, the Roon Server is discovered on the local network+ at start; `ROON_CORE` chooses among several.+* `ROON_TRACE` describes every frame exchanged with Roon on stderr.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,73 @@+# roon-mcp++A [Model Context Protocol](https://modelcontextprotocol.io) server, on+stdio, that lets an assistant play music on a [Roon](https://roon.app)+system: list the zones, search and browse the library, queue or play what+was found, and control playback and volume.++This is an independent, unofficial project, not affiliated with or endorsed+by Roon Labs. It is built on+[roon-api](https://hackage.haskell.org/package/roon-api) and+[effectful-mcp](https://hackage.haskell.org/package/effectful-mcp), and+speaks MCP revision 2026-07-28, and the earlier revisions to the clients+that only know them.++## Tools++| Tool | What it does |+|---|---|+| `list_zones` | The zones, what plays in each, their outputs with their volume, their playback options, and what each allows. |+| `get_queue` | The next items of the queue of a zone. |+| `search_tracks` | Several searches at once, one per track; candidates with an id, a title and artists. |+| `queue_tracks` | Candidates into the queue of a zone, in order: at the end (`queue`, the default), after the current track (`add_next`), or in place of the queue, the first at once (`play_now`). Reports each track. |+| `control` | Play, pause, stop, next, previous. |+| `browse_library` | The library by albums, artists, playlists, genres, composers and internet radios, or a search of all of it; opens the lists it finds, page by page. |+| `play_item` | What `browse_library` found (a track, an album, a playlist, an artist, a radio) into a zone: `queue` (the default), `add_next`, `play_now`, `start_radio` or `shuffle`. |+| `set_volume` | The volume of a zone or of one of its outputs: a level, a move, or mute. |+| `seek` | A position in the track that plays, or a move from the current one. |+| `set_playback_options` | Shuffle, Roon Radio after the queue, and the loop. |+| `transfer_zone` | What plays in a zone, with its queue, to another zone. |+| `get_image` | An image of Roon, such as a cover, from an `image_key` given by the other tools. |++Zones are named by their id or their name.++## Setting up++ cabal install roon-mcp+ roon-mcp register++`roon-mcp register` connects to the Roon Server and waits until you enable+"roon-mcp" in Roon, under Settings, Extensions. It does so once: the token+it receives is kept in `$XDG_STATE_HOME/roon-api/`.++Then declare the server to the MCP client, for instance Claude Code:++ claude mcp add roon -- /path/to/roon-mcp++`ROON_HOST` and `ROON_PORT` choose the server. Without `ROON_HOST`,+roon-mcp looks for one on the local network when it starts, by SOOD;+`ROON_CORE`, a name or a unique id, chooses among several. If none answers,+it uses `127.0.0.1:9330`. `ROON_TRACE=1` describes every frame exchanged with Roon+on stderr, which MCP leaves free for logs.++## How it works++Each call opens a connection to Roon, does its work and closes it, so the+server keeps no state. Roon keeps one connection per extension, so calls+take their connections one at a time. A candidate id carries the browsing+session where Roon keeps the result of its search, so that searching and+queueing can be two calls.++## Building++To build against copies of the libraries this package is built on+([roon-api](https://hackage.haskell.org/package/roon-api),+[effectful-mcp](https://hackage.haskell.org/package/effectful-mcp) and those+under them) checked out next to this repository, pass+`--project-file=cabal.project.siblings`.++Tested with GHC 9.8.4, 9.10.3 and 9.12.4, and Roon Server 2.75.++## License++BSD-3-Clause. See [LICENSE](LICENSE).
+ app/Main.hs view
@@ -0,0 +1,109 @@+-- | @roon-mcp@: an MCP server, on stdio, that plays music on Roon.+--+-- @roon-mcp register@ registers the extension once, waiting for the user+-- to enable it in Roon.+module Main (main) where++import Data.Text (Text, pack)+import Data.Text.Encoding (encodeUtf8)+import Effectful (Eff, IOE, runEff, type (:>))+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Concurrent.MVar (newMVar)+import Effectful.Environment (Environment, getArgs, lookupEnv, runEnvironment)+import Effectful.Error.Static (runErrorNoCallStack)+import Effectful.FileSystem (FileSystem, runFileSystem)+import Effectful.FileSystem.IO (stderr)+import Effectful.FileSystem.IO.ByteString (hPutStrLn)+import Effectful.MCP.Server (ServerConfig (..), implementation, serveStdio,+ serverConfig)+import Roon.Connection (runRoon)+import Roon.Discovery (Core (..), defaultDiscovery, discover)+import Roon.Effect.TokenStore (defaultTokenFile, runTokenStoreFile)+import Roon.Effect.WebSocket (ServerAddress (..), localServer, runWebSocket)+import Roon.Error (RoonError)+import Roon.Registry (ExtensionInfo (..))+import RoonMcp.Tools (Context (..), describeError, extension, instructions,+ serverVersion, tools)+import System.Exit (exitFailure)+import Text.Read (readMaybe)++main :: IO ()+main = do+ succeeded <- runEff . runConcurrent . runFileSystem . runEnvironment $ program+ if succeeded then pure () else exitFailure++type Effects = '[Environment, FileSystem, Concurrent, IOE]++-- | 'False' when the program failed.+program :: Eff Effects Bool+program = do+ context <- configure+ getArgs >>= \case+ [] -> do+ serveStdio+ (serverConfig (implementation "roon-mcp" serverVersion) (tools context))+ { instructions = Just instructions+ }+ pure True+ ["register"] -> register context+ _ -> do+ complain "usage: roon-mcp [register] (ROON_HOST and ROON_PORT choose the server, otherwise it is discovered, ROON_CORE choosing among several; ROON_TRACE=1 describes every frame on stderr)"+ pure False++-- | The server address, the token file and the options.+configure :: Eff Effects Context+configure = do+ address <- serverAddress+ tokenFile <- defaultTokenFile extension.extensionId+ connectionLock <- newMVar ()+ -- ROON_TRACE, when set, describes every frame on stderr.+ tracing <- maybe False (not . null) <$> lookupEnv "ROON_TRACE"+ pure+ Context+ { address+ , tokenFile+ , registrationTimeout = 5_000_000+ , traceLimit = if tracing then Just 300 else Nothing+ , connectionLock+ }++-- | ROON_HOST and ROON_PORT when ROON_HOST is set. Otherwise the server+-- that answers a discovery on the network, the one named or identified by+-- ROON_CORE if there are several; failing that, 127.0.0.1:9330.+serverAddress :: Eff Effects ServerAddress+serverAddress =+ lookupEnv "ROON_HOST" >>= \case+ Just host -> do+ port <- (>>= readMaybe) <$> lookupEnv "ROON_PORT"+ pure ServerAddress {host, port = maybe localServer.port id port}+ Nothing -> do+ wanted <- fmap pack <$> lookupEnv "ROON_CORE"+ cores <- discover defaultDiscovery+ let chosen = case wanted of+ Nothing -> cores+ Just name -> [core | core <- cores, core.uniqueId == name || core.name == Just name]+ case chosen of+ core : others -> do+ complain ("Using the Roon Server " <> maybe core.uniqueId id core.name <> " at " <> describe core.address <> if null others then "." else ", the first of several: ROON_CORE chooses one.")+ pure core.address+ [] -> do+ complain ("No Roon Server " <> maybe "" (\name -> "named " <> name <> " ") wanted <> "answered the discovery; using " <> describe localServer <> ".")+ pure localServer+ where+ describe address = pack address.host <> ":" <> pack (show address.port)++-- | Register, waiting as long as the user takes to enable the extension.+register :: Context -> Eff Effects Bool+register context = do+ complain ("Connecting to " <> pack context.address.host <> ":" <> pack (show context.address.port) <> ". Enable \"roon-mcp\" in Roon, under Settings, Extensions.")+ outcome <-+ runErrorNoCallStack @RoonError . runTokenStoreFile context.tokenFile . runWebSocket context.address $+ runRoon extension (const (pure ()))+ case outcome of+ Right () -> True <$ complain ("Registered. The token is in " <> pack context.tokenFile <> ".")+ Left err -> False <$ complain ("roon-mcp: " <> describeError context err)++-- | Write to stderr: stdout carries the protocol.+complain :: FileSystem :> es => Text -> Eff es ()+complain = hPutStrLn stderr . encodeUtf8+
+ roon-mcp.cabal view
@@ -0,0 +1,99 @@+cabal-version: 3.12+name: roon-mcp+version: 0.1.0.0+synopsis: An MCP server that plays music on Roon+description:+ A Model Context Protocol server, over stdio, that lets an assistant play+ music on a Roon system: list the zones and their queues, search and+ browse the library, queue or play tracks, albums, playlists and radios,+ control playback, volume and playback options, move what plays to+ another zone, and fetch images such as covers. Built on roon-api and+ effectful-mcp. Not affiliated with Roon Labs.++homepage: https://github.com/GuillaumedeVolpiano/roon_mcp+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: Sound, AI+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/roon_mcp.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ DuplicateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ NoFieldSelectors+ OverloadedRecordDot+ OverloadedStrings+ RoleAnnotations++ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ RoonMcp.Plan+ RoonMcp.Tools++ other-modules: Paths_roon_mcp+ autogen-modules: Paths_roon_mcp++ build-depends:+ , aeson ^>=2.3+ , base >=4.19 && <4.22+ , effectful ^>=2.7+ , effectful-core ^>=2.7.1+ , effectful-mcp ^>=0.1+ , roon-api ^>=0.1+ , streamly-core ^>=0.3.3+ , text ^>=2.1+ , time >=1.12 && <1.15++executable roon-mcp+ import: shared+ hs-source-dirs: app+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , base+ , effectful+ , effectful-mcp+ , roon-api+ , roon-mcp+ , text++test-suite roon-mcp-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , aeson+ , base+ , effectful+ , effectful-core+ , effectful-mcp+ , roon-api+ , roon-mcp+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10+ , text
+ src/RoonMcp/Plan.hs view
@@ -0,0 +1,246 @@+-- |+-- Module : RoonMcp.Plan+-- Description : The pure decisions of the server: candidate ids, zones,+-- and the order of the actions that queue tracks+-- License : BSD-3-Clause+module RoonMcp.Plan+ ( -- * Candidate ids+ candidateId+ , decodeCandidateId++ -- * Zones+ , findZone++ -- * Queueing+ , Mode (..)+ , modeName+ , parseMode+ , plan++ -- * Library items+ , ItemKind (..)+ , ItemRef (..)+ , itemKind+ , kindName+ , itemId+ , decodeItemId+ , libraryHierarchies+ , plainText+ , PlayAction (..)+ , playActionName+ , playActionTitle+ , parsePlayAction++ -- * Volume+ , outputsFor+ , volumeWithin++ -- * Images+ , imageMediaType+ ) where++import Data.Text (Text, breakOn, breakOnEnd, intercalate, isPrefixOf, splitOn,+ strip, stripPrefix, toCaseFold, toLower)+import Data.Text qualified as T (drop, length, null, take, takeWhile)+import Roon.Browse (Candidate (..), Hierarchy (..), Item (..), ItemHint (..),+ Session (..), TrackAction (..))+import Roon.Transport (Output (..), OutputId (..), Volume (..), Zone (..),+ ZoneId (..))++-- | An id that carries all a later call needs: the browsing session and+-- the key of the item in it. The server keeps nothing between calls.+candidateId :: Candidate -> Maybe Text+candidateId Candidate {session = Session {multiSessionKey = Just key}, item = Item {itemKey = Just itemKey}} =+ Just (key <> "|" <> itemKey)+candidateId _ = Nothing++-- | The candidate an id stands for. Its title is the id itself, since the+-- id does not carry the title.+decodeCandidateId :: Text -> Maybe Candidate+decodeCandidateId text = case breakOn "|" text of+ (key, rest)+ | not (T.null key)+ , Just itemKey <- stripPrefix "|" rest+ , not (T.null itemKey) ->+ Just+ Candidate+ { session = Session {hierarchy = Search, multiSessionKey = Just key}+ , item = Item {title = text, subtitle = Nothing, imageKey = Nothing, itemKey = Just itemKey, hint = Just ActionList, inputPrompt = Nothing}+ }+ _ -> Nothing++-- | The zone with this id or, failing that, this name, ignoring case.+-- 'Left' says why none fits, with the zones there are.+findZone :: Text -> [Zone] -> Either Text Zone+findZone wanted zones = case [zone | zone <- zones, zone.zoneId == ZoneId wanted] of+ zone : _ -> Right zone+ [] -> case [zone | zone <- zones, toCaseFold zone.displayName == toCaseFold wanted] of+ [zone] -> Right zone+ [] -> Left ("No zone named or identified as \"" <> wanted <> "\". Zones: " <> known)+ _ -> Left ("Several zones are named \"" <> wanted <> "\"; use a zone id. Zones: " <> known)+ where+ known = intercalate ", " [zone.displayName <> " (" <> unZoneId zone.zoneId <> ")" | zone <- zones]+ unZoneId (ZoneId zoneId) = zoneId++-- | How to put tracks in a queue.+data Mode+ = -- | At the end of the queue, in order.+ ModeQueue+ | -- | Right after the current track, in order.+ ModeAddNext+ | -- | In place of the queue: the first track at once, the others right+ -- after it, in order.+ ModePlayNow+ deriving stock (Eq, Show, Enum, Bounded)++-- | The name of a mode in the arguments of a tool.+modeName :: Mode -> Text+modeName = \case+ ModeQueue -> "queue"+ ModeAddNext -> "add_next"+ ModePlayNow -> "play_now"++-- | The mode a name stands for.+parseMode :: Text -> Maybe Mode+parseMode name = lookup name [(modeName mode, mode) | mode <- [minBound .. maxBound]]++-- | The actions to perform, in the order to perform them, each with the+-- position of its track in the request. Roon's Add Next puts a track right+-- after the current one, so a list added next goes in reverse order.+plan :: Mode -> [a] -> [(Int, TrackAction, a)]+plan mode tracks = case mode of+ ModeQueue -> [(index, Queue, track) | (index, track) <- indexed]+ ModeAddNext -> [(index, AddNext, track) | (index, track) <- reverse indexed]+ ModePlayNow -> case indexed of+ [] -> []+ (index, first) : rest -> (index, PlayNow, first) : [(i, AddNext, track) | (i, track) <- reverse rest]+ where+ indexed = zip [0 ..] tracks++-- | The media type of an image from a @Content-Type@: its parameters+-- dropped, in lower case. 'Nothing' when it does not name an image.+imageMediaType :: Text -> Maybe Text+imageMediaType contentType+ | "image/" `isPrefixOf` mediaType && T.length mediaType > 6 = Just mediaType+ | otherwise = Nothing+ where+ mediaType = toLower (strip (T.takeWhile (/= ';') contentType))++-- | What an item of the library is to the caller.+data ItemKind+ = -- | Opens another listing.+ KindList+ | -- | Something to play: a track, or what plays a whole album.+ KindPlayable+ | -- | An action of Roon. Never opened from an id: it would be performed.+ KindAction+ | -- | Only displayed.+ KindOther+ deriving stock (Eq, Show, Enum, Bounded)++-- | The kind of an item, from its hint.+itemKind :: Item -> ItemKind+itemKind item = case item.hint of+ Just ListItem -> KindList+ Just ActionList -> KindPlayable+ Just Action -> KindAction+ _ -> KindOther++-- | The name of a kind in the results of a tool.+kindName :: ItemKind -> Text+kindName = \case+ KindList -> "list"+ KindPlayable -> "playable"+ KindAction -> "action"+ KindOther -> "text"++kindLetter :: ItemKind -> Text+kindLetter = T.take 1 . kindName++-- | An item of a listing, as its id names it.+data ItemRef = ItemRef+ { session :: Session+ , kind :: ItemKind+ , key :: Text+ }+ deriving stock (Eq, Show)++-- | The hierarchies of Roon that the library tools open, by name. The+-- settings of Roon are left out.+libraryHierarchies :: [(Text, Hierarchy)]+libraryHierarchies =+ [ ("albums", Albums)+ , ("artists", Artists)+ , ("playlists", Playlists)+ , ("genres", Genres)+ , ("composers", Composers)+ , ("internet_radio", InternetRadio)+ , ("search", Search)+ ]++-- | An id that carries all a later call needs: the hierarchy, the key of+-- the browsing session, what the item is, and its key in the session. The+-- server keeps nothing between calls.+itemId :: Session -> Item -> Maybe Text+itemId Session {hierarchy, multiSessionKey = Just sessionKey} item@Item {itemKey = Just key}+ | Just name <- lookup hierarchy [(found, name) | (name, found) <- libraryHierarchies] =+ Just (intercalate "|" [name, sessionKey, kindLetter (itemKind item), key])+itemId _ _ = Nothing++-- | The item an id names; 'Nothing' when the text is not an id.+decodeItemId :: Text -> Maybe ItemRef+decodeItemId text = case splitOn "|" text of+ [name, sessionKey, letter, key]+ | Just hierarchy <- lookup name libraryHierarchies+ , kind : _ <- [found | found <- [minBound .. maxBound], kindLetter found == letter]+ , not (T.null sessionKey)+ , not (T.null key) ->+ Just ItemRef {session = Session {hierarchy, multiSessionKey = Just sessionKey}, kind, key}+ _ -> Nothing++-- | A text of Roon without its links: @[[487290|Miles Davis]]@ is given+-- as @Miles Davis@.+plainText :: Text -> Text+plainText text = case breakOn "[[" text of+ (before, "") -> before+ (before, rest) -> case breakOn "]]" (T.drop 2 rest) of+ (_, "") -> text+ (link, after) -> before <> snd (breakOnEnd "|" link) <> plainText (T.drop 2 after)++-- | What to do with something to play.+data PlayAction = ActPlayNow | ActAddNext | ActQueue | ActStartRadio | ActShuffle+ deriving stock (Eq, Show, Enum, Bounded)++-- | The name of an action in the arguments of a tool.+playActionName :: PlayAction -> Text+playActionName = \case+ ActPlayNow -> "play_now"+ ActAddNext -> "add_next"+ ActQueue -> "queue"+ ActStartRadio -> "start_radio"+ ActShuffle -> "shuffle"++-- | The English title of the action in Roon.+playActionTitle :: PlayAction -> Text+playActionTitle = \case+ ActPlayNow -> "Play Now"+ ActAddNext -> "Add Next"+ ActQueue -> "Queue"+ ActStartRadio -> "Start Radio"+ ActShuffle -> "Shuffle"++-- | The action a name stands for.+parsePlayAction :: Text -> Maybe PlayAction+parsePlayAction name = lookup name [(playActionName action, action) | action <- [minBound .. maxBound]]++-- | The outputs of a zone a volume change is for: the one with this id or+-- this name, or all of them when none is asked for.+outputsFor :: Maybe Text -> Zone -> Either Text [Output]+outputsFor Nothing zone = Right zone.outputs+outputsFor (Just wanted) zone = case [output | output <- zone.outputs, output.outputId == OutputId wanted || toCaseFold output.displayName == toCaseFold wanted] of+ [] -> Left ("No output named or identified as \"" <> wanted <> "\" in " <> zone.displayName <> ". Outputs: " <> intercalate ", " (map (.displayName) zone.outputs))+ found -> Right found++-- | A volume kept within what the output accepts, when it says.+volumeWithin :: Volume -> Double -> Double+volumeWithin volume = maybe id min volume.maximum . maybe id max volume.minimum
+ src/RoonMcp/Tools.hs view
@@ -0,0 +1,809 @@+-- |+-- Module : RoonMcp.Tools+-- Description : The tools of the server, each over a connection of its own+-- License : BSD-3-Clause+--+-- Every call opens a connection to the Roon Server, registers with the+-- stored token, does its work and closes the connection: the server keeps+-- no state. Connections are taken one at a time ('connectionLock'). Browsing sessions outlive connections on the Roon side, which+-- is what lets a search and the queueing of its candidates be two calls.+-- Images are the exception: they come over HTTP, without a connection.+module RoonMcp.Tools+ ( Context (..)+ , extension+ , serverVersion+ , Effects+ , tools+ , instructions+ , describeError+ ) where++import Data.Aeson (FromJSON (..), Value, object, withObject, (.!=), (.:), (.:?),+ (.=))+import Data.List (sortOn)+import Data.Maybe (catMaybes, mapMaybe)+import Data.Text (Text, intercalate, pack, strip)+import Data.Text qualified as T (null)+import Data.Text.Encoding (encodeUtf8)+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Version (showVersion)+import Effectful (Eff, IOE, MonadIO (liftIO), type (:>))+import Effectful.Concurrent (Concurrent)+import Effectful.Concurrent.MVar (MVar, withMVar)+import Effectful.Error.Static (Error, runErrorNoCallStack, throwError)+import Effectful.FileSystem (FileSystem)+import Effectful.FileSystem.IO (stderr)+import Effectful.FileSystem.IO.ByteString (hPutStrLn)+import Effectful.MCP.Tool (Tool (annotations),+ ToolAnnotations (destructiveHint, idempotentHint, openWorldHint, readOnlyHint),+ ToolResult (isError), errorResult, imageResult,+ noAnnotations, structuredResult, textResult, tool,+ withArguments)+import Paths_roon_mcp (version)+import Roon.Browse (BrowseResult (..), Candidate (..), Hierarchy (..),+ Item (..), List (..), ListHint (..), LoadResult (..),+ Navigation (..), SearchOptions (..), Session (..), browse,+ defaultSearchOptions, load, performAction,+ performTrackAction, searchTracksConcurrently,+ trackActionTitle)+import Roon.Connection (runRoonWithin)+import Roon.Effect.Moo (Moo)+import Roon.Effect.TokenStore (TokenStore, runTokenStoreFile)+import Roon.Effect.WebSocket (ServerAddress (..), WebSocket, runWebSocket,+ traceFrames)+import Roon.Error (RoonError (..))+import Roon.Image (Image (..), defaultImageLimits, fetchImage, fitWithin,+ runImageHttp)+import Roon.Registry (ExtensionInfo (..))+import Roon.Transport (Control (..), DisplayLines (..), Loop (..),+ LoopChange (..), NowPlaying (..), Output (..),+ OutputId (..), PlaybackState (..), QueueEvent (..),+ QueueItem (..), Seek (..), SettingsChange (..),+ Volume (..), VolumeChange (..), VolumeType (..),+ Zone (..), ZoneId (..), ZoneSettings (..),+ changeSettings, changeVolume, control, getZones, mute,+ seek, subscribeQueue, transferZone)+import RoonMcp.Plan (ItemKind (KindAction, KindOther),+ ItemRef (ItemRef, key, kind, session), candidateId,+ decodeCandidateId, decodeItemId, findZone, imageMediaType,+ itemId, itemKind, kindName, libraryHierarchies, modeName,+ outputsFor, parseMode, parsePlayAction, plainText, plan,+ playActionName, playActionTitle, volumeWithin)+import Streamly.Data.Fold (one)+import Streamly.Data.Stream (fold)++-- | What every call needs.+data Context = Context+ { address :: ServerAddress+ , tokenFile :: FilePath+ , registrationTimeout :: Int+ -- ^ Microseconds to wait for the registration; the extension must have+ -- been enabled beforehand.+ , traceLimit :: Maybe Int+ -- ^ When set, every frame is described on stderr, its body cut to this+ -- many characters.+ , connectionLock :: MVar ()+ -- ^ Taken for each connection. Roon keeps one connection per extension:+ -- when a second one registers, it sends an empty frame to the first,+ -- which then fails. Calls served at the same time wait for each other.+ }++-- | The version of this package, as the server gives it to Roon and to+-- MCP clients.+serverVersion :: Text+serverVersion = pack (showVersion version)++-- | How the server introduces itself to Roon.+extension :: ExtensionInfo+extension =+ ExtensionInfo+ { extensionId = "io.github.guillaumedevolpiano.roon-mcp"+ , displayName = "roon-mcp"+ , displayVersion = serverVersion+ , publisher = "roon-mcp"+ , email = "nobody@example.invalid"+ , website = Just "https://github.com/GuillaumedeVolpiano/roon_mcp"+ , requiredServices = ["com.roonlabs.transport:2", "com.roonlabs.browse:1"]+ , optionalServices = []+ , providedServices = []+ }++-- | What the server tells the model about how to use its tools.+instructions :: Text+instructions =+ "Plays music on the Roon system of this machine. To play tracks: call list_zones to pick a zone; \+ \call search_tracks with one query per track, giving the title and the artist; choose among the \+ \candidates by their title and artists (search results give no album); then call queue_tracks \+ \with the chosen candidate ids, in order, and a mode. Candidate ids come from search_tracks: use \+ \them soon after the search. Zones, queue items and candidates may carry an image_key: get_image \+ \returns that image, such as an album cover. For albums, artists, playlists and radios, \+ \browse_library lists or searches the library and play_item plays what it found. set_volume, seek, \+ \set_playback_options and transfer_zone act on a zone."++-- | What the tools need: input and output, threads, and the files where+-- the token is kept.+type Effects es = (IOE :> es, Concurrent :> es, FileSystem :> es)++-- | Run Roon work over a connection of its own.+withConnection+ :: Effects es+ => Context+ -> Eff (Moo : WebSocket : TokenStore : Error RoonError : es) a+ -> Eff es (Either RoonError a)+withConnection context work =+ withMVar context.connectionLock . const . runErrorNoCallStack . runTokenStoreFile context.tokenFile $+ runWebSocket context.address . trace $+ runRoonWithin (Just context.registrationTimeout) extension (const work)+ where+ trace = maybe id (\limit -> traceFrames limit (hPutStrLn stderr . encodeUtf8)) context.traceLimit++-- | Run Roon work and turn a failure into a result the model can read.+roon :: Effects es => Context -> (a -> ToolResult) -> Eff (Moo : WebSocket : TokenStore : Error RoonError : es) a -> Eff es ToolResult+roon context toResult work = either (errorResult . describeError context) toResult <$> withConnection context work++-- | An error of Roon as a text the model can act on.+describeError :: Context -> RoonError -> Text+describeError context = \case+ TimedOut "com.roonlabs.registry:1/register" ->+ "The extension \"roon-mcp\" is not enabled in Roon. Ask the user to run `roon-mcp register` in a terminal \+ \and to enable \"roon-mcp\" in Roon, under Settings, Extensions; then call again."+ ConnectFailed cause ->+ "Cannot reach the Roon Server at " <> pack context.address.host <> ":" <> pack (show context.address.port) <> ": " <> cause+ ConnectionLost -> "The connection to the Roon Server was lost; call again."+ TimedOut request -> "The Roon Server did not answer " <> request <> " in time."+ BrowseFailed message -> "Roon refused: " <> message+ BrowseItemMissing what -> "Roon did not offer " <> what <> "."+ ImageFailed reason -> "Roon gave no image: " <> reason+ UnexpectedReply _ "InvalidItemKey" -> "This id is no longer valid: call browse_library or search_tracks again for fresh ids."+ UnexpectedReply request status -> "Roon answered " <> request <> " with " <> status <> "."+ other -> pack (show other)++-- | The tools of the server, in the order they are listed.+tools :: Effects es => Context -> [Tool es]+tools context =+ [ (tool "list_zones" "List the zones of Roon: where music plays, what plays there, and what it allows." noArguments (\_ -> listZones context))+ {annotations = readOnly}+ , (tool "get_queue" "List the next items of the queue of a zone." queueSchema (withArguments (getQueue context)))+ {annotations = readOnly}+ , ( tool+ "search_tracks"+ "Search the Roon library for tracks, one query per track, all at once. Each query gives its candidates \+ \(id, title, artists), best first, or an error. Put the title and the artist in the query."+ searchSchema+ (withArguments (searchTracks context))+ )+ {annotations = readOnly}+ , ( tool+ "queue_tracks"+ "Put tracks found by search_tracks in the queue of a zone, in the order given. Modes: \"queue\" adds them \+ \at the end of the queue; \"add_next\" right after the current track; \"play_now\" replaces the queue with \+ \these tracks and plays the first at once. Prefer add_next or queue unless the user wants the queue \+ \replaced. Reports each track; a failure does not stop the others."+ queueTracksSchema+ (withArguments (queueTracks context))+ )+ -- Destructive: the play_now mode replaces the queue.+ {annotations = noAnnotations {readOnlyHint = Just False, destructiveHint = Just True, idempotentHint = Just False, openWorldHint = Just False}}+ , ( tool+ "control"+ "Operate the playback of a zone: play, pause, playpause, stop, next or previous."+ controlSchema+ (withArguments (controlZone context))+ )+ {annotations = noAnnotations {readOnlyHint = Just False, destructiveHint = Just False, openWorldHint = Just False}}+ , ( tool+ "browse_library"+ "Browse the Roon library: albums, artists, playlists, genres, composers and internet radios, or search \+ \it for anything. Give one of: a hierarchy to list it from its top, a search text, or the item_id of an \+ \item of kind \"list\" from an earlier call to open it. Items of kind \"playable\" (a track, or \+ \\"Play Album\", \"Play Playlist\") go to play_item, and so does a whole album or playlist by its own \+ \item_id. Long listings come in pages: offset and max_items."+ browseSchema+ (withArguments (browseLibrary context))+ )+ {annotations = readOnly}+ , ( tool+ "play_item"+ "Play something found by browse_library in a zone: a track, an album, a playlist, an artist or a radio, \+ \by its item_id. Actions: \"queue\" adds it at the end of the queue; \"add_next\" right after the \+ \current track; \"play_now\" replaces the queue and plays it at once; \"start_radio\" plays similar \+ \music; \"shuffle\" (playlists) plays it in random order, replacing the queue. Prefer queue or add_next \+ \unless the user wants the queue replaced."+ playItemSchema+ (withArguments (playItem context))+ )+ -- Destructive: play_now, start_radio and shuffle replace the queue.+ {annotations = noAnnotations {readOnlyHint = Just False, destructiveHint = Just True, idempotentHint = Just False, openWorldHint = Just False}}+ , ( tool+ "set_volume"+ "Set or move the volume of a zone, or mute it. The volume is in the units of each output, between the \+ \minimum and the maximum that list_zones gives (some are in decibels, hence negative). Give \"level\" \+ \for a volume, or \"change\" to move it by that much, and \"mute\" to mute or unmute. All the outputs \+ \of the zone are changed unless \"output\" names one. Raise the volume in small moves."+ volumeSchema+ (withArguments (setVolume context))+ )+ {annotations = changes}+ , ( tool+ "seek"+ "Move inside the track that plays in a zone: to a position in seconds from its start, or by a number of \+ \seconds (negative to go back) when \"relative\" is true."+ seekSchema+ (withArguments (seekZone context))+ )+ {annotations = changes}+ , ( tool+ "set_playback_options"+ "Change how a zone plays: shuffle, the Roon Radio that follows the queue (auto_radio), and the loop \+ \(\"disabled\", \"loop\" for the whole queue, \"loop_one\" for the current track). Options left out \+ \stay as they are."+ optionsSchema+ (withArguments (setOptions context))+ )+ {annotations = changes {idempotentHint = Just True}}+ , ( tool+ "transfer_zone"+ "Move what plays in a zone, with its queue, to another zone."+ transferSchema+ (withArguments (transfer context))+ )+ {annotations = changes}+ , ( tool+ "get_image"+ "Fetch an image of Roon, such as the cover of what plays, from an image_key given by list_zones, \+ \get_queue or search_tracks. The image fits in a square of the size asked, in pixels."+ imageSchema+ (withArguments (getImage context))+ )+ {annotations = readOnly}+ ]+ where+ readOnly = noAnnotations {readOnlyHint = Just True, openWorldHint = Just False}+ changes = noAnnotations {readOnlyHint = Just False, destructiveHint = Just False, openWorldHint = Just False}++-- list_zones++listZones :: Effects es => Context -> Eff es ToolResult+listZones context = roon context (structuredResult . object . pure . ("zones" .=) . map zoneSummary) getZones++zoneSummary :: Zone -> Value+zoneSummary zone =+ object $+ [ "zone_id" .= unZoneId zone.zoneId+ , "name" .= zone.displayName+ , "state" .= stateName zone.state+ , "outputs" .= map outputSummary zone.outputs+ , "allowed" .= [name | (name, True) <- [("play", zone.isPlayAllowed), ("pause", zone.isPauseAllowed), ("previous", zone.isPreviousAllowed), ("next", zone.isNextAllowed), ("seek", zone.isSeekAllowed)] :: [(Text, Bool)]]+ ]+ <> catMaybes+ [ ("options" .=) . options <$> zone.settings+ , ("now_playing" .=) . nowPlaying <$> zone.nowPlaying+ , ("queue_items_remaining" .=) <$> zone.queueItemsRemaining+ , ("queue_seconds_remaining" .=) <$> zone.queueTimeRemaining+ ]+ where+ options settings = object ["shuffle" .= settings.shuffle, "auto_radio" .= settings.autoRadio, "loop" .= loopName settings.loop]+ outputSummary output =+ object $+ ["output_id" .= unOutputId output.outputId, "name" .= output.displayName]+ <> catMaybes [("volume" .=) . volumeSummary <$> output.volume]+ volumeSummary volume =+ object $+ ["unit" .= volumeUnit volume.volumeType]+ <> catMaybes+ [ ("level" .=) <$> volume.value+ , ("minimum" .=) <$> volume.minimum+ , ("maximum" .=) <$> volume.maximum+ , ("step" .=) <$> volume.step+ , ("muted" .=) <$> volume.isMuted+ ]+ nowPlaying playing =+ object $+ ["title" .= playing.threeLine.line1]+ <> catMaybes+ [ ("artists" .=) <$> playing.threeLine.line2+ , ("album" .=) <$> playing.threeLine.line3+ , ("seconds" .=) <$> playing.length+ , ("position" .=) <$> playing.seekPosition+ , ("image_key" .=) <$> playing.imageKey+ ]++stateName :: PlaybackState -> Text+stateName = \case+ Playing -> "playing"+ Paused -> "paused"+ Loading -> "loading"+ Stopped -> "stopped"+ OtherState name -> name++unZoneId :: ZoneId -> Text+unZoneId (ZoneId zoneId) = zoneId++unOutputId :: OutputId -> Text+unOutputId (OutputId outputId) = outputId++loopName :: Loop -> Text+loopName = \case+ LoopDisabled -> "disabled"+ LoopQueue -> "loop"+ LoopOne -> "loop_one"+ OtherLoop name -> name++volumeUnit :: VolumeType -> Text+volumeUnit = \case+ VolumeDecibel -> "db"+ VolumeNumber -> "number"+ VolumeIncremental -> "incremental"+ OtherVolumeType name -> name++-- get_queue++data QueueArguments = QueueArguments Text Int++instance FromJSON QueueArguments where+ parseJSON = withObject "arguments" $ \fields ->+ QueueArguments <$> fields .: "zone" <*> fields .:? "max_items" .!= 20++getQueue :: Effects es => Context -> QueueArguments -> Eff es ToolResult+getQueue context (QueueArguments wanted maxItems) =+ withZone context wanted $ \zone ->+ subscribeQueue zone.zoneId (clamp 1 100 maxItems) (fold one) >>= \case+ Just (QueueSubscribed items) -> pure (structuredResult (object ["items" .= map queueEntry items]))+ _ -> pure (errorResult "Roon gave no queue.")+ where+ queueEntry item =+ object $+ ["queue_item_id" .= item.queueItemId, "title" .= item.threeLine.line1]+ <> catMaybes [("artists" .=) <$> item.threeLine.line2, ("album" .=) <$> item.threeLine.line3, ("seconds" .=) <$> item.length, ("image_key" .=) <$> item.imageKey]++-- | Find the zone, then do the work; a zone that is not there gives an+-- error result that lists the zones.+withZone+ :: Effects es+ => Context+ -> Text+ -> (Zone -> Eff (Moo : WebSocket : TokenStore : Error RoonError : es) ToolResult)+ -> Eff es ToolResult+withZone context wanted work =+ roon context id $+ getZones >>= \zones -> either (pure . errorResult) work (findZone wanted zones)++-- search_tracks++data SearchArguments = SearchArguments [Text] Int++instance FromJSON SearchArguments where+ parseJSON = withObject "arguments" $ \fields ->+ SearchArguments <$> fields .: "queries" <*> fields .:? "max_candidates" .!= 5++searchTracks :: Effects es => Context -> SearchArguments -> Eff es ToolResult+searchTracks context (SearchArguments queries maxCandidates)+ | null queries = pure (errorResult "Give at least one query.")+ | length queries > 20 = pure (errorResult "Give at most 20 queries at once.")+ | otherwise = do+ -- Sessions of their own, so that this search does not move those of+ -- earlier ones, whose candidates may still be queued.+ stamp <- liftIO getPOSIXTime+ let prefix = "roon-mcp-" <> pack (show (floor (stamp * 1_000_000) :: Integer)) <> "-"+ options = defaultSearchOptions {maxCandidates = clamp 1 20 maxCandidates}+ roon context (structuredResult . object . pure . ("results" .=) . map result) $+ searchTracksConcurrently options prefix queries+ where+ result (query, outcome) = case outcome of+ Left err -> object ["query" .= query, "error" .= describeError context err]+ Right candidates -> object ["query" .= query, "candidates" .= mapMaybe candidate candidates]+ candidate found =+ (\identifier -> object (["candidate_id" .= identifier, "title" .= found.item.title] <> catMaybes [("artists" .=) <$> found.item.subtitle, ("image_key" .=) <$> found.item.imageKey]))+ <$> candidateId found++-- queue_tracks++data QueueTracksArguments = QueueTracksArguments Text [Text] Text++instance FromJSON QueueTracksArguments where+ parseJSON = withObject "arguments" $ \fields ->+ QueueTracksArguments <$> fields .: "zone" <*> fields .: "candidate_ids" <*> fields .:? "mode" .!= "queue"++queueTracks :: Effects es => Context -> QueueTracksArguments -> Eff es ToolResult+queueTracks context (QueueTracksArguments wanted identifiers modeText) = case parseMode modeText of+ Nothing -> pure (errorResult ("Unknown mode \"" <> modeText <> "\": use queue, add_next or play_now."))+ Just mode+ | null identifiers -> pure (errorResult "Give at least one candidate id.")+ | otherwise -> withZone context wanted $ \zone -> report mode <$> traverse (perform zone) (plan mode identifiers)+ where+ perform zone (index, action, identifier) = case decodeCandidateId identifier of+ Nothing -> pure (index, identifier, action, Left "Not a candidate id from search_tracks.")+ Just candidate ->+ (index,identifier,action,) . either (Left . describeError context) Right+ <$> runErrorNoCallStack (performTrackAction zone.zoneId (trackActionTitle action) candidate)+ report mode outcomes =+ let entries = sortOn (\(index, _, _, _) -> index) outcomes+ failures = length [() | (_, _, _, Left _) <- entries]+ entry (_, identifier, action, outcome) =+ object $+ ["candidate_id" .= identifier, "action" .= trackActionTitle action, "ok" .= either (const False) (const True) outcome]+ <> either (\err -> ["error" .= err]) (const []) outcome+ value = object ["mode" .= modeName mode, "tracks" .= map entry entries, "failures" .= failures]+ in (structuredResult value) {isError = failures == length entries}++-- control++data ControlArguments = ControlArguments Text Text++instance FromJSON ControlArguments where+ parseJSON = withObject "arguments" $ \fields -> ControlArguments <$> fields .: "zone" <*> fields .: "action"++controlZone :: Effects es => Context -> ControlArguments -> Eff es ToolResult+controlZone context (ControlArguments wanted actionName) = case lookup actionName controls of+ Nothing -> pure (errorResult ("Unknown action \"" <> actionName <> "\": use " <> intercalate ", " (map fst controls) <> "."))+ Just which -> withZone context wanted $ \zone -> textResult ("Done: " <> actionName <> " on " <> zone.displayName <> ".") <$ control zone.zoneId which+ where+ controls = [("play", Play), ("pause", Pause), ("playpause", PlayPause), ("stop", Stop), ("next", Next), ("previous", Previous)]++-- browse_library++data BrowseArguments = BrowseArguments (Maybe Text) (Maybe Text) (Maybe Text) Int Int++instance FromJSON BrowseArguments where+ parseJSON = withObject "arguments" $ \fields ->+ BrowseArguments+ <$> fields .:? "hierarchy"+ <*> fields .:? "search"+ <*> fields .:? "item_id"+ <*> fields .:? "offset" .!= 0+ <*> fields .:? "max_items" .!= 30++browseLibrary :: Effects es => Context -> BrowseArguments -> Eff es ToolResult+browseLibrary context (BrowseArguments hierarchyName searchText itemText offset maxItems) = do+ stamp <- liftIO getPOSIXTime+ -- A session of its own for each listing started here, so that it does+ -- not move those of earlier ones, whose ids may still be used.+ let fresh hierarchy = Session {hierarchy, multiSessionKey = Just ("roon-mcp-b-" <> pack (show (floor (stamp * 1_000_000) :: Integer)))}+ case (hierarchyName, searchText, itemText) of+ (Just name, Nothing, Nothing) -> case lookup name [(found, hierarchy) | (found, hierarchy) <- libraryHierarchies, hierarchy /= Search] of+ Just hierarchy -> open (fresh hierarchy) (Top Nothing)+ Nothing -> pure (errorResult ("Unknown hierarchy \"" <> name <> "\": use " <> intercalate ", " browsable <> "."))+ (Nothing, Just text, Nothing)+ | T.null (strip text) -> pure (errorResult "Give a text to search for.")+ | otherwise -> open (fresh Search) (Top (Just text))+ (Nothing, Nothing, Just identifier) -> case decodeItemId identifier of+ Nothing -> pure (errorResult "Not an item_id from browse_library.")+ Just ItemRef {kind = KindAction} -> pure (errorResult "This item is an action: it is not opened. Give play_item the item that offers it.")+ Just ref -> open ref.session (Select ref.key)+ _ -> pure (errorResult "Give exactly one of hierarchy, search and item_id.")+ where+ browsable = [name | (name, hierarchy) <- libraryHierarchies, hierarchy /= Search]+ open current navigation =+ roon context (listing current) $ do+ browse current (Nothing :: Maybe ZoneId) navigation >>= \case+ BrowseMessage message True -> throwError (BrowseFailed message)+ _ -> pure ()+ level <- load current (max 0 offset) (clamp 1 100 maxItems)+ -- Observed with Roon Server 2.75: a key selected in a session that+ -- Roon has forgotten is not refused; the top of the hierarchy+ -- comes back instead. An item opened is never the top.+ case navigation of+ Select _ | level.list.level == 0 -> throwError (UnexpectedReply "com.roonlabs.browse:1/browse" "InvalidItemKey")+ _ -> pure level+ listing current level =+ structuredResult . object $+ [ "title" .= plainText level.list.title+ , "total" .= level.list.count+ , "offset" .= level.offset+ , "items" .= map (entry current) level.items+ ]+ <> catMaybes+ [ ("subtitle" .=) . plainText <$> level.list.subtitle+ , ("image_key" .=) <$> level.list.imageKey+ , if level.list.hint == Just ActionListHint+ then Just ("note" .= ("These are the actions of the item opened: give that item to play_item with the action wanted." :: Text))+ else Nothing+ ]+ entry current item =+ object $+ ["title" .= plainText item.title, "kind" .= kindName (itemKind item)]+ <> catMaybes+ [ ("item_id" .=) <$> itemId current item+ , ("subtitle" .=) . plainText <$> item.subtitle+ , ("image_key" .=) <$> item.imageKey+ ]++-- play_item++data PlayItemArguments = PlayItemArguments Text Text Text++instance FromJSON PlayItemArguments where+ parseJSON = withObject "arguments" $ \fields ->+ PlayItemArguments <$> fields .: "zone" <*> fields .: "item_id" <*> fields .:? "action" .!= "queue"++playItem :: Effects es => Context -> PlayItemArguments -> Eff es ToolResult+playItem context (PlayItemArguments wanted identifier actionName) = case (parsePlayAction actionName, target) of+ (Nothing, _) -> pure (errorResult ("Unknown action \"" <> actionName <> "\": use " <> intercalate ", " (map playActionName [minBound .. maxBound]) <> "."))+ (_, Left problem) -> pure (errorResult problem)+ (Just action, Right candidate) -> withZone context wanted $ \zone ->+ textResult ("Done: " <> playActionTitle action <> " in " <> zone.displayName <> ".")+ <$ performAction zone.zoneId (playActionTitle action) candidate+ where+ -- An item of browse_library, or a candidate of search_tracks.+ target = case (decodeItemId identifier, decodeCandidateId identifier) of+ (Just ItemRef {kind = KindAction}, _) -> Left "This item is an action. Give the item that offers it, with the action wanted."+ (Just ItemRef {kind = KindOther}, _) -> Left "This item cannot be played."+ (Just ref, _) -> Right Candidate {session = ref.session, item = Item {title = "this item", subtitle = Nothing, imageKey = Nothing, itemKey = Just ref.key, hint = Nothing, inputPrompt = Nothing}}+ (Nothing, Just candidate) -> Right candidate+ (Nothing, Nothing) -> Left "Not an item_id from browse_library nor a candidate id from search_tracks."++-- set_volume++data VolumeArguments = VolumeArguments Text (Maybe Text) (Maybe Double) (Maybe Double) (Maybe Bool)++instance FromJSON VolumeArguments where+ parseJSON = withObject "arguments" $ \fields ->+ VolumeArguments <$> fields .: "zone" <*> fields .:? "output" <*> fields .:? "level" <*> fields .:? "change" <*> fields .:? "mute"++setVolume :: Effects es => Context -> VolumeArguments -> Eff es ToolResult+setVolume context (VolumeArguments wanted outputName level change muting)+ | Just _ <- level, Just _ <- change = pure (errorResult "Give level or change, not both.")+ | Nothing <- level, Nothing <- change, Nothing <- muting = pure (errorResult "Give level, change or mute.")+ | otherwise = withZone context wanted $ \zone -> case outputsFor outputName zone of+ Left problem -> pure (errorResult problem)+ Right outputs -> report zone <$> traverse apply outputs+ where+ apply output = (output,) <$> runErrorNoCallStack (adjust output)+ adjust output = case output.volume of+ Nothing -> pure (Just ("Roon does not control the volume of this output." :: Text))+ Just volume -> do+ mapM_ (changeVolume output.outputId . VolumeTo . volumeWithin volume) level+ mapM_ (changeVolume output.outputId . VolumeBy) change+ mapM_ (mute output.outputId) muting+ pure Nothing+ report zone outcomes =+ let entry (output, outcome) =+ object $+ ["output" .= output.displayName, "ok" .= (outcome == Right Nothing)]+ <> either (\err -> ["error" .= describeError context err]) (maybe [] (\why -> ["error" .= why])) outcome+ failures = length [() | (_, outcome) <- outcomes, outcome /= Right Nothing]+ value = object ["zone" .= zone.displayName, "outputs" .= map entry outcomes, "failures" .= failures]+ in (structuredResult value) {isError = failures == length outcomes}++-- seek++data SeekArguments = SeekArguments Text Int Bool++instance FromJSON SeekArguments where+ parseJSON = withObject "arguments" $ \fields ->+ SeekArguments <$> fields .: "zone" <*> fields .: "seconds" <*> fields .:? "relative" .!= False++seekZone :: Effects es => Context -> SeekArguments -> Eff es ToolResult+seekZone context (SeekArguments wanted seconds relative) = withZone context wanted $ \zone ->+ if not zone.isSeekAllowed+ then pure (errorResult ("Seeking is not allowed in " <> zone.displayName <> " at the moment."))+ else+ textResult ("Done: " <> (if relative then "moved by " else "moved to ") <> pack (show seconds) <> " seconds in " <> zone.displayName <> ".")+ <$ seek zone.zoneId (if relative then SeekBy seconds else SeekTo (max 0 seconds))++-- set_playback_options++data OptionsArguments = OptionsArguments Text (Maybe Bool) (Maybe Bool) (Maybe Text)++instance FromJSON OptionsArguments where+ parseJSON = withObject "arguments" $ \fields ->+ OptionsArguments <$> fields .: "zone" <*> fields .:? "shuffle" <*> fields .:? "auto_radio" <*> fields .:? "loop"++setOptions :: Effects es => Context -> OptionsArguments -> Eff es ToolResult+setOptions context (OptionsArguments wanted shuffle autoRadio loopText) = case traverse parseLoop loopText of+ Nothing -> pure (errorResult ("Unknown loop \"" <> maybe "" id loopText <> "\": use disabled, loop or loop_one."))+ Just loop+ | shuffle == Nothing && autoRadio == Nothing && loop == Nothing -> pure (errorResult "Give shuffle, auto_radio or loop.")+ | otherwise -> withZone context wanted $ \zone ->+ textResult ("Done: options changed in " <> zone.displayName <> ".")+ <$ changeSettings zone.zoneId SettingsChange {setShuffle = shuffle, setAutoRadio = autoRadio, setLoop = SetLoop <$> loop}+ where+ parseLoop name = lookup name [("disabled", LoopDisabled), ("loop", LoopQueue), ("loop_one", LoopOne)]++-- transfer_zone++data TransferArguments = TransferArguments Text Text++instance FromJSON TransferArguments where+ parseJSON = withObject "arguments" $ \fields -> TransferArguments <$> fields .: "from_zone" <*> fields .: "to_zone"++transfer :: Effects es => Context -> TransferArguments -> Eff es ToolResult+transfer context (TransferArguments fromName toName) =+ roon context id $+ getZones >>= \zones -> case (findZone fromName zones, findZone toName zones) of+ (Left problem, _) -> pure (errorResult problem)+ (_, Left problem) -> pure (errorResult problem)+ (Right from, Right to)+ | from.zoneId == to.zoneId -> pure (errorResult "The two zones are the same.")+ | otherwise -> textResult ("Done: moved from " <> from.displayName <> " to " <> to.displayName <> ".") <$ transferZone from.zoneId to.zoneId++-- get_image++data ImageArguments = ImageArguments Text Int++instance FromJSON ImageArguments where+ parseJSON = withObject "arguments" $ \fields ->+ ImageArguments <$> fields .: "image_key" <*> fields .:? "size" .!= 300++-- | Images come over HTTP, without a connection of the extension: no+-- registration, and no need to wait for the calls that hold one.+getImage :: Effects es => Context -> ImageArguments -> Eff es ToolResult+getImage context (ImageArguments key size) =+ runErrorNoCallStack (runImageHttp defaultImageLimits (fetchImage context.address key (fitWithin (clamp 32 1024 size)))) >>= \case+ Left err -> pure (errorResult (describeError context err))+ Right image -> pure $ case imageMediaType image.contentType of+ Just mediaType -> imageResult mediaType image.bytes+ Nothing -> errorResult ("Roon answered with \"" <> image.contentType <> "\", which is not an image.")++-- Schemas++noArguments :: Value+noArguments = object ["type" .= ("object" :: Text), "additionalProperties" .= False]++zoneProperty :: Value+zoneProperty = object ["type" .= ("string" :: Text), "description" .= ("A zone id or name, from list_zones." :: Text)]++browseSchema :: Value+browseSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "hierarchy" .= object ["type" .= ("string" :: Text), "enum" .= [name | (name, hierarchy) <- libraryHierarchies, hierarchy /= Search], "description" .= ("List this part of the library from its top." :: Text)]+ , "search" .= object ["type" .= ("string" :: Text), "description" .= ("Search the library for this text: artists, albums, tracks, playlists and more." :: Text)]+ , "item_id" .= object ["type" .= ("string" :: Text), "description" .= ("Open this item of kind \"list\" from an earlier browse_library." :: Text)]+ , "offset" .= object ["type" .= ("integer" :: Text), "minimum" .= (0 :: Int), "default" .= (0 :: Int)]+ , "max_items" .= object ["type" .= ("integer" :: Text), "minimum" .= (1 :: Int), "maximum" .= (100 :: Int), "default" .= (30 :: Int)]+ ]+ , "additionalProperties" .= False+ ]++playItemSchema :: Value+playItemSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "item_id" .= object ["type" .= ("string" :: Text), "description" .= ("An item_id from browse_library, or a candidate id from search_tracks." :: Text)]+ , "action" .= object ["type" .= ("string" :: Text), "enum" .= map playActionName [minBound .. maxBound], "default" .= ("queue" :: Text)]+ ]+ , "required" .= ["zone" :: Text, "item_id"]+ , "additionalProperties" .= False+ ]++volumeSchema :: Value+volumeSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "output" .= object ["type" .= ("string" :: Text), "description" .= ("An output id or name of the zone, from list_zones; all its outputs when left out." :: Text)]+ , "level" .= object ["type" .= ("number" :: Text), "description" .= ("The volume to set, in the units of the output." :: Text)]+ , "change" .= object ["type" .= ("number" :: Text), "description" .= ("How much to move the volume, in the units of the output; negative to lower it." :: Text)]+ , "mute" .= object ["type" .= ("boolean" :: Text)]+ ]+ , "required" .= ["zone" :: Text]+ , "additionalProperties" .= False+ ]++seekSchema :: Value+seekSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "seconds" .= object ["type" .= ("integer" :: Text)]+ , "relative" .= object ["type" .= ("boolean" :: Text), "default" .= False]+ ]+ , "required" .= ["zone" :: Text, "seconds"]+ , "additionalProperties" .= False+ ]++optionsSchema :: Value+optionsSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "shuffle" .= object ["type" .= ("boolean" :: Text)]+ , "auto_radio" .= object ["type" .= ("boolean" :: Text)]+ , "loop" .= object ["type" .= ("string" :: Text), "enum" .= ["disabled" :: Text, "loop", "loop_one"]]+ ]+ , "required" .= ["zone" :: Text]+ , "additionalProperties" .= False+ ]++transferSchema :: Value+transferSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties" .= object ["from_zone" .= zoneProperty, "to_zone" .= zoneProperty]+ , "required" .= ["from_zone" :: Text, "to_zone"]+ , "additionalProperties" .= False+ ]++imageSchema :: Value+imageSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "image_key" .= object ["type" .= ("string" :: Text), "description" .= ("An image_key from list_zones, get_queue or search_tracks." :: Text)]+ , "size" .= object ["type" .= ("integer" :: Text), "minimum" .= (32 :: Int), "maximum" .= (1024 :: Int), "default" .= (300 :: Int)]+ ]+ , "required" .= ["image_key" :: Text]+ , "additionalProperties" .= False+ ]++queueSchema :: Value+queueSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "max_items" .= object ["type" .= ("integer" :: Text), "minimum" .= (1 :: Int), "maximum" .= (100 :: Int), "default" .= (20 :: Int)]+ ]+ , "required" .= ["zone" :: Text]+ , "additionalProperties" .= False+ ]++searchSchema :: Value+searchSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "queries"+ .= object+ [ "type" .= ("array" :: Text)+ , "items" .= object ["type" .= ("string" :: Text)]+ , "minItems" .= (1 :: Int)+ , "maxItems" .= (20 :: Int)+ , "description" .= ("One query per track: its title and its artist." :: Text)+ ]+ , "max_candidates" .= object ["type" .= ("integer" :: Text), "minimum" .= (1 :: Int), "maximum" .= (20 :: Int), "default" .= (5 :: Int)]+ ]+ , "required" .= ["queries" :: Text]+ , "additionalProperties" .= False+ ]++queueTracksSchema :: Value+queueTracksSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "candidate_ids"+ .= object+ [ "type" .= ("array" :: Text)+ , "items" .= object ["type" .= ("string" :: Text)]+ , "minItems" .= (1 :: Int)+ , "description" .= ("Candidate ids from search_tracks, in the order to play them." :: Text)+ ]+ , "mode" .= object ["type" .= ("string" :: Text), "enum" .= map modeName [minBound .. maxBound], "default" .= ("queue" :: Text)]+ ]+ , "required" .= ["zone" :: Text, "candidate_ids"]+ , "additionalProperties" .= False+ ]++controlSchema :: Value+controlSchema =+ object+ [ "type" .= ("object" :: Text)+ , "properties"+ .= object+ [ "zone" .= zoneProperty+ , "action" .= object ["type" .= ("string" :: Text), "enum" .= ["play", "pause", "playpause", "stop", "next", "previous" :: Text]]+ ]+ , "required" .= ["zone" :: Text, "action"]+ , "additionalProperties" .= False+ ]++clamp :: Int -> Int -> Int -> Int+clamp low high = max low . min high
+ test/Main.hs view
@@ -0,0 +1,159 @@+module Main (main) where++import Control.Concurrent.MVar (newMVar)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.KeyMap (fromList)+import Data.Aeson.KeyMap qualified as JK (lookup)+import Data.Foldable (toList)+import Data.Text (Text)+import Effectful (runEff)+import Effectful.Concurrent (runConcurrent)+import Effectful.FileSystem (runFileSystem)+import Effectful.MCP.Server (handleRequest, implementation, serverConfig)+import Roon.Browse (Candidate (..), Hierarchy (..), Item (..), ItemHint (..),+ Session (..), TrackAction (..))+import Roon.Effect.WebSocket (localServer)+import Roon.Transport (Output (..), OutputId (..), PlaybackState (..),+ Volume (..), VolumeType (..), Zone (..), ZoneId (..))+import RoonMcp.Plan (ItemKind (KindList, KindPlayable),+ ItemRef (ItemRef, key, kind, session),+ Mode (ModeAddNext, ModePlayNow, ModeQueue),+ PlayAction (ActAddNext, ActPlayNow, ActQueue, ActShuffle, ActStartRadio),+ candidateId, decodeCandidateId, decodeItemId, findZone,+ imageMediaType, itemId, outputsFor, parseMode,+ parsePlayAction, plainText, plan, playActionTitle,+ volumeWithin)+import RoonMcp.Tools (Context (..), tools)+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+ testGroup+ "roon-mcp"+ [ testGroup+ "plan"+ [ testCase "queue: in order, at the end" $+ plan ModeQueue "abc" @?= [(0, Queue, 'a'), (1, Queue, 'b'), (2, Queue, 'c')]+ , testCase "add_next: in reverse, so that they play in order" $+ plan ModeAddNext "abc" @?= [(2, AddNext, 'c'), (1, AddNext, 'b'), (0, AddNext, 'a')]+ , testCase "play_now: the first at once, the others after it in reverse" $+ plan ModePlayNow "abc" @?= [(0, PlayNow, 'a'), (2, AddNext, 'c'), (1, AddNext, 'b')]+ , testCase "play_now with one track" $ plan ModePlayNow "a" @?= [(0, PlayNow, 'a')]+ , testCase "modes by name" $ map parseMode ["queue", "add_next", "play_now", "shuffle"] @?= [Just ModeQueue, Just ModeAddNext, Just ModePlayNow, Nothing]+ ]+ , testGroup+ "candidate ids"+ [ testCase "carry the session and the item key" $ do+ let found = Candidate {session = Session Search (Just "roon-mcp-1-0"), item = trackItem "First Song" "2:0"}+ candidateId found @?= Just "roon-mcp-1-0|2:0"+ fmap (\candidate -> (candidate.session, candidate.item.itemKey)) (decodeCandidateId "roon-mcp-1-0|2:0")+ @?= Just (Session Search (Just "roon-mcp-1-0"), Just "2:0")+ , testCase "reject what is not one" $ map decodeCandidateId ["", "nokey", "|2:0", "session|"] @?= [Nothing, Nothing, Nothing, Nothing]+ ]+ , testGroup+ "zones"+ [ testCase "by id" $ fmap (.displayName) (findZone "zone-0002" zones) @?= Right "Kitchen"+ , testCase "by name, ignoring case" $ fmap (.zoneId) (findZone "living room" zones) @?= Right (ZoneId "zone-0001")+ , testCase "an unknown zone lists the zones" $+ findZone "Garage" zones @?= Left "No zone named or identified as \"Garage\". Zones: Living Room (zone-0001), Kitchen (zone-0002)"+ ]+ , testGroup+ "item ids"+ [ testCase "carry the hierarchy, the session, the kind and the key" $ do+ let current = Session Albums (Just "roon-mcp-b-1")+ itemId current (trackItem "Play Album" "85:0") @?= Just "albums|roon-mcp-b-1|p|85:0"+ itemId current (trackItem "An Album" "83:4") {hint = Just ListItem} @?= Just "albums|roon-mcp-b-1|l|83:4"+ itemId current (trackItem "Play Now" "88:0") {hint = Just Action} @?= Just "albums|roon-mcp-b-1|a|88:0"+ decodeItemId "albums|roon-mcp-b-1|l|83:4" @?= Just ItemRef {session = current, kind = KindList, key = "83:4"}+ decodeItemId "search|s|p|2:0" @?= Just ItemRef {session = Session Search (Just "s"), kind = KindPlayable, key = "2:0"}+ , testCase "items without a key, sessions without one and the settings have no id" $ do+ itemId (Session Albums (Just "s")) (trackItem "No Results" "x") {itemKey = Nothing} @?= Nothing+ itemId (Session Albums Nothing) (trackItem "An Album" "1:0") @?= Nothing+ itemId (Session Settings (Just "s")) (trackItem "Setup" "1:0") @?= Nothing+ , testCase "reject what is not one" $+ map decodeItemId ["", "albums|s|l", "settings|s|l|1:0", "albums||l|1:0", "albums|s|z|1:0", "albums|s|l|", "roon-mcp-1-0|2:0"]+ @?= replicate 7 Nothing+ ]+ , testGroup+ "texts of Roon"+ [ testCase "links are given as their text" $+ map plainText ["Miles Davis", "[[487290|Miles Davis]]", "[[1|A]] / [[2|B]] and C", "open [[ only", "[[3|unclosed"]+ @?= ["Miles Davis", "Miles Davis", "A / B and C", "open [[ only", "[[3|unclosed"]+ ]+ , testGroup+ "play actions"+ [ testCase "by name" $+ map parsePlayAction ["play_now", "add_next", "queue", "start_radio", "shuffle", "Play Now", ""]+ @?= [Just ActPlayNow, Just ActAddNext, Just ActQueue, Just ActStartRadio, Just ActShuffle, Nothing, Nothing]+ , testCase "as Roon titles them" $+ map playActionTitle [minBound .. maxBound] @?= ["Play Now", "Add Next", "Queue", "Start Radio", "Shuffle"]+ ]+ , testGroup+ "volume"+ [ testCase "all the outputs of a zone, or the one named or identified" $ do+ let zone = (zoneNamed "zone-0001" "Living Room") {outputs = [output "out-1" "Amplifier", output "out-2" "Kitchen Speaker"]}+ fmap (map (.displayName)) (outputsFor Nothing zone) @?= Right ["Amplifier", "Kitchen Speaker"]+ fmap (map (.displayName)) (outputsFor (Just "kitchen speaker") zone) @?= Right ["Kitchen Speaker"]+ fmap (map (.displayName)) (outputsFor (Just "out-1") zone) @?= Right ["Amplifier"]+ fmap (map (.displayName)) (outputsFor (Just "Garage") zone)+ @?= Left "No output named or identified as \"Garage\" in Living Room. Outputs: Amplifier, Kitchen Speaker"+ , testCase "a level is kept within what the output accepts" $ do+ let bounded = Volume {volumeType = VolumeDecibel, minimum = Just (-80), maximum = Just 0, value = Just (-30), step = Just 1, isMuted = Just False}+ map (volumeWithin bounded) [-100, -30, 12] @?= [-80, -30, 0]+ volumeWithin bounded {minimum = Nothing, maximum = Nothing} 500 @?= 500+ ]+ , testGroup+ "image media types"+ [ testCase "parameters and case are dropped" $+ map imageMediaType ["image/jpeg", "Image/PNG; q=1", " image/webp "] @?= [Just "image/jpeg", Just "image/png", Just "image/webp"]+ , testCase "what is not an image is refused" $+ map imageMediaType ["", "text/plain", "image/", "application/json"] @?= [Nothing, Nothing, Nothing, Nothing]+ ]+ , testCase "tools/list gives the twelve tools, each with an object schema" $ do+ lock <- newMVar ()+ let context = Context {address = localServer, tokenFile = "/nonexistent/tokens.json", registrationTimeout = 1, traceLimit = Nothing, connectionLock = lock}+ result <- runEff . runConcurrent . runFileSystem $+ handleRequest (serverConfig (implementation "roon-mcp" "0") (tools context)) "tools/list" (fromList [("_meta", meta)])+ case result of+ Right (Object fields) | Just (Array listed) <- JK.lookup "tools" fields -> do+ map (field "name") (toList listed) @?= map (Just . String) ["list_zones", "get_queue", "search_tracks", "queue_tracks", "control", "browse_library", "play_item", "set_volume", "seek", "set_playback_options", "transfer_zone", "get_image"]+ map (\definition -> field "inputSchema" definition >>= field "type") (toList listed) @?= replicate 12 (Just (String "object"))+ other -> assertFailure ("unexpected: " <> show other)+ ]+ where+ meta = object ["io.modelcontextprotocol/protocolVersion" .= ("2026-07-28" :: Text), "io.modelcontextprotocol/clientCapabilities" .= object []]+ field key = \case+ Object fields -> JK.lookup key fields+ _ -> Nothing++trackItem :: Text -> Text -> Item+trackItem title key = Item {title, subtitle = Nothing, imageKey = Nothing, itemKey = Just key, hint = Just ActionList, inputPrompt = Nothing}++output :: Text -> Text -> Output+output identifier name =+ Output {outputId = OutputId identifier, zoneId = ZoneId "zone-0001", displayName = name, volume = Nothing, sourceControls = [], canGroupWithOutputIds = []}++zones :: [Zone]+zones = [zoneNamed "zone-0001" "Living Room", zoneNamed "zone-0002" "Kitchen"]++zoneNamed :: Text -> Text -> Zone+zoneNamed identifier name =+ Zone+ { zoneId = ZoneId identifier+ , displayName = name+ , outputs = []+ , state = Stopped+ , isPreviousAllowed = False+ , isNextAllowed = False+ , isPauseAllowed = False+ , isPlayAllowed = True+ , isSeekAllowed = False+ , queueItemsRemaining = Nothing+ , queueTimeRemaining = Nothing+ , settings = Nothing+ , nowPlaying = Nothing+ }