baikai-mcp-0.1.0.0: test/ProtocolSpec.hs
module ProtocolSpec (tests) where
import Baikai.Mcp.Internal.Sse
import Baikai.Mcp.Protocol
import Baikai.Mcp.Transport
import Data.Aeson (Value (..), object, (.=))
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.Either (isLeft)
import Data.IORef
import Data.Map.Strict qualified as Map
import Data.Text (Text)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))
tests :: TestTree
tests =
testGroup
"Protocol"
[ envelopes,
resultKinds,
cacheHints,
headerValues,
paramMirrors,
sseParsing,
draining
]
obj :: [(Aeson.Key, Value)] -> KeyMap.KeyMap Value
obj = KeyMap.fromList
envelopes :: TestTree
envelopes =
testGroup
"JSON-RPC envelopes"
[ testCase "a request carries version, id, method and params" $
encodeRequest (RequestIdNumber 7) "tools/list" (obj [("cursor", "c")])
@?= object ["jsonrpc" .= ("2.0" :: Text), "id" .= (7 :: Int), "method" .= ("tools/list" :: Text), "params" .= object ["cursor" .= ("c" :: Text)]],
testCase "a notification has no id and omits empty params" $
encodeNotification "notifications/initialized" KeyMap.empty
@?= object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/initialized" :: Text)],
testCase "a frame with both result and error is rejected" $
assertBool "rejected" . isLeft $
decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int), "result" .= object [], "error" .= object ["code" .= (1 :: Int), "message" .= ("x" :: Text)]]),
testCase "a frame without jsonrpc 2.0 is rejected" $
assertBool "rejected" . isLeft $
decodeMessage (object ["id" .= (1 :: Int), "result" .= object []]),
testCase "a null request id is rejected" $
assertBool "rejected" . isLeft $
decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= Null, "method" .= ("ping" :: Text)]),
testCase "string and integer ids decode" $ do
decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("a" :: Text), "result" .= object []])
@?= Right (IncomingResponse (Just (RequestIdText "a")) (Right KeyMap.empty))
decodeMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (3 :: Int), "error" .= object ["code" .= (-32601 :: Int), "message" .= ("no" :: Text)]])
@?= Right (IncomingResponse (Just (RequestIdNumber 3)) (Left (rpcError (-32601) "no"))),
testCase "_meta merges with protocol fields winning" $ do
let merged = withRequestMeta (requestMeta latestModernVersion Nothing) (obj [("_meta", object ["traceparent" .= ("t" :: Text), "io.modelcontextprotocol/protocolVersion" .= ("old" :: Text)])])
KeyMap.lookup "_meta" merged
@?= Just
( object
[ "traceparent" .= ("t" :: Text),
"io.modelcontextprotocol/protocolVersion" .= ("2026-07-28" :: Text),
"io.modelcontextprotocol/clientCapabilities" .= object []
]
),
testCase "unsupported-version data lists the offered versions" $
unsupportedVersionsOffered (RpcError (-32022) "x" (Just (object ["supported" .= ["2026-07-28", "2025-11-25" :: Text], "requested" .= ("1900-01-01" :: Text)])))
@?= Just [ProtocolVersion "2026-07-28", ProtocolVersion "2025-11-25"]
]
resultKinds :: TestTree
resultKinds =
testGroup
"result types"
[ testCase "complete and absent resultType are complete" $ do
decodeResultKind "tools/list" (obj [("resultType", "complete")]) @?= Right ResultComplete
decodeResultKind "tools/list" KeyMap.empty @?= Right ResultComplete,
testCase "state-only input_required on tools/call" $
decodeResultKind "tools/call" (obj [("resultType", "input_required"), ("requestState", "s1")])
@?= Right (ResultInputRequired (InputRequired Nothing (Just "s1"))),
testCase "input requests and state" $
decodeResultKind "prompts/get" (obj [("resultType", "input_required"), ("inputRequests", object ["a" .= object ["method" .= ("roots/list" :: Text)]]), ("requestState", "s")])
@?= Right (ResultInputRequired (InputRequired (Just (Map.fromList [("a", object ["method" .= ("roots/list" :: Text)])])) (Just "s"))),
testCase "input_required with neither field is invalid" $
assertBool "rejected" . isLeft $
decodeResultKind "resources/read" (obj [("resultType", "input_required")]),
testCase "input_required on a method that does not allow it is invalid" $
assertBool "rejected" . isLeft $
decodeResultKind "tools/list" (obj [("resultType", "input_required"), ("requestState", "s")]),
testCase "an unknown resultType is invalid" $
assertBool "rejected" . isLeft $
decodeResultKind "tools/call" (obj [("resultType", "task")])
]
cacheHints :: TestTree
cacheHints =
testGroup
"cache hints"
[ testCase "public and private hints decode; negative ttl clamps to zero" $ do
decodeCacheHint (obj [("ttlMs", Number 5000), ("cacheScope", "private")]) @?= Right (Just (CacheHint 5000 CachePrivate))
decodeCacheHint (obj [("ttlMs", Number (-4)), ("cacheScope", "public")]) @?= Right (Just (CacheHint 0 CachePublic)),
testCase "absent hints are Nothing" $ decodeCacheHint KeyMap.empty @?= Right Nothing,
testCase "an unknown scope or a lone field is invalid" $ do
assertBool "scope" . isLeft $ decodeCacheHint (obj [("ttlMs", Number 1), ("cacheScope", "shared")])
assertBool "lone" . isLeft $ decodeCacheHint (obj [("ttlMs", Number 1)])
]
-- | The encoding table from the 2026-07-28 Streamable HTTP page.
headerValues :: TestTree
headerValues =
testGroup
"header value encoding"
[ testCase "plain ASCII passes through" $ encodeHeaderValue "us-west1" @?= "us-west1",
testCase "non-ASCII is Base64-wrapped" $ encodeHeaderValue "Hello, 世界" @?= "=?base64?SGVsbG8sIOS4lueVjA==?=",
testCase "leading or trailing whitespace is Base64-wrapped" $ encodeHeaderValue " padded " @?= "=?base64?IHBhZGRlZCA=?=",
testCase "a newline is Base64-wrapped" $ encodeHeaderValue "line1\nline2" @?= "=?base64?bGluZTEKbGluZTI=?=",
testCase "a sentinel-shaped literal is Base64-wrapped" $ encodeHeaderValue "=?base64?literal?=" @?= "=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=",
testCase "decoding inverts encoding" $
mapM_ (\t -> decodeHeaderValue (encodeHeaderValue t) @?= Right t) ["us-west1", "Hello, 世界", " padded ", "line1\nline2", "=?base64?literal?=", ""]
]
paramMirrors :: TestTree
paramMirrors =
testGroup
"parameter mirrors"
[ testCase "string, integer and boolean values" $ do
fmap (fmap paramHeaderValue) (paramHeader "Region" (Just "us-west1")) @?= Right (Just "us-west1")
fmap (fmap paramHeaderValue) (paramHeader "Count" (Just (Number 42))) @?= Right (Just "42")
fmap (fmap paramHeaderValue) (paramHeader "Neg" (Just (Number (-7)))) @?= Right (Just "-7")
fmap (fmap paramHeaderValue) (paramHeader "Flag" (Just (Bool False))) @?= Right (Just "false")
fmap (fmap paramHeaderField) (paramHeader "Region" (Just "x")) @?= Right (Just "Mcp-Param-Region"),
testCase "null and absent values are omitted" $ do
paramHeader "Region" (Just Null) @?= Right Nothing
paramHeader "Region" Nothing @?= Right Nothing,
testCase "unsafe integers, fractions, arrays and invalid names are refused" $ do
assertBool "unsafe" . isLeft $ paramHeader "N" (Just (Number (2 ^ (53 :: Int))))
assertBool "fraction" . isLeft $ paramHeader "N" (Just (Number 1.5))
assertBool "array" . isLeft $ paramHeader "N" (Just (Aeson.toJSON [1 :: Int]))
assertBool "name" . isLeft $ paramHeader "bad name" (Just "x")
assertBool "empty" . isLeft $ paramHeader "" (Just "x")
]
feedAll :: Int -> [ByteString] -> Either String [SseEvent]
feedAll lim = go (newSseParser lim) []
where
go _ acc [] = Right (concat (reverse acc))
go p acc (c : cs) = case feedSse p c of
Left e -> Left e
Right (p', evs) -> go p' (evs : acc) cs
sseParsing :: TestTree
sseParsing =
testGroup
"server-sent events"
[ testCase "events split across chunks at every byte reassemble" $ do
let stream = ": keepalive\r\nevent: message\r\ndata: {\"a\":\r\ndata: 1}\r\n\r\ndata: two\n\n"
expected = [SseEvent "message" "{\"a\":\n1}", SseEvent "" "two"]
feedAll 1024 [stream] @?= Right expected
feedAll 1024 (map BS.singleton (BS.unpack stream)) @?= Right expected,
testCase "a CR at the end of a chunk followed by LF is one line break" $
feedAll 1024 ["data: x\r", "\n\r", "\n"] @?= Right [SseEvent "" "x"],
testCase "an incomplete event at end of input is not dispatched" $
feedAll 1024 ["data: x\n"] @?= Right [],
testCase "an oversized line or event is refused" $ do
assertBool "line" . isLeft $ feedAll 8 ["data: 0123456789"]
assertBool "event" . isLeft $ feedAll 11 ["data: 12345\ndata: 12345\n\n"]
]
draining :: TestTree
draining =
testGroup
"bounded drain"
[ testCase "pages are concatenated in order" $ do
let pages = Map.fromList [(Nothing, page [1, 2] (Just "a")), (Just "a", page [3] (Just "")), (Just "", page [4] Nothing)]
r <- drainPages defaultDrainLimits (\c -> pure (Right @Text (pages Map.! fmap cursorToText c)))
r @?= Right [1, 2, 3, 4 :: Int],
testCase "a repeated cursor stops the drain" $ do
r <- drainPages defaultDrainLimits (\_ -> pure (Right @Text (page [1 :: Int] (Just "same"))))
r @?= Left (DrainRepeatedCursor 2),
testCase "the page limit is enforced before the next fetch" $ do
calls <- newIORef (0 :: Int)
r <- drainPages defaultDrainLimits {maxPages = 2} $ \c -> do
modifyIORef' calls (+ 1)
n <- readIORef calls
pure (Right @Text (page [n] (Just (maybe "0" (const (if n == 1 then "x" else "y")) c))))
r @?= Left (DrainTooManyPages 2)
readIORef calls >>= (@?= 2),
testCase "item and byte ceilings" $ do
r1 <- drainPages defaultDrainLimits {maxItems = 2} (\_ -> pure (Right @Text (page [1, 2, 3 :: Int] Nothing)))
r1 @?= Left (DrainTooManyItems 3)
r2 <- drainPages defaultDrainLimits {maxBytes = 5} (\_ -> pure (Right @Text (page [1 :: Int] Nothing) {responseBytes = 10}))
r2 @?= Left (DrainTooManyBytes 10),
testCase "a fetch failure names the page" $ do
r <- drainPages defaultDrainLimits (\c -> pure (maybe (Right (page [1 :: Int] (Just "n"))) (const (Left ("boom" :: Text))) c))
case r of
Left (DrainPageFailed 2 "boom") -> pure ()
other -> assertFailure (show other)
]
where
page xs c = Page {items = xs, nextCursor = cursorFromText <$> c, cache = Nothing, responseBytes = 1}