baikai-mcp-0.1.0.0: test/StreamSpec.hs
module StreamSpec (tests) where
import Baikai.Mcp.Client
import Baikai.Mcp.Protocol
import Baikai.Mcp.Tool
import Baikai.Mcp.Transport.Stream
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Async, async, cancel, poll, wait)
import Control.Concurrent.STM
import Control.Exception (bracket, finally)
import Control.Monad (forM_, when)
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object)
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 McpStub (waitFor)
import System.IO (hClose, hFlush)
import System.Process (createPipe)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))
tests :: TestTree
tests =
testGroup
"Caller-owned streams"
[ framing,
eras,
lifecycle,
handles
]
-- ---------------------------------------------------------------------------
-- In-memory pipes and scripted servers
data Pipe = Pipe
{ client :: McpStream,
toServer :: TQueue (Maybe ByteString),
toClient :: TQueue (Maybe ByteString),
readsInFlight :: IORef Int,
clientClosedIt :: IORef Bool
}
newPipe :: IO Pipe
newPipe = do
c2s <- newTQueueIO
s2c <- newTQueueIO
inflight <- newIORef 0
closed <- newIORef False
let readChunk = do
atomicModifyIORef' inflight (\n -> (n + 1, ()))
(maybe "" id <$> atomically (readTQueue s2c)) `finally` atomicModifyIORef' inflight (\n -> (n - 1, ()))
pure
Pipe
{ client =
McpStream
{ readChunk = readChunk,
writeChunk = \b -> atomically (writeTQueue c2s (Just b)),
closeStream = Just (writeIORef closed True >> atomically (writeTQueue c2s Nothing))
},
toServer = c2s,
toClient = s2c,
readsInFlight = inflight,
clientClosedIt = closed
}
data Server = Server
{ received :: IORef [Value],
send :: Value -> IO (),
sendRaw :: ByteString -> IO (),
closeOutput :: IO ()
}
-- | Run a line-oriented server over the pipe until the client closes it.
runServer :: Pipe -> (Server -> Value -> IO ()) -> IO (Server, Async ())
runServer p handler = do
rec' <- newIORef []
let srv =
Server
{ received = rec',
send = \v -> atomically (writeTQueue p.toClient (Just (BS.toStrict (Aeson.encode v) <> "\n"))),
sendRaw = \b -> atomically (writeTQueue p.toClient (Just b)),
closeOutput = atomically (writeTQueue p.toClient Nothing)
}
loop buffered = case BS8.elemIndex '\n' buffered of
Just i -> do
let line = BS.take i buffered
case Aeson.decodeStrict line of
Just v -> modifyIORef' rec' (<> [v]) >> handler srv v
Nothing -> pure ()
loop (BS.drop (i + 1) buffered)
Nothing -> do
chunk <- atomically (readTQueue p.toServer)
case chunk of
Nothing -> pure ()
Just c -> loop (buffered <> c)
a <- async (loop BS.empty)
pure (srv, a)
field :: Aeson.Key -> Value -> Maybe Value
field k = \case
Object o -> KeyMap.lookup k o
_ -> Nothing
paramsOf :: Value -> Object
paramsOf v = case field "params" v of
Just (Object o) -> o
_ -> KeyMap.empty
methodOf :: Value -> Maybe Text
methodOf v = case field "method" v of
Just (String m) -> Just m
_ -> Nothing
reply :: Value -> [(Aeson.Key, Value)] -> Value
reply req fields = object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "id" req, "result" .= object fields]
replyError :: Value -> Int -> Text -> Maybe Value -> Value
replyError req c m d = object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "id" req, "error" .= object (["code" .= c, "message" .= m] <> maybe [] (\x -> ["data" .= x]) d)]
toolsPage :: Value -> Object -> Value
toolsPage req p = case KeyMap.lookup "cursor" p of
Nothing -> reply req ["tools" .= [tool "echo"], "nextCursor" .= ("2" :: Text)]
Just _ -> reply req ["tools" .= [tool "other"]]
where
tool :: Text -> Value
tool n = object ["name" .= n, "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["msg" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Msg" :: Text)]]]]
echoResult :: Value -> Object -> Value
echoResult req p =
let msg = case KeyMap.lookup "arguments" p of
Just (Object a) | Just (String m) <- KeyMap.lookup "msg" a -> m
_ -> "?"
in reply req ["content" .= [object ["type" .= ("text" :: Text), "text" .= msg]]]
-- | A 2026-07-28 server: rejects initialize, requires per-request _meta.
modernStdio :: Server -> Value -> IO ()
modernStdio srv msg = case (methodOf msg, field "id" msg) of
(Just "notifications/cancelled", _) -> pure ()
(Just _, Nothing) -> pure ()
(Just "initialize", Just _) -> srv.send (replyError msg (-32601) "Method not found: this server speaks 2026-07-28 (initialize is not supported)" Nothing)
(Just m, Just _)
| not (hasMeta msg) -> srv.send (replyError msg (-32602) "missing _meta" Nothing)
| otherwise -> case m of
"server/discover" -> srv.send (reply msg ["resultType" .= ("complete" :: Text), "supportedVersions" .= ["2026-07-28" :: Text], "capabilities" .= object ["tools" .= object []]])
"tools/list" -> srv.send (toolsPage msg (paramsOf msg))
"tools/call" -> case KeyMap.lookup "name" (paramsOf msg) of
Just "echo" -> srv.send (echoResult msg (paramsOf msg))
Just "stateful"
| KeyMap.member "requestState" (paramsOf msg) -> srv.send (reply msg ["content" .= ([] :: [Value])])
| otherwise -> srv.send (reply msg ["resultType" .= ("input_required" :: Text), "requestState" .= ("s" :: Text)])
Just "slow" -> pure ()
Just "die" -> srv.closeOutput
Just "huge" -> srv.sendRaw (BS8.replicate 4096 'x' <> "\n")
Just "garbage" -> srv.sendRaw "this is not json\n"
_ -> srv.send (replyError msg (-32602) "unknown tool" Nothing)
"subscriptions/listen" -> do
let sid = field "id" msg
filt = KeyMap.lookup "notifications" (paramsOf msg)
note method extra = srv.send (object ["jsonrpc" .= ("2.0" :: Text), "method" .= (method :: Text), "params" .= object (("_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]) : extra)])
note "notifications/subscriptions/acknowledged" ["notifications" .= filt]
case filt of
Just f | Just (Bool True) <- field "toolsListChanged" f -> note "notifications/tools/list_changed" []
Just f | Just (Array us) <- field "resourceSubscriptions" f -> forM_ us $ \u -> note "notifications/resources/updated" ["uri" .= u]
_ -> pure ()
_ -> srv.send (replyError msg (-32601) "Method not found" Nothing)
_ -> pure ()
where
hasMeta v = case KeyMap.lookup "_meta" (paramsOf v) of
Just (Object meta) -> KeyMap.member "io.modelcontextprotocol/protocolVersion" meta
_ -> False
-- | A 2025-11-25 server: errors (or stays silent) until initialized, and
-- pings the client once initialized.
legacyStdio :: Bool -> IORef Bool -> Server -> Value -> IO ()
legacyStdio silentProbe initialized srv msg = do
ready <- readIORef initialized
case (methodOf msg, field "id" msg) of
(Nothing, _) -> pure ()
(Just "notifications/initialized", Nothing) -> do
writeIORef initialized True
srv.send (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("ping-1" :: Text), "method" .= ("ping" :: Text)])
(Just _, Nothing) -> pure ()
(Just "initialize", Just _) -> srv.send (reply msg ["protocolVersion" .= ("2025-11-25" :: Text), "capabilities" .= object ["tools" .= object []], "serverInfo" .= object ["name" .= ("old" :: Text), "version" .= ("1" :: Text)]])
(Just m, Just _)
| not ready -> if silentProbe then pure () else srv.send (replyError msg (-32600) ("server not initialized: " <> m) Nothing)
| m == "tools/list" -> srv.send (toolsPage msg (paramsOf msg))
| m == "tools/call" -> srv.send (echoResult msg (paramsOf msg))
| otherwise -> srv.send (replyError msg (-32601) "Method not found" Nothing)
streamCfg :: McpStreamConfig
streamCfg = (mcpStreamConfig "stdio-fixture") {probeTimeout = 0.3, streamLimits = defaultMcpLimits {requestTimeout = 2, connectTimeout = 3}}
withServer :: (Server -> Value -> IO ()) -> (Pipe -> Server -> IO a) -> IO a
withServer handler k = do
p <- newPipe
bracket (runServer p handler) (cancel . snd) $ \(srv, _) -> k p srv
connectOn :: McpStreamConfig -> Pipe -> IO McpConnection
connectOn cfg p = do
r <- connectMcpStream cfg p.client
case r of
Right c -> pure c
Left e -> assertFailure ("connect failed: " <> show e) >> error "unreachable"
methodsSeen :: Server -> IO [Text]
methodsSeen srv = foldr (\v acc -> maybe acc (: acc) (methodOf v)) [] <$> readIORef srv.received
-- | Identical caller code for every server: list all tools, call one.
exercise :: McpConnection -> IO (Either McpToolError (McpOutcome McpToolResult))
exercise c = do
listing <- listTools c defaultDrainLimits
case listing of
Right l | (t : _) <- [x | x <- l.tools, x.name == "echo"] -> do
length l.tools @?= 2
t.headerMirrors @?= []
callTool c (mcpToolCall t (KeyMap.fromList [("msg", String "line one\nline two")]))
other -> assertFailure (show other) >> error "unreachable"
-- ---------------------------------------------------------------------------
framing :: TestTree
framing =
testGroup
"framing and correlation"
[ testCase "one compact line per message; embedded newlines stay escaped" $
withServer modernStdio $ \p srv -> do
c <- connectOn streamCfg p
r <- exercise c
case r of
Right (McpCompleted res) -> res.content @?= [TextBlock "line one\nline two"]
other -> assertFailure (show other)
msgs <- readIORef srv.received
length msgs @?= 4
closeMcp c,
testCase "replies are routed by id when they arrive out of order" $ do
held <- newIORef []
let handler srv msg = case (methodOf msg, field "id" msg) of
(Just "tools/call", Just _) -> do
modifyIORef' held (msg :)
pending <- readIORef held
when (length pending == 2) $ forM_ pending $ \m -> srv.send (echoResult m (paramsOf m))
_ -> modernStdio srv msg
withServer handler $ \p _ -> do
c <- connectOn streamCfg p
let call msg = callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo"), ("arguments", object ["msg" .= (msg :: Text)])]))
a <- async (call "first")
threadDelay 20000
b <- call "second"
ra <- wait a
fmap (KeyMap.lookup "content" . (.result)) ra @?= Right (Just (Aeson.toJSON [object ["type" .= ("text" :: Text), "text" .= ("first" :: Text)]]))
fmap (KeyMap.lookup "content" . (.result)) b @?= Right (Just (Aeson.toJSON [object ["type" .= ("text" :: Text), "text" .= ("second" :: Text)]]))
closeMcp c
]
eras :: TestTree
eras =
testGroup
"era detection"
[ testCase "the same caller code reaches a modern-only server" $
withServer modernStdio $ \p srv -> do
c <- connectOn streamCfg p
connectionEra c @?= Modern latestModernVersion
_ <- exercise c
methodsSeen srv >>= (@?= ["server/discover", "tools/list", "tools/list", "tools/call"])
closeMcp c,
testCase "the same caller code reaches a handshake-only server" $ do
ready <- newIORef False
withServer (legacyStdio False ready) $ \p srv -> do
c <- connectOn streamCfg p
connectionEra c @?= Legacy (ProtocolVersion "2025-11-25")
r <- exercise c
case r of
Right (McpCompleted _) -> pure ()
other -> assertFailure (show other)
methodsSeen srv >>= (@?= ["server/discover", "initialize", "notifications/initialized", "tools/list", "tools/list", "tools/call"])
waitFor 50 (any (\v -> field "id" v == Just "ping-1" && field "result" v == Just (object [])) <$> readIORef srv.received)
closeMcp c,
testCase "silence to the probe falls back after the timeout" $ do
ready <- newIORef False
withServer (legacyStdio True ready) $ \p srv -> do
c <- connectOn streamCfg p
connectionEra c @?= Legacy (ProtocolVersion "2025-11-25")
msgs <- readIORef srv.received
map methodOf (take 3 msgs) @?= map Just ["server/discover", "notifications/cancelled", "initialize"]
field "requestId" (Object (paramsOf (msgs !! 1))) @?= field "id" (msgs !! 0)
closeMcp c,
testCase "an unsupported-version answer is modern: no fallback" $ do
let handler srv msg = case methodOf msg of
Just "server/discover" -> srv.send (replyError msg (-32022) "Unsupported protocol version" (Just (object ["supported" .= ["2099-01-01" :: Text], "requested" .= ("2026-07-28" :: Text)])))
_ -> modernStdio srv msg
withServer handler $ \p srv -> do
r <- connectMcpStream streamCfg p.client
case r of
Left e -> e.kind @?= IncompatibleServer
Right _ -> assertFailure "expected an incompatibility"
methodsSeen srv >>= (@?= ["server/discover"]),
testCase "a known legacy server skips the probe; modern-only never sends initialize" $ do
ready <- newIORef False
withServer (legacyStdio False ready) $ \p srv -> do
c <- connectOn streamCfg {streamProfile = StreamLegacyOnly} p
closeMcp c
take 1 <$> methodsSeen srv >>= (@?= ["initialize"])
ready' <- newIORef False
withServer (legacyStdio False ready') $ \p srv -> do
r <- connectMcpStream streamCfg {streamProfile = StreamModernOnly} p.client
case r of
Left e -> e.kind @?= IncompatibleServer
Right _ -> assertFailure "expected the legacy server to be refused"
methodsSeen srv >>= (@?= ["server/discover"])
]
lifecycle :: TestTree
lifecycle =
testGroup
"cancellation, subscriptions and limits"
[ testCase "a timed-out call is cancelled once and its late reply is dropped" $ do
let handler srv msg = do
modernStdio srv msg
when (methodOf msg == Just "notifications/cancelled") $
srv.send (object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "requestId" (Object (paramsOf msg)), "result" .= object ["content" .= ([] :: [Value])]])
withServer handler $ \p srv -> do
c <- connectOn streamCfg {streamLimits = defaultMcpLimits {requestTimeout = 0.3, connectTimeout = 3}} p
e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "slow")]))
case e of
Left err -> err.kind @?= TimedOut
Right _ -> assertFailure "expected a timeout"
r <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo"), ("arguments", object ["msg" .= ("after" :: Text)])]))
fmap (KeyMap.lookup "content" . (.result)) r @?= Right (Just (Aeson.toJSON [object ["type" .= ("text" :: Text), "text" .= ("after" :: Text)]]))
msgs <- readIORef srv.received
let slowIds = take 1 [field "id" v | v <- msgs, methodOf v == Just "tools/call"]
[field "requestId" (Object (paramsOf v)) | v <- msgs, methodOf v == Just "notifications/cancelled"] @?= slowIds
closeMcp c,
testCase "two subscriptions on one channel each receive only their own notifications" $
withServer modernStdio $ \p srv -> do
c <- connectOn streamCfg p
r <- withSubscription c emptySubscriptionFilter {toolsListChanged = True} $ \a -> do
rb <- withSubscription c emptySubscriptionFilter {resourceSubscriptions = ["file:///x"]} $ \b -> do
eb <- nextSubscriptionEvent b
pure (eb, subscriptionId b)
ea <- nextSubscriptionEvent a
pure (ea, rb)
case r of
Right (SubscriptionNotification ma _, Right (SubscriptionNotification mb _, bid)) -> do
ma @?= "notifications/tools/list_changed"
mb @?= "notifications/resources/updated"
waitFor 50 $ do
msgs <- readIORef srv.received
pure (Just (Aeson.toJSON bid) `elem` [field "requestId" (Object (paramsOf v)) | v <- msgs, methodOf v == Just "notifications/cancelled"])
other -> assertFailure (show other)
connectionOpenListeners c >>= (@?= 0)
closeMcp c,
testCase "state-only continuation works unchanged" $
withServer modernStdio $ \p _ -> do
c <- connectOn streamCfg p
r <- callInteractive c (mcpCall "tools/call" (KeyMap.fromList [("name", "stateful")]))
case r of
Right (McpCompleted cr) -> cr.continuationRounds @?= 1
other -> assertFailure (show other)
closeMcp c,
testCase "an oversized line fails the connection with a bounded error" $
withServer modernStdio $ \p _ -> do
c <- connectOn streamCfg {streamLimits = defaultMcpLimits {maxFrameBytes = 1024, requestTimeout = 2}} p
e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "huge")]))
either (\err -> err.kind @?= LimitExceeded) (const (assertFailure "expected a limit error")) e
e2 <- callMethod c (mcpCall "tools/list" KeyMap.empty)
either (\err -> err.delivery @?= NotSent) (const (assertFailure "expected the channel to be failed")) e2
closeMcp c
readIORef p.readsInFlight >>= (@?= 0)
readIORef p.clientClosedIt >>= (@?= True),
testCase "a line that is not JSON fails the waiting request" $
withServer modernStdio $ \p _ -> do
c <- connectOn streamCfg p
e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "garbage")]))
either (\err -> err.kind @?= MalformedReply) (const (assertFailure "expected a malformed reply")) e
closeMcp c,
testCase "an end of input during a tool call is an uncertain outcome" $
withServer modernStdio $ \p _ -> do
c <- connectOn streamCfg p
let die = either (error . show) id (decodeTool False (object ["name" .= ("die" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]))
r <- callTool c (mcpToolCall die KeyMap.empty)
case r of
Left (ToolRequestFailed e) -> e.delivery @?= Uncertain
other -> assertFailure (show other)
closeMcp c
readIORef p.readsInFlight >>= (@?= 0),
testCase "a denied send writes nothing and release is idempotent" $
withServer modernStdio $ \p srv -> do
let hook = McpRequestHook (\att -> pure (if att.method == "tools/call" then SendDenied "no" else SendAllowed []))
c <- connectOn streamCfg {streamRequestHook = hook} p
before <- length <$> readIORef srv.received
e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo")]))
either (\err -> err.kind @?= RequestDenied) (const (assertFailure "expected a denial")) e
after <- length <$> readIORef srv.received
after @?= before
closeMcp c
closeMcp c
e2 <- callMethod c (mcpCall "tools/list" KeyMap.empty)
either (\err -> err.kind @?= ConnectionReleased) (const (assertFailure "expected a released handle")) e2
]
-- | The handle helper over real OS pipes.
handles :: TestTree
handles =
testCase "handleStream works over OS pipes and closes the server's input" $ do
(serverIn, clientOut) <- createPipe
(clientIn, serverOut) <- createPipe
p <- newPipe
let bridgeOut = do
chunk <- BS.hGetSome serverIn 65536
if BS.null chunk then atomically (writeTQueue p.toServer Nothing) else atomically (writeTQueue p.toServer (Just chunk)) >> bridgeOut
bridgeIn = do
chunk <- atomically (readTQueue p.toClient)
case chunk of
Nothing -> hClose serverOut
Just b -> BS.hPut serverOut b >> hFlush serverOut >> bridgeIn
bracket (runServer p modernStdio) (cancel . snd) $ \(_, serverThread) -> do
a1 <- async bridgeOut
a2 <- async bridgeIn
r <- withMcpStream streamCfg (handleStream clientIn clientOut) $ \c -> callMethod c (mcpCall "tools/list" KeyMap.empty)
assertBool "listed over handles" (either (const False) (either (const False) (const True)) r)
-- Releasing closed the server's input, so the server saw end of input.
waitFor 50 (maybe False (const True) <$> poll serverThread)
mapM_ cancel [a1, a2]