packages feed

baikai-mcp-0.1.0.0: src/Baikai/Mcp/Transport/Stream.hs

-- | MCP over a caller-owned byte stream: the stdio binding without the
-- process.
--
-- Each message is one line of compact UTF-8 JSON. The caller starts the
-- server, hands over its output (to read) and input (to write), and keeps
-- ownership of the process: this module launches, restarts and kills
-- nothing. One reader thread routes replies by request identifier and
-- subscription notifications by @io.modelcontextprotocol/subscriptionId@.
-- Writers are serialized so lines never interleave.
--
-- There is no per-request stream to close, so cancelling a request (or a
-- timeout) sends @notifications/cancelled@, and a late reply is dropped.
-- An end of input fails every request still waiting; a tool call among
-- them has an uncertain outcome.
module Baikai.Mcp.Transport.Stream
  ( McpStream (..),
    handleStream,
    streamBinding,
  )
where

import Baikai.Mcp.Error
import Baikai.Mcp.Internal.Binding
import Baikai.Mcp.Internal.Http (rethrowAsync)
import Baikai.Mcp.Internal.Mux qualified as Mux
import Baikai.Mcp.Protocol
import Control.Concurrent.Async (async, cancel)
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Exception (SomeException, mask, onException, try)
import Data.Aeson (toJSON)
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as BS8
import Data.IORef
import Data.Text (Text)
import System.IO (Handle, hClose, hFlush)

-- | The two halves of a connection to a server, supplied by the caller.
data McpStream = McpStream
  { -- | Read the next chunk from the server; empty at end of input.
    readChunk :: IO ByteString,
    -- | Write bytes to the server.
    writeChunk :: ByteString -> IO (),
    -- | Run when the connection is released, for example closing the
    -- server's input so that it exits. The process stays the caller's.
    closeStream :: Maybe (IO ())
  }

-- | A stream over the server's output (read) and input (write) handles.
-- Releasing the connection closes the input handle.
handleStream :: Handle -> Handle -> McpStream
handleStream fromServer toServer =
  McpStream
    { readChunk = BS.hGetSome fromServer 65536,
      writeChunk = \b -> BS.hPut toServer b >> hFlush toServer,
      closeStream = Just (hClose toServer)
    }

-- | A multiplexed binding over the stream. The reader starts at once.
streamBinding :: Text -> WireLimits -> McpStream -> IO Binding
streamBinding label lim s = do
  writeLock <- newMVar ()
  handlerRef <- newIORef (\_ _ _ -> pure ())
  mux <- Mux.newMux (\rid m p -> readIORef handlerRef >>= \h -> h rid m p)
  released <- newIORef False
  let writeLine :: ByteString -> IO (Either McpError ())
      writeLine bytes
        | BS8.elem '\n' bytes = pure (Left (mcpError InvalidInput NotSent "an encoded message contains a newline"))
        | otherwise = do
            failed <- Mux.failure mux
            case failed of
              Just e -> pure (Left e {delivery = NotSent})
              Nothing -> do
                r <- try @SomeException (withMVar writeLock (\_ -> s.writeChunk (bytes <> "\n")))
                case r of
                  Left e -> rethrowAsync e >> pure (Left (mcpError TransportFailure Uncertain "writing to the server failed"))
                  Right () -> pure (Right ())
      cancelRequest rid = do
        _ <- try @SomeException (writeLine (BS.toStrict (Aeson.encode (encodeNotification "notifications/cancelled" (KeyMap.fromList [("requestId", toJSON rid)])))))
        pure ()
  reader <- async (readLoop lim s mux)
  let release = do
        was <- atomicModifyIORef' released (True,)
        if was
          then pure ()
          else do
            cancel reader
            Mux.failAll mux (mcpError ConnectionReleased NotSent "the MCP connection has been released")
            maybe (pure ()) (\c -> () <$ try @SomeException c) s.closeStream
      exchange _ ex = do
        reg <- Mux.register mux ex.requestId
        case reg of
          Left e -> pure (Left e)
          Right waiter -> mask $ \restore -> do
            written <- restore (writeLine ex.body) `onException` Mux.unregister mux ex.requestId
            case written of
              Left e -> Mux.unregister mux ex.requestId >> pure (Left e)
              Right () -> do
                r <-
                  restore (Mux.await waiter)
                    `onException` (Mux.unregister mux ex.requestId >> cancelRequest ex.requestId)
                Mux.unregister mux ex.requestId
                pure r
      openStream _ ex = do
        reg <- Mux.registerListener mux ex.requestId
        case reg of
          Left e -> pure (Left e)
          Right queue -> do
            written <- writeLine ex.body
            case written of
              Left e -> Mux.unregisterListener mux ex.requestId >> pure (Left e)
              Right () -> do
                ended <- newIORef False
                let next = do
                      item <- atomically (readTQueue queue)
                      case item of
                        StreamEnded _ -> writeIORef ended True
                        StreamMessage (IncomingResponse _ _) -> writeIORef ended True
                        StreamMessage (IncomingNotification "notifications/cancelled" _) -> writeIORef ended True
                        _ -> pure ()
                      pure item
                    close = do
                      Mux.unregisterListener mux ex.requestId
                      done <- atomicModifyIORef' ended (True,)
                      if done then pure () else cancelRequest ex.requestId
                pure (Right MessageStream {next = next, close = close})
  pure
    Binding
      { shape = ByteStream,
        endpointText = label,
        origin = label,
        exchange = exchange,
        post = \_ body -> writeLine body,
        openStream = Just openStream,
        terminate = Nothing,
        release = release,
        unsolicited = Just handlerRef
      }

-- | Split input into lines under the frame limit and route each message.
-- Any unreadable line, oversized line or end of input fails the channel.
readLoop :: WireLimits -> McpStream -> Mux.Mux -> IO ()
readLoop lim s mux = do
  r <- try @SomeException (go BS.empty)
  case r of
    Left e -> do
      rethrowAsync e
      Mux.failAll mux (mcpError TransportFailure Uncertain "reading from the server failed")
    Right () -> pure ()
  where
    go buffered = case BS8.elemIndex '\n' buffered of
      Just i
        | i > lim.maxFrameBytes ->
            Mux.failAll mux (mcpError LimitExceeded Uncertain "the server wrote a line longer than the frame limit")
      Just i -> do
        let line = BS8.takeWhile (/= '\r') (BS.take i buffered)
            rest = BS.drop (i + 1) buffered
        if BS.null (BS8.strip line)
          then go rest
          else case Aeson.eitherDecodeStrict line of
            Left _ -> Mux.failAll mux (mcpError MalformedReply Uncertain "the server wrote a line that is not JSON")
            Right v -> case decodeMessage v of
              Left why -> Mux.failAll mux (mcpError MalformedReply Uncertain ("the server wrote an invalid message: " <> why))
              Right msg -> Mux.dispatch mux (BS.length line) msg >> go rest
      Nothing
        | BS.length buffered > lim.maxFrameBytes ->
            Mux.failAll mux (mcpError LimitExceeded Uncertain "the server wrote a line longer than the frame limit")
        | otherwise -> do
            chunk <- s.readChunk
            if BS.null chunk
              then Mux.failAll mux (mcpError TransportFailure Uncertain "the server closed its output")
              else go (buffered <> chunk)