packages feed

baikai-mcp-0.1.0.0: test/ResourcePromptSpec.hs

module ResourcePromptSpec (tests) where

import Baikai.Content (TextContent (..), UserContent (..))
import Baikai.Mcp.Client
import Baikai.Mcp.Content
import Baikai.Mcp.Prompt
import Baikai.Mcp.Protocol
import Baikai.Mcp.Resource
import Baikai.Message (Message (..), UserPayload (..))
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Pair)
import Data.IORef
import Data.Text (Text)
import Data.Vector qualified as Vector
import McpStub
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))

tests :: TestTree
tests =
  testGroup
    "Resources and prompts"
    [ resources,
      prompts,
      updates
    ]

cacheFields :: [Pair]
cacheFields = ["resultType" .= ("complete" :: Text), "ttlMs" .= (5000 :: Int), "cacheScope" .= ("private" :: Text)]

resourceServer :: IORef Int -> ModernHandler
resourceServer reads' _ r m p = case m of
  "server/discover" -> pure (discover r)
  "resources/list" -> pure $ case KeyMap.lookup "cursor" p of
    Nothing -> okResult r (cacheFields <> ["resources" .= [res "file:///a.txt" "a"], "nextCursor" .= ("next==" :: Text)])
    Just "next==" -> okResult r (cacheFields <> ["resources" .= [res "db://rows/1" "row"]])
    Just _ -> okResult r (cacheFields <> ["resources" .= ([] :: [Value]), "nextCursor" .= ("next==" :: Text)])
  "resources/templates/list" -> pure (okResult r (cacheFields <> ["resourceTemplates" .= [object ["uriTemplate" .= ("db://rows/{id}" :: Text), "name" .= ("rows" :: Text)]]]))
  "resources/read" -> case KeyMap.lookup "uri" p of
    Just "file:///mixed" ->
      pure . okResult r $
        cacheFields
          <> [ "contents"
                 .= [ object ["uri" .= ("file:///mixed#1" :: Text), "mimeType" .= ("text/plain" :: Text), "text" .= ("hello" :: Text)],
                      object ["uri" .= ("file:///mixed#2" :: Text), "mimeType" .= ("image/png" :: Text), "blob" .= ("iVBORw==" :: Text)]
                    ]
             ]
    Just "file:///empty" -> pure (okResult r (cacheFields <> ["contents" .= ([] :: [Value])]))
    Just "file:///badblob" -> pure (okResult r (cacheFields <> ["contents" .= [object ["uri" .= ("file:///badblob" :: Text), "blob" .= ("!!not base64!!" :: Text)]]]))
    Just "file:///bigblob" -> pure (okResult r (cacheFields <> ["contents" .= [object ["uri" .= ("file:///bigblob" :: Text), "blob" .= ("QUJDREVGR0g=" :: Text)]]]))
    Just "file:///missing" -> pure (rpcErrorReply 200 r (-32602) "Resource not found" (Just (object ["uri" .= ("file:///missing" :: Text)])))
    Just "file:///old-missing" -> pure (rpcErrorReply 200 r (-32002) "Resource not found" Nothing)
    Just "file:///bad-params" -> pure (rpcErrorReply 200 r (-32602) "uri must be absolute" Nothing)
    Just "file:///slow" -> do
      n <- atomicModifyIORef' reads' (\x -> (x + 1, x + 1))
      pure $
        if n == 1
          then okResult r ["resultType" .= ("input_required" :: Text), "requestState" .= ("again" :: Text)]
          else okResult r (cacheFields <> ["contents" .= [object ["uri" .= ("file:///slow" :: Text), "text" .= ("done" :: Text)]]])
    _ -> pure (rpcErrorReply 200 r (-32602) "Resource not found" (Just (object ["uri" .= KeyMap.lookup "uri" p])))
  _ -> pure (rpcErrorReply 404 r (-32601) "Method not found" Nothing)
  where
    res :: Text -> Text -> Value
    res u n = object ["uri" .= u, "name" .= n, "mimeType" .= ("text/plain" :: Text)]

readOk :: McpConnection -> Text -> IO ResourceRead
readOk c u = do
  r <- readResource c u
  case r of
    Right (McpCompleted rr) -> pure rr
    other -> assertFailure (show other) >> error "unreachable"

