packages feed

baikai-mcp-0.1.0.0: test/ModernHttpSpec.hs

module ModernHttpSpec (tests) where

import Baikai.Mcp.Client
import Baikai.Mcp.Protocol
import Baikai.Mcp.Transport (paramHeader)
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object)
import Data.ByteString qualified as BS
import Data.IORef
import Data.Map.Strict qualified as Map
import Data.Text (Text)
import McpStub
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))

tests :: TestTree
tests =
  testGroup
    "Modern Streamable HTTP"
    [ discovery,
      errors,
      continuation,
      interruption,
      routing
    ]

discovery :: TestTree
discovery =
  testGroup
    "discovery"
    [ testCase "discovery succeeds without initialize and headers match the body" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else rpcErrorReply 404 r (-32601) "no" Nothing))) $ \stub -> do
          c <- connectOrFail (config stub)
          connectionEra c @?= Modern latestModernVersion
          let d = connectionDescription c
          d.serverInfo @?= Just (implementation "stub" "1.0.0")
          d.instructions @?= Just "stub instructions"
          d.cache @?= Just (CacheHint 60000 CachePublic)
          assertBool "tools capability" (capabilityPresent "tools" d.capabilities)
          rs <- stub.requests
          methodsOf rs @?= ["server/discover"]
          map (header "Accept") rs @?= [Just "application/json, text/event-stream"]
          KeyMap.lookup "io.modelcontextprotocol/clientInfo" (rpcMeta (rs !! 0)) @?= Just (object ["name" .= ("baikai-mcp" :: Text), "version" .= ("0.1.0.0" :: Text)])
          closeMcp c,
      testCase "the same discovery result arrives over split SSE frames" $ do
        viaJson <- withStub (modernServer (\_ r _ _ -> pure (discover r))) $ \stub ->
          connectionDescription <$> connectOrFail (config stub)
        viaSse <- withStub
          ( modernServer $ \_ r _ _ -> do
              let frame = sseResult r discoverResultObject
                  (a, b) = BS.splitAt 23 frame
                  progress = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/message" :: Text), "params" .= object ["level" .= ("info" :: Text), "data" .= ("hi" :: Text)]])
              pure (ReplySse 200 [] [Chunk ":\n\n", Chunk progress, Chunk a, Pause 20000, Chunk b])
          )
          $ \stub -> connectionDescription <$> connectOrFail (config stub)
        viaSse @?= viaJson
    ]

errors :: TestTree
errors =
  testGroup
    "errors"
    [ testCase "an unsupported version is an incompatibility, not a fallback" $
        withStub (modernServer (\_ r _ _ -> pure (rpcErrorReply 400 r (-32022) "Unsupported protocol version" (Just (object ["supported" .= ["2099-01-01" :: Text], "requested" .= ("2026-07-28" :: Text)]))))) $ \stub -> do
          e <- connectMcp (config stub) >>= expectErr
          e.kind @?= IncompatibleServer
          methodsOf <$> stub.requests >>= (@?= ["server/discover"]),
      testCase "a missing client capability stays modern" $
        withStub (modernServer (\_ r _ _ -> pure (rpcErrorReply 400 r (-32021) "Missing capability" (Just (object ["requiredCapabilities" .= object ["roots" .= object []]]))))) $ \stub -> do
          e <- connectMcp (config stub) >>= expectErr
          e.kind @?= RemoteRpcError
          fmap (.code) e.rpc @?= Just (-32021)
          e.httpStatus @?= Just 400
          methodsOf <$> stub.requests >>= (@?= ["server/discover"]),
      testCase "a header mismatch rejection is reported with its code" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else rpcErrorReply 400 r (-32020) "Header mismatch" Nothing))) $ \stub -> do
          c <- connectOrFail (config stub)
          e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr
          fmap (.code) e.rpc @?= Just (-32020)
          e.delivery @?= Answered,
      testCase "a response with an unrelated id is malformed and uncertain" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else ok (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (999 :: Int), "result" .= object []])))) $ \stub -> do
          c <- connectOrFail (config stub)
          e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr
          e.kind @?= MalformedReply
          e.delivery @?= Uncertain,
      testCase "an oversized response is refused" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r ["tools" .= [String (mconcat (replicate 4000 "x"))]]))) $ \stub -> do
          c <- connectOrFail (config stub) {limits = fastLimits {maxResponseBytes = 1024}}
          e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr
          e.kind @?= LimitExceeded,
      testCase "a stream that ends before its response is a lost reply" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else ReplySse 200 [] [Chunk ":\n\n"]))) $ \stub -> do
          c <- connectOrFail (config stub)
          e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo")])) >>= expectErr
          e.kind @?= TransportFailure
          e.delivery @?= Uncertain,
      testCase "a denied request transmits nothing" $
        withStub (modernServer (\_ r _ _ -> pure (discover r))) $ \stub -> do
          let hook = McpRequestHook $ \att -> pure (if att.method == "tools/call" then SendDenied "not approved" else SendAllowed [])
          c <- connectOrFail (config stub) {requestHook = hook}
          e <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "echo")])) >>= expectErr
          e.kind @?= RequestDenied
          e.delivery @?= NotSent
          methodsOf <$> stub.requests >>= (@?= ["server/discover"]),
      testCase "a credential challenge never downgrades" $
        withStub (\_ _ -> pure (ReplyRaw 401 [("WWW-Authenticate", "Bearer resource_metadata=\"https://x/.well-known\"")] "")) $ \stub -> do
          e <- connectMcp (config stub) >>= expectErr
          e.httpStatus @?= Just 401
          e.challenge @?= Just "Bearer resource_metadata=\"https://x/.well-known\""
          methodsOf <$> stub.requests >>= (@?= ["server/discover"]),
      testCase "a redirect is not followed" $
        withStub (\_ _ -> pure (ReplyRaw 307 [("Location", "http://127.0.0.1:1/elsewhere")] "")) $ \stub -> do
          e <- connectMcp (config stub) >>= expectErr
          e.kind @?= HttpFailure
          e.httpStatus @?= Just 307
          length <$> stub.requests >>= (@?= 1)
    ]

