packages feed

baikai-mcp-0.1.0.0: test/LegacySpec.hs

module LegacySpec (tests) where

import Baikai.Mcp.Client
import Baikai.Mcp.Protocol
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.IORef
import Data.Text (Text)
import Data.Text.Encoding qualified as TE
import McpStub
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))

tests :: TestTree
tests =
  testGroup
    "Legacy profiles"
    [ streamable,
      httpSse
    ]

data LegacyCfg = LegacyCfg
  { version :: Text,
    session :: Maybe ByteString,
    expireAfter :: Maybe Int,
    pingFirst :: Bool
  }

-- | A handshake-era Streamable HTTP server. It answers 400 with an empty
-- body to anything before initialize, as such servers commonly do.
legacyServer :: LegacyCfg -> IORef Int -> Stub -> StubRequest -> IO StubReply
legacyServer cfg served _ r
  | r.httpMethod == "DELETE" = pure (ReplyRaw 200 [] "")
  | otherwise = case rpcMethod r of
      Just "initialize"
        | header "Mcp-Session-Id" r /= Nothing -> pure (ReplyRaw 400 [] "")
        | otherwise ->
            pure . ReplyJson 200 [("Mcp-Session-Id", s) | Just s <- [cfg.session]] $
              object
                [ "jsonrpc" .= ("2.0" :: Text),
                  "id" .= rpcId r,
                  "result"
                    .= object
                      [ "protocolVersion" .= cfg.version,
                        "capabilities" .= object ["tools" .= object []],
                        "serverInfo" .= object ["name" .= ("legacy" :: Text), "version" .= ("0.9" :: Text)]
                      ]
                ]
      Just "notifications/initialized"
        | sessionOk -> pure (ReplyRaw 202 [] "")
        | otherwise -> pure (ReplyRaw 400 [] "")
      Just "tools/list"
        | not sessionOk || not versionOk -> pure (ReplyRaw 400 [] "")
        | otherwise -> do
            n <- atomicModifyIORef' served (\x -> (x + 1, x + 1))
            case cfg.expireAfter of
              Just k | n > k -> pure (ReplyRaw 404 [] "")
              _
                | cfg.pingFirst ->
                    pure (ReplySse 200 [] [Chunk (sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("srv-1" :: Text), "method" .= ("ping" :: Text)])), Chunk (sseResult r toolsPage)])
                | otherwise -> pure (okResult r toolsPage)
      Just _ | rpcId r == Null -> pure (ReplyRaw 202 [] "")
      _ -> pure (ReplyRaw 400 [] "")
  where
    sessionOk = header "Mcp-Session-Id" r == cfg.session
    versionOk
      | cfg.version >= "2025-06-18" = fmap TE.decodeUtf8 (header "MCP-Protocol-Version" r) == Just cfg.version
      | otherwise = True
    toolsPage = ["tools" .= [object ["name" .= ("echo" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)]]]]

listTools :: McpConnection -> IO (Either McpError CompleteResult)
listTools c = callMethod c (mcpCall "tools/list" KeyMap.empty)