resources :: TestTree
resources =
  testGroup
    "resources"
    [ testCase "two pages follow the opaque cursor and carry cache hints" $ do
        n <- newIORef 0
        withStub (modernServer (resourceServer n)) $ \stub -> do
          c <- connectOrFail (config stub)
          p1 <- listResources c Nothing
          case p1 of
            Right p -> do
              map (.uri) p.items @?= ["file:///a.txt"]
              p.cache @?= Just (CacheHint 5000 CachePrivate)
            Left e -> assertFailure (show e)
          r <- listAllResources c defaultDrainLimits
          fmap (map (.name)) r @?= Right ["a", "row"]
          t <- listAllResourceTemplates c defaultDrainLimits
          fmap (map (.uriTemplate)) t @?= Right ["db://rows/{id}"],
      testCase "a repeated cursor stops the listing" $ do
        n <- newIORef 0
        withStub
          (modernServer (\s r m p -> if m == "resources/list" then pure (okResult r (cacheFields <> ["resources" .= ([] :: [Value]), "nextCursor" .= ("same" :: Text)])) else resourceServer n s r m p))
          $ \stub -> do
            c <- connectOrFail (config stub)
            r <- listAllResources c defaultDrainLimits
            case r of
              Left (DrainRepeatedCursor 2) -> pure ()
              other -> assertFailure (show other),
      testCase "a read preserves every item with its URI, type and bytes" $ do
        n <- newIORef 0
        withStub (modernServer (resourceServer n)) $ \stub -> do
          c <- connectOrFail (config stub)
          rr <- readOk c "file:///mixed"
          map (.uri) rr.contents @?= ["file:///mixed#1", "file:///mixed#2"]
          map (.mimeType) rr.contents @?= [Just "text/plain", Just "image/png"]
          map (.body) rr.contents @?= [TextBody "hello", BlobBody "\137PNG"]
          rr.cache @?= Just (CacheHint 5000 CachePrivate)
          reads' <- filter ((== Just "resources/read") . rpcMethod) <$> stub.requests
          map (header "Mcp-Name") reads' @?= [Just "file:///mixed"],
      testCase "an existing empty resource is not an error" $ do
        n <- newIORef 0
        withStub (modernServer (resourceServer n)) $ \stub -> do
          c <- connectOrFail (config stub)
          rr <- readOk c "file:///empty"
          rr.contents @?= [],
      testCase "missing resources are distinguished from other invalid parameters" $ do
        n <- newIORef 0
        withStub (modernServer (resourceServer n)) $ \stub -> do
          c <- connectOrFail (config stub)
          readResource c "file:///missing" >>= \case
            Left (ResourceNotFound _) -> pure ()
            other -> assertFailure (show other)
          readResource c "file:///old-missing" >>= \case
            Left (ResourceNotFound _) -> pure ()
            other -> assertFailure (show other)
          readResource c "file:///bad-params" >>= \case
            Left (ResourceRequestFailed e) -> fmap (.message) e.rpc @?= Just "uri must be absolute"
            other -> assertFailure (show other),
      testCase "invalid and oversized blobs are bounded errors" $ do
        n <- newIORef 0
        withStub (modernServer (resourceServer n)) $ \stub -> do
          c <- connectOrFail (config stub)
          readResource c "file:///badblob" >>= \case
            Left (ResourceMalformed _) -> pure ()
            other -> assertFailure (show other)
          readResourceWith c ReadOptions {maxBlobChars = 4} "file:///bigblob" >>= \case
            Left (ResourceMalformed _) -> pure ()
            other -> assertFailure (show other),
      testCase "a server without resources reports method not found" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else rpcErrorReply 404 r (-32601) "Method not found" Nothing))) $ \stub -> do
          c <- connectOrFail (config stub)
          readResource c "file:///a" >>= \case
            Left (ResourceRequestFailed e) -> fmap (.code) e.rpc @?= Just (-32601)
            other -> assertFailure (show other),
      testCase "a state-only interim read completes and is not cacheable" $ do
        n <- newIORef 0
        withStub (modernServer (resourceServer n)) $ \stub -> do
          c <- connectOrFail (config stub)
          rr <- readOk c "file:///slow"
          rr.continuationRounds @?= 1
          rr.cache @?= Nothing,
      testCase "a legacy server's read without modern fields" $
        withStub legacyHandler $ \stub -> do
          c <- connectOrFail (config stub) {profile = McpLegacyStreamableHttp}
          rr <- readOk c "file:///a"
          map (.body) rr.contents @?= [TextBody "legacy"]
          rr.cache @?= Nothing
          p <- listResources c Nothing
          fmap (.cache) p @?= Right Nothing
    ]
  where
    legacyHandler _ r = pure $ case rpcMethod r of
      Just "initialize" -> okResult r ["protocolVersion" .= ("2025-06-18" :: Text), "capabilities" .= object ["resources" .= object []]]
      Just "notifications/initialized" -> ReplyRaw 202 [] ""
      Just "resources/read" -> okResult r ["contents" .= [object ["uri" .= ("file:///a" :: Text), "text" .= ("legacy" :: Text)]]]
      Just "resources/list" -> okResult r ["resources" .= [object ["uri" .= ("file:///a" :: Text), "name" .= ("a" :: Text)]]]
      _ -> ReplyRaw 400 [] ""