-- | A tools/call that needs @rounds@ state-only rounds before completing.
statefulTool :: Int -> IORef [Object] -> ModernHandler
statefulTool rounds seen _ r m p = case m of
  "server/discover" -> pure (discover r)
  "tools/call" -> do
    modifyIORef' seen (<> [p])
    n <- length <$> readIORef seen
    pure $
      if n > rounds
        then okResult r ["resultType" .= ("complete" :: Text), "content" .= [object ["type" .= ("text" :: Text), "text" .= ("done" :: Text)]]]
        else okResult r ["resultType" .= ("input_required" :: Text), "requestState" .= ("opaque/state+" <> show n <> "==")]
  _ -> pure (rpcErrorReply 404 r (-32601) "no" Nothing)

toolCall :: McpCall
toolCall = mcpCall "tools/call" (KeyMap.fromList [("name", "slow_tool"), ("arguments", object ["x" .= (1 :: Int)])])

continuation :: TestTree
continuation =
  testGroup
    "interim results"
    [ testCase "two state-only rounds complete with three distinct requests" $ do
        seen <- newIORef []
        withStub (modernServer (statefulTool 2 seen)) $ \stub -> do
          c <- connectOrFail (config stub)
          r <- callInteractive c toolCall
          case r of
            Right (McpCompleted cr) -> do
              cr.continuationRounds @?= 2
              cr.cache @?= Nothing
            other -> assertFailure (show other)
          calls <- filter ((== Just "tools/call") . rpcMethod) <$> stub.requests
          length calls @?= 3
          let ids = map rpcId calls
          assertBool "distinct ids" (length ids == length (foldr (\x acc -> if x `elem` acc then acc else x : acc) [] ids))
          map (KeyMap.lookup "requestState" . rpcParams) calls
            @?= [Nothing, Just "opaque/state+1==", Just "opaque/state+2=="]
          let stripped = map (KeyMap.delete "requestState" . rpcParams) calls
          assertBool "identical parameters" (and (zipWith (==) stripped (drop 1 stripped)))
          map (header "Mcp-Name") calls @?= replicate 3 (Just "slow_tool"),
      testCase "a denied continuation stops with the state and sends nothing more" $ do
        seen <- newIORef []
        withStub (modernServer (statefulTool 2 seen)) $ \stub -> do
          let hook = McpRequestHook $ \att -> pure $ case att.purpose of
                PurposeContinuation _ -> SendDenied "host stopped the loop"
                _ -> SendAllowed []
          c <- connectOrFail (config stub) {requestHook = hook}
          r <- callInteractive c toolCall
          case r of
            Right (McpUnfinished u) -> do
              u.requestState @?= Just "opaque/state+1=="
              assertBool "denied" (case u.reason of ContinuationDenied _ -> True; _ -> False)
            other -> assertFailure (show other)
          length <$> readIORef seen >>= (@?= 1),
      testCase "a spent round limit stops with the typed outcome" $ do
        seen <- newIORef []
        withStub (modernServer (statefulTool 10 seen)) $ \stub -> do
          c <- connectOrFail (config stub) {limits = fastLimits {maxContinuationRounds = 1}}
          r <- callInteractive c toolCall
          fmap (fmap (.reason)) (unfinishedOf r) @?= Just (Just RoundLimitReached)
          length <$> readIORef seen >>= (@?= 2),
      testCase "a zero round limit disables continuation" $ do
        seen <- newIORef []
        withStub (modernServer (statefulTool 1 seen)) $ \stub -> do
          c <- connectOrFail (config stub) {limits = fastLimits {maxContinuationRounds = 0}}
          r <- callInteractive c toolCall
          fmap (fmap (.reason)) (unfinishedOf r) @?= Just (Just RoundLimitReached)
          length <$> readIORef seen >>= (@?= 1),
      testCase "input requests are returned unanswered"
        $ withStub
          ( modernServer $ \_ r m _ ->
              pure $
                if m == "server/discover"
                  then discover r
                  else okResult r ["resultType" .= ("input_required" :: Text), "inputRequests" .= object ["login" .= object ["method" .= ("elicitation/create" :: Text)]], "requestState" .= ("s" :: Text)]
          )
        $ \stub -> do
          c <- connectOrFail (config stub)
          r <- callInteractive c toolCall
          case r of
            Right (McpUnfinished u) -> do
              u.reason @?= NeedsClientInput
              u.requestState @?= Just "s"
              fmap Map.size u.inputRequests @?= Just 1
            other -> assertFailure (show other)
          length . filter ((== Just "tools/call") . rpcMethod) <$> stub.requests >>= (@?= 1)
    ]
  where
    unfinishedOf = \case
      Right (McpUnfinished u) -> Just (Just u)
      _ -> Nothing

