baikai-mcp-0.1.0.0: src/Baikai/Mcp/Internal/Mux.hs
-- | Reply routing for bindings where every message shares one channel: the
-- deprecated HTTP+SSE transport and caller-owned byte streams.
--
-- One reader feeds 'dispatch'. A request registers a waiter /before/ it
-- is written, so its reply cannot race past it. A response whose waiter is
-- gone (cancelled or timed out) is dropped. Notifications carrying an
-- @io.modelcontextprotocol/subscriptionId@ go to the listener registered
-- under that identifier; a server's @notifications/cancelled@ for a
-- listener and the response to a listener's own request both end it. When
-- the channel fails every waiter and listener receives that failure.
--
-- This module is internal. Its contents may change in any release.
module Baikai.Mcp.Internal.Mux
( Mux,
newMux,
register,
unregister,
await,
registerListener,
unregisterListener,
dispatch,
failAll,
failure,
)
where
import Baikai.Mcp.Error
import Baikai.Mcp.Internal.Binding
import Baikai.Mcp.Protocol
import Control.Concurrent.STM
import Data.Aeson (Value (..), fromJSON)
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Text (Text)
data Mux = Mux
{ waiters :: !(TVar (Map RequestId (TMVar (Either McpError Reply)))),
listeners :: !(TVar (Map RequestId (TQueue StreamItem))),
failed :: !(TVar (Maybe McpError)),
unsolicitedRequest :: RequestId -> Text -> Object -> IO ()
}
newMux :: (RequestId -> Text -> Object -> IO ()) -> IO Mux
newMux onRequest = do
w <- newTVarIO Map.empty
l <- newTVarIO Map.empty
f <- newTVarIO Nothing
pure Mux {waiters = w, listeners = l, failed = f, unsolicitedRequest = onRequest}
failure :: Mux -> IO (Maybe McpError)
failure m = readTVarIO m.failed
-- | Register a waiter for a request about to be written.
register :: Mux -> RequestId -> IO (Either McpError (TMVar (Either McpError Reply)))
register m rid = atomically $ do
f <- readTVar m.failed
case f of
Just e -> pure (Left e {delivery = NotSent})
Nothing -> do
v <- newEmptyTMVar
modifyTVar' m.waiters (Map.insert rid v)
pure (Right v)
unregister :: Mux -> RequestId -> IO ()
unregister m rid = atomically (modifyTVar' m.waiters (Map.delete rid))
await :: TMVar (Either McpError Reply) -> IO (Either McpError Reply)
await = atomically . readTMVar
registerListener :: Mux -> RequestId -> IO (Either McpError (TQueue StreamItem))
registerListener m rid = atomically $ do
f <- readTVar m.failed
case f of
Just e -> pure (Left e {delivery = NotSent})
Nothing -> do
q <- newTQueue
modifyTVar' m.listeners (Map.insert rid q)
pure (Right q)
unregisterListener :: Mux -> RequestId -> IO ()
unregisterListener m rid = atomically (modifyTVar' m.listeners (Map.delete rid))
-- | Route one message read from the channel. @size@ is its byte count.
dispatch :: Mux -> Int -> IncomingMessage -> IO ()
dispatch m size = \case
-- A response nobody waits for belongs to a cancelled request and is
-- dropped.
IncomingResponse (Just rid) r -> atomically $ do
ws <- readTVar m.waiters
case Map.lookup rid ws of
Just v -> do
_ <- tryPutTMVar v (Right Reply {outcome = r, bytes = size, status = Nothing, sessionId = Nothing})
modifyTVar' m.waiters (Map.delete rid)
Nothing -> do
ls <- readTVar m.listeners
case Map.lookup rid ls of
Just q -> writeTQueue q (StreamMessage (IncomingResponse (Just rid) r))
Nothing -> pure ()
IncomingResponse Nothing _ -> pure ()
msg@(IncomingNotification method params) -> atomically $ do
ls <- readTVar m.listeners
let target = case subscriptionOf params of
Just sid -> Just sid
Nothing
| method == "notifications/cancelled" -> cancelledId params
| otherwise -> Nothing
case target >>= (`Map.lookup` ls) of
Just q -> writeTQueue q (StreamMessage msg)
Nothing -> pure ()
IncomingRequest rid method params -> m.unsolicitedRequest rid method params
subscriptionOf :: Object -> Maybe RequestId
subscriptionOf params = case KeyMap.lookup "_meta" params of
Just (Object meta) -> KeyMap.lookup metaSubscriptionId meta >>= fromResult . fromJSON
_ -> Nothing
cancelledId :: Object -> Maybe RequestId
cancelledId params = KeyMap.lookup "requestId" params >>= fromResult . fromJSON
fromResult :: Aeson.Result a -> Maybe a
fromResult = \case
Aeson.Success a -> Just a
Aeson.Error _ -> Nothing
-- | The channel ended: fail every waiter and listener and refuse new ones.
failAll :: Mux -> McpError -> IO ()
failAll m e = atomically $ do
writeTVar m.failed . Just =<< (maybe e id <$> readTVar m.failed)
ws <- readTVar m.waiters
mapM_ (\v -> tryPutTMVar v (Left e)) (Map.elems ws)
writeTVar m.waiters Map.empty
ls <- readTVar m.listeners
mapM_ (\q -> writeTQueue q (StreamEnded (Just e))) (Map.elems ls)
writeTVar m.listeners Map.empty