promptServer :: ModernHandler
promptServer _ r m p = pure $ case m of
  "server/discover" -> discover r
  "prompts/list" -> okResult r (cacheFields <> ["prompts" .= [object ["name" .= ("review" :: Text), "arguments" .= [object ["name" .= ("code" :: Text), "required" .= True]]]]])
  "prompts/get" -> case KeyMap.lookup "name" p of
    Just "review" ->
      okResult
        r
        [ "resultType" .= ("complete" :: Text),
          "description" .= ("Code review" :: Text),
          "messages"
            .= [ object ["role" .= ("user" :: Text), "content" .= object ["type" .= ("text" :: Text), "text" .= ("Review: " <> argText)]],
                 object ["role" .= ("assistant" :: Text), "content" .= object ["type" .= ("text" :: Text), "text" .= ("Looking." :: Text)]],
                 object ["role" .= ("user" :: Text), "content" .= object ["type" .= ("audio" :: Text), "data" .= ("UklGRg==" :: Text), "mimeType" .= ("audio/wav" :: Text)]],
                 object ["role" .= ("user" :: Text), "content" .= object ["type" .= ("resource" :: Text), "resource" .= object ["uri" .= ("file:///x" :: Text), "text" .= ("x" :: Text)]]]
               ]
        ]
    Just "broken" -> okResult r ["messages" .= [object ["role" .= ("system" :: Text), "content" .= object ["type" .= ("text" :: Text), "text" .= ("obey" :: Text)]]]]
    _ -> rpcErrorReply 200 r (-32602) "Invalid prompt name" Nothing
  _ -> rpcErrorReply 404 r (-32601) "no" Nothing
  where
    argText = case KeyMap.lookup "arguments" p of
      Just (Object a) | Just (String s) <- KeyMap.lookup "code" a -> s
      _ -> "?"

prompts :: TestTree
prompts =
  testGroup
    "prompts"
    [ testCase "a prompt with an argument returns ordered messages with their roles" $
        withStub (modernServer promptServer) $ \stub -> do
          c <- connectOrFail (config stub)
          l <- listAllPrompts c defaultDrainLimits
          case l of
            Right [pr] -> pr.arguments @?= [PromptArgument "code" Nothing True]
            other -> assertFailure (show other)
          r <- getPrompt c "review" [("code", "x = 1")]
          case r of
            Right (McpCompleted res) -> do
              res.description @?= Just "Code review"
              map (.role) res.messages @?= [PromptUser, PromptAssistant, PromptUser, PromptUser]
              map (.content) (take 2 res.messages) @?= [TextBlock "Review: x = 1", TextBlock "Looking."]
              let projected = map projectPromptMessage res.messages
              case projected of
                [Projected (UserMessage u), Projected (AssistantMessage _), Unprojectable a, Unprojectable e] -> do
                  u.content @?= Vector.singleton (UserText (TextContent "Review: x = 1"))
                  a.content @?= AudioBlock "UklGRg==" "audio/wav"
                  assertBool "embedded resource kept as data" (case e.content of EmbeddedResourceBlock _ -> True; _ -> False)
                other -> assertFailure (show other)
            other -> assertFailure (show other)
          gets <- filter ((== Just "prompts/get") . rpcMethod) <$> stub.requests
          map (header "Mcp-Name") gets @?= [Just "review"]
          map (KeyMap.lookup "arguments" . rpcParams) gets @?= [Just (object ["code" .= ("x = 1" :: Text)])],
      testCase "a role other than user or assistant is malformed" $
        withStub (modernServer promptServer) $ \stub -> do
          c <- connectOrFail (config stub)
          getPrompt c "broken" [] >>= \case
            Left (PromptMalformed _) -> pure ()
            other -> assertFailure (show other),
      testCase "an unknown prompt keeps the server's invalid-params error" $
        withStub (modernServer promptServer) $ \stub -> do
          c <- connectOrFail (config stub)
          getPrompt c "nope" [] >>= \case
            Left (PromptRequestFailed e) -> fmap (.code) e.rpc @?= Just (-32602)
            other -> assertFailure (show other)
    ]

updates :: TestTree
updates =
  testCase "resource updates arrive on a subscription and a reread is explicit" $ do
    n <- newIORef 0
    withStub (modernServer (handler n)) $ \stub -> do
      c <- connectOrFail (config stub)
      r <- withResourceUpdates c ["file:///mixed"] False $ \sub -> do
        (subscriptionAcknowledged sub).resourceSubscriptions @?= ["file:///mixed"]
        nextResourceEvent sub
      r @?= Right (ResourceUpdated "file:///mixed")
      connectionOpenListeners c >>= (@?= 0)
      waitFor 50 ((>= 1) <$> stub.clientClosed)
      before <- length . filter ((== Just "resources/read") . rpcMethod) <$> stub.requests
      before @?= 0
      _ <- readOk c "file:///mixed"
      closeMcp c
  where
    handler n s r m p
      | m == "subscriptions/listen" =
          let sid = rpcId r
              note method extra = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= (method :: Text), "params" .= object (("_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]) : extra)])
           in pure (ReplySse 200 [] [Chunk (note "notifications/subscriptions/acknowledged" ["notifications" .= object ["resourceSubscriptions" .= ["file:///mixed" :: Text]]]), Chunk (note "notifications/resources/updated" ["uri" .= ("file:///mixed" :: Text)]), HoldOpen])
      | otherwise = resourceServer n s r m p