interruption :: TestTree
interruption =
  testCase "an interrupted call reaches the server once and closes its stream"
    $ withStub
      ( modernServer $ \_ r m _ ->
          pure $
            if m == "server/discover"
              then discover r
              else ReplySse 200 [] [Chunk (sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/progress" :: Text), "params" .= object ["progressToken" .= (1 :: Int), "progress" .= (1 :: Int)]])), HoldOpen]
      )
    $ \stub -> do
      c <- connectOrFail (config stub) {limits = fastLimits {requestTimeout = 0.4}}
      notes <- newIORef (0 :: Int)
      e <- callMethod c toolCall {onNotification = Just (\_ _ -> modifyIORef' notes (+ 1))} >>= expectErr
      e.kind @?= TimedOut
      e.delivery @?= Uncertain
      readIORef notes >>= (@?= 1)
      waitFor 50 ((>= 1) <$> stub.clientClosed)
      length . filter ((== Just "tools/call") . rpcMethod) <$> stub.requests >>= (@?= 1)

routing :: TestTree
routing =
  testCase "names and parameter mirrors are encoded into headers" $
    withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r ["content" .= ([] :: [Value])]))) $ \stub -> do
      c <- connectOrFail (config stub)
      region <- either (\e -> assertFailure (show e) >> error "unreachable") (maybe (assertFailure "no mirror" >> error "unreachable") pure) (paramHeader "Region" (Just "Hello, 世界"))
      _ <- callMethod c (mcpCall "tools/call" (KeyMap.fromList [("name", "天気"), ("arguments", object ["region" .= ("Hello, 世界" :: Text)])])) {paramHeaders = [region]}
      calls <- filter ((== Just "tools/call") . rpcMethod) <$> stub.requests
      map (header "Mcp-Name") calls @?= [Just "=?base64?5aSp5rCX?="]
      map (header "Mcp-Param-Region") calls @?= [Just "=?base64?SGVsbG8sIOS4lueVjA==?="]
      map (header "Mcp-Method") calls @?= [Just "tools/call"]