streamable :: TestTree
streamable =
  testGroup
    "handshake-era Streamable HTTP"
    [ testCase "2025-11-25 with a session: fallback, handshake, session echo and teardown" $ do
        served <- newIORef 0
        withStub (legacyServer (LegacyCfg "2025-11-25" (Just "sess-42") Nothing False) served) $ \stub -> do
          c <- connectOrFail (config stub)
          connectionEra c @?= Legacy (ProtocolVersion "2025-11-25")
          (connectionDescription c).serverInfo @?= Just (implementation "legacy" "0.9")
          r <- listTools c
          assertBool "listed" (either (const False) (const True) r)
          closeMcp c
          closeMcp c
          rs <- stub.requests
          methodsOf rs @?= ["server/discover", "initialize", "notifications/initialized", "tools/list", "DELETE"]
          map (header "Mcp-Session-Id") rs @?= [Nothing, Nothing, Just "sess-42", Just "sess-42", Just "sess-42"]
          map (header "MCP-Protocol-Version") (drop 2 rs) @?= replicate 3 (Just "2025-11-25")
          let initParams = rpcParams (rs !! 1)
          KeyMap.lookup "protocolVersion" initParams @?= Just "2025-11-25"
          assertBool "no modern _meta on legacy requests" (not (KeyMap.member "_meta" (rpcParams (rs !! 3)))),
      testCase "2025-06-18 without a session: no session header and no teardown" $ do
        served <- newIORef 0
        withStub (legacyServer (LegacyCfg "2025-06-18" Nothing Nothing False) served) $ \stub -> do
          c <- connectOrFail (config stub)
          connectionEra c @?= Legacy (ProtocolVersion "2025-06-18")
          _ <- listTools c
          closeMcp c
          rs <- stub.requests
          methodsOf rs @?= ["server/discover", "initialize", "notifications/initialized", "tools/list"]
          assertBool "no session header" (all ((== Nothing) . header "Mcp-Session-Id") rs),
      testCase "an expired session is reported, marks the handle, and is not replayed" $ do
        served <- newIORef 0
        withStub (legacyServer (LegacyCfg "2025-11-25" (Just "s") (Just 1) False) served) $ \stub -> do
          c <- connectOrFail (config stub)
          _ <- listTools c
          e <- listTools c >>= expectErr
          e.kind @?= SessionExpired
          e.delivery @?= Answered
          e2 <- listTools c >>= expectErr
          e2.kind @?= SessionExpired
          e2.delivery @?= NotSent
          readIORef served >>= (@?= 2),
      testCase "a version outside the allowlist is refused" $ do
        served <- newIORef 0
        withStub (legacyServer (LegacyCfg "2023-01-01" Nothing Nothing False) served) $ \stub -> do
          e <- connectMcp (config stub) >>= expectErr
          e.kind @?= IncompatibleServer
          methodsOf <$> stub.requests >>= (@?= ["server/discover", "initialize"]),
      testCase "an explicitly legacy endpoint skips the probe" $ do
        served <- newIORef 0
        withStub (legacyServer (LegacyCfg "2025-11-25" Nothing Nothing False) served) $ \stub -> do
          c <- connectOrFail (config stub) {profile = McpLegacyStreamableHttp}
          closeMcp c
          methodsOf <$> stub.requests >>= (@?= ["initialize", "notifications/initialized"]),
      testCase "the modern-only profile refuses a legacy server" $ do
        served <- newIORef 0
        withStub (legacyServer (LegacyCfg "2025-11-25" Nothing Nothing False) served) $ \stub -> do
          e <- connectMcp (config stub) {profile = McpModernOnly} >>= expectErr
          e.kind @?= IncompatibleServer
          methodsOf <$> stub.requests >>= (@?= ["server/discover"]),
      testCase "a ping on a response stream is answered through the hook" $ do
        served <- newIORef 0
        replies <- newIORef []
        withStub (legacyServer (LegacyCfg "2025-11-25" (Just "s") Nothing True) served) $ \stub -> do
          let hook = McpRequestHook $ \att -> modifyIORef' replies (<> [att.purpose]) >> pure (SendAllowed [])
          c <- connectOrFail (config stub) {requestHook = hook}
          r <- listTools c
          assertBool "listed" (either (const False) (const True) r)
          waitFor 50 ((== 5) . length <$> stub.requests)
          rs <- stub.requests
          let answers = [x | x <- rs, rpcId x == String "srv-1"]
          map (.json) answers @?= [Just (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("srv-1" :: Text), "result" .= object []])]
          map (header "Mcp-Session-Id") answers @?= [Just "s"]
          purposes <- readIORef replies
          assertBool "reply passed the hook" (PurposeReply `elem` purposes)
    ]

-- | A 2024-11-05 HTTP+SSE server: a GET event stream whose first event
-- names the message endpoint, and a POST endpoint whose replies travel on
-- the event stream.
sseServer :: ByteString -> Stub -> StubRequest -> IO StubReply
sseServer advertised stub r
  | r.httpMethod == "GET" = pure (ReplyChannel 200 [] ["event: endpoint\ndata: " <> advertised <> "\n\n"])
  | r.path /= "/messages" = pure (ReplyRaw 404 [] "")
  | otherwise = do
      case rpcMethod r of
        Just "initialize" ->
          stub.push (sseResult r ["protocolVersion" .= ("2024-11-05" :: Text), "capabilities" .= object ["tools" .= object []], "serverInfo" .= object ["name" .= ("old" :: Text), "version" .= ("0.1" :: Text)]])
        Just "tools/list" -> stub.push (sseResult r ["tools" .= ([] :: [Value])])
        _ -> pure ()
      pure (ReplyRaw 202 [] "")

httpSse :: TestTree
httpSse =
  testGroup
    "deprecated HTTP+SSE"
    [ testCase "GET stream, endpoint event, POSTed requests and replies on the stream" $
        withStub (sseServer "/messages?sessionId=s1") $ \stub -> do
          c <- connectOrFail (config stub) {profile = McpLegacyHttpSse}
          connectionEra c @?= Legacy (ProtocolVersion "2024-11-05")
          r <- listTools c
          case r of
            Right cr -> KeyMap.lookup "tools" cr.result @?= Just (Aeson.toJSON ([] :: [Value]))
            Left e -> assertFailure (show e)
          closeMcp c
          rs <- stub.requests
          methodsOf rs @?= ["GET", "initialize", "notifications/initialized", "tools/list"]
          map (.query) (drop 1 rs) @?= replicate 3 "?sessionId=s1"
          waitFor 50 ((>= 1) <$> stub.clientClosed),
      testCase "a message endpoint on another origin is refused before any POST" $
        withStub (sseServer "http://evil.invalid/messages") $ \stub -> do
          e <- connectMcp (config stub) {profile = McpLegacyHttpSse} >>= expectErr
          e.kind @?= IncompatibleServer
          e.delivery @?= NotSent
          methodsOf <$> stub.requests >>= (@?= ["GET"])
    ]