packages feed

baikai-mcp-0.1.0.0: test/ToolSpec.hs

module ToolSpec (tests) where

import Baikai.Content (ImageContent (..), TextContent (..), ToolResultContent (..))
import Baikai.Mcp.Client
import Baikai.Mcp.JsonSchema (SchemaViolation (..))
import Baikai.Mcp.Protocol
import Baikai.Mcp.Tool
import Baikai.Message (ToolResult (..))
import Baikai.Tool (Tool (description, name, parameters))
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object, 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
    "Tools"
    [ descriptors,
      discovery,
      invocation,
      results,
      changes,
      legacy
    ]

-- ---------------------------------------------------------------------------
-- Fixture descriptors

composedInput :: Value
composedInput =
  object
    [ "type" .= ("object" :: Text),
      "$defs" .= object ["unit" .= object ["enum" .= ["c", "f" :: Text]]],
      "properties"
        .= object
          [ "region" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Region" :: Text)],
            "options" .= object ["type" .= ("object" :: Text), "properties" .= object ["count" .= object ["type" .= ("integer" :: Text), "x-mcp-header" .= ("Count" :: Text)]]],
            "unit" .= object ["$ref" .= ("#/$defs/unit" :: Text)],
            "query" .= object ["anyOf" .= [object ["type" .= ("string" :: Text)], object ["type" .= ("null" :: Text)]]]
          ],
      "required" .= ["region" :: Text]
    ]

weatherTool :: Value
weatherTool =
  object
    [ "name" .= ("get_weather" :: Text),
      "title" .= ("Weather" :: Text),
      "inputSchema" .= composedInput,
      "outputSchema"
        .= object
          [ "$defs" .= object ["temp" .= object ["type" .= ("number" :: Text)]],
            "type" .= ("object" :: Text),
            "properties" .= object ["temperature" .= object ["$ref" .= ("#/$defs/temp" :: Text)], "unit" .= object ["enum" .= ["c", "f" :: Text]]],
            "required" .= ["temperature" :: Text],
            "allOf" .= [object ["not" .= object ["required" .= ["error" :: Text]]]]
          ]
    ]

plainTool :: Text -> Value
plainTool n = object ["name" .= n, "inputSchema" .= object ["type" .= ("object" :: Text)]]

badTools :: [Value]
badTools =
  [ object ["name" .= ("on_number" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["n" .= object ["type" .= ("number" :: Text), "x-mcp-header" .= ("N" :: Text)]]]],
    object ["name" .= ("duplicate" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["a" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Dup" :: Text)], "b" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("dup" :: Text)]]]],
    object ["name" .= ("under_items" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["xs" .= object ["type" .= ("array" :: Text), "items" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Item" :: Text)]]]]],
    object ["name" .= ("bad_token" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["a" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("Bad Name" :: Text)]]]]
  ]

-- | A modern server with a two-page tool list and a scriptable tools/call.
toolServer :: (StubRequest -> Text -> Object -> IO StubReply) -> ModernHandler
toolServer onCall _ r m p = case m of
  "server/discover" -> pure (discover r)
  "tools/list" -> pure $ case KeyMap.lookup "cursor" p of
    Nothing -> okResult r (listPage (weatherTool : take 2 badTools) (Just "p2"))
    Just "p2" -> okResult r (listPage (plainTool "echo" : drop 2 badTools) Nothing)
    Just _ -> rpcErrorReply 400 r (-32602) "invalid cursor" Nothing
  "tools/call" -> case KeyMap.lookup "name" p of
    Just (String n) -> onCall r n p
    _ -> pure (rpcErrorReply 400 r (-32602) "no name" Nothing)
  _ -> pure (rpcErrorReply 404 r (-32601) "no" Nothing)

listPage :: [Value] -> Maybe Text -> [Pair]
listPage ts next =
  ["resultType" .= ("complete" :: Text), "tools" .= ts, "ttlMs" .= (0 :: Int), "cacheScope" .= ("public" :: Text)]
    <> maybe [] (\c -> ["nextCursor" .= c]) next

completeWith :: [Pair] -> StubRequest -> Text -> Object -> IO StubReply
completeWith fields r _ _ = pure (okResult r (("resultType" .= ("complete" :: Text)) : fields))

discoverTools :: McpConnection -> IO ToolListing
discoverTools c = do
  r <- listTools c defaultDrainLimits
  case r of
    Right l -> pure l
    Left e -> assertFailure (show e) >> error "unreachable"

weatherOf :: ToolListing -> IO McpTool
weatherOf l = case [t | t <- l.tools, t.name == "get_weather"] of
  [t] -> pure t
  _ -> assertFailure "get_weather missing" >> error "unreachable"

completed :: Either McpToolError (McpOutcome McpToolResult) -> IO McpToolResult
completed = \case
  Right (McpCompleted r) -> pure r
  other -> assertFailure ("expected a completed result: " <> show other) >> error "unreachable"

toolCalls :: Stub -> IO [StubRequest]
toolCalls stub = filter ((== Just "tools/call") . rpcMethod) <$> stub.requests

-- ---------------------------------------------------------------------------

descriptors :: TestTree
descriptors =
  testGroup
    "descriptors"
    [ testCase "the input schema survives projection to a model tool verbatim" $
        case decodeTool True weatherTool of
          Right t -> do
            let bt = toBaikaiTool t
            bt.name @?= "get_weather"
            bt.parameters @?= composedInput
            bt.description @?= "Weather"
            t.headerMirrors @?= [HeaderMirror "Count" ["options", "count"], HeaderMirror "Region" ["region"]]
          Left e -> assertFailure (show e),
      testCase "invalid x-mcp-header annotations reject the tool" $
        mapM_ (\v -> assertBool (show v) (either (const True) (const False) (decodeTool True v))) badTools,
      testCase "annotations are ignored where mirrors are not used" $
        mapM_ (\v -> assertBool (show v) (either (const False) (null . (.headerMirrors)) (decodeTool False v))) badTools,
      testCase "an annotation on the root or inside composition is rejected" $ do
        assertBool "root" . either (const True) (const False) $ decodeTool True (object ["name" .= ("r" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "x-mcp-header" .= ("Root" :: Text)]])
        assertBool "anyOf" . either (const True) (const False) $
          decodeTool True (object ["name" .= ("c" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text), "anyOf" .= [object ["properties" .= object ["a" .= object ["type" .= ("string" :: Text), "x-mcp-header" .= ("A" :: Text)]]]]]])
    ]

discovery :: TestTree
discovery =
  testGroup
    "discovery"
    [ testCase "two pages are drained; invalid siblings are excluded and reported" $
        withStub (modernServer (toolServer (completeWith []))) $ \stub -> do
          c <- connectOrFail (config stub)
          l <- discoverTools c
          map (.name) l.tools @?= ["get_weather", "echo"]
          map (.toolName) l.rejected @?= map Just ["on_number", "duplicate", "under_items", "bad_token"]
          closeMcp c,
      testCase "a page carries its cache hint and cursor" $
        withStub (modernServer (toolServer (completeWith []))) $ \stub -> do
          c <- connectOrFail (config stub)
          r <- listToolsPage c Nothing
          case r of
            Right tp -> do
              tp.page.cache @?= Just (CacheHint 0 CachePublic)
              fmap cursorToText tp.page.nextCursor @?= Just "p2"
              length tp.rejected @?= 2
            Left e -> assertFailure (show e),
      testCase "a denied second page leaves one request at the server" $
        withStub (modernServer (toolServer (completeWith []))) $ \stub -> do
          let hook = McpRequestHook (\att -> pure (maybe (SendAllowed []) (const (SendDenied "page budget")) att.cursor))
          c <- connectOrFail (config stub) {requestHook = hook}
          r <- listTools c defaultDrainLimits
          case r of
            Left (DrainPageFailed 2 e) -> e.kind @?= RequestDenied
            other -> assertFailure (show other)
          length . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests >>= (@?= 1),
      testCase "a cyclic cursor stops discovery" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r (listPage [plainTool "a"] (Just "loop"))))) $ \stub -> do
          c <- connectOrFail (config stub)
          r <- listTools c defaultDrainLimits
          case r of
            Left (DrainRepeatedCursor 2) -> pure ()
            other -> assertFailure (show other),
      testCase "a malformed list response is an error" $
        withStub (modernServer (\_ r m _ -> pure (if m == "server/discover" then discover r else okResult r ["tools" .= ("nope" :: Text)]))) $ \stub -> do
          c <- connectOrFail (config stub)
          r <- listToolsPage c Nothing
          case r of
            Left e -> e.kind @?= MalformedReply
            Right _ -> assertFailure "expected a malformed reply"
    ]

invocation :: TestTree
invocation =
  testGroup
    "invocation"
    [ testCase "native name, arguments, Unicode and nested mirrors; null mirror omitted" $
        withStub (modernServer (toolServer (completeWith ["content" .= ([] :: [Value]), "structuredContent" .= object ["temperature" .= (21.5 :: Double)]]))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          let args = KeyMap.fromList [("region", "東京"), ("options", object ["count" .= Null]), ("unit", "c")]
          r <- callTool c (mcpToolCall t args) >>= completed
          r.outputCheck @?= OutputConforms
          [call] <- toolCalls stub
          KeyMap.lookup "name" (rpcParams call) @?= Just "get_weather"
          KeyMap.lookup "arguments" (rpcParams call) @?= Just (Object args)
          header "Mcp-Name" call @?= Just "get_weather"
          header "Mcp-Param-Region" call @?= Just "=?base64?5p2x5Lqs?="
          header "Mcp-Param-Count" call @?= Nothing,
      testCase "an unmirrorable argument is refused before sending" $
        withStub (modernServer (toolServer (completeWith ["content" .= ([] :: [Value])]))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", object [])]))
          case r of
            Left (ToolArgumentsUnmirrorable _) -> pure ()
            other -> assertFailure (show other)
          toolCalls stub >>= (@?= []) . map rpcId,
      testCase "a header-mismatch rejection is descriptor drift and is not retried" $
        withStub (modernServer (toolServer (\r _ _ -> pure (rpcErrorReply 400 r (-32020) "Header mismatch: Mcp-Param-Region" Nothing)))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          before <- length <$> stub.requests
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "x")]))
          case r of
            Left (ToolDescriptorDrift e) -> e.delivery @?= Answered
            other -> assertFailure (show other)
          after <- length <$> stub.requests
          after - before @?= 1,
      testCase "a state-only interim result completes on its second round with the same mirrors" $ do
        rounds <- newIORef (0 :: Int)
        let onCall r _ _ = do
              n <- atomicModifyIORef' rounds (\x -> (x + 1, x + 1))
              pure $
                if n == 1
                  then okResult r ["resultType" .= ("input_required" :: Text), "requestState" .= ("st" :: Text)]
                  else okResult r ["resultType" .= ("complete" :: Text), "content" .= ([] :: [Value]), "structuredContent" .= object ["temperature" .= (1 :: Int)]]
        withStub (modernServer (toolServer onCall)) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")])) >>= completed
          r.continuationRounds @?= 1
          calls <- toolCalls stub
          map (header "Mcp-Param-Region") calls @?= [Just "eu", Just "eu"]
          map (KeyMap.lookup "arguments" . rpcParams) calls @?= replicate 2 (Just (object ["region" .= ("eu" :: Text)]))
          map (KeyMap.lookup "requestState" . rpcParams) calls @?= [Nothing, Just "st"],
      testCase "an interim result with input requests is returned unanswered" $
        withStub (modernServer (toolServer (\r _ _ -> pure (okResult r ["resultType" .= ("input_required" :: Text), "inputRequests" .= object ["q" .= object ["method" .= ("sampling/createMessage" :: Text)]]])))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))
          case r of
            Right (McpUnfinished u) -> u.reason @?= NeedsClientInput
            other -> assertFailure (show other),
      testCase "a dropped response is uncertain and reaches the server exactly once" $
        withStub (modernServer (toolServer (\_ _ _ -> pure (ReplySse 200 [] [Chunk ":\n\n"])))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))
          case r of
            Left (ToolRequestFailed e) -> e.delivery @?= Uncertain
            other -> assertFailure (show other)
          length <$> toolCalls stub >>= (@?= 1)
    ]

results :: TestTree
results =
  testGroup
    "results"
    [ testCase "a composed output-schema violation keeps the result" $
        withStub (modernServer (toolServer (completeWith ["content" .= ([] :: [Value]), "structuredContent" .= object ["temperature" .= ("warm" :: Text), "error" .= True]]))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))
          case r of
            Left (ToolOutputViolatesSchema vs res) -> do
              assertBool "type violation" (any ((== "/temperature") . (.instancePath)) vs)
              assertBool "composed violation" (any ((== "not") . (.keyword)) vs)
              res.structured @?= StructuredContent (object ["temperature" .= ("warm" :: Text), "error" .= True])
            other -> assertFailure (show other),
      testCase "a declared schema without structured content cannot be verified" $
        withStub (modernServer (toolServer (completeWith ["content" .= [object ["type" .= ("text" :: Text), "text" .= ("hi" :: Text)]]]))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")]))
          case r of
            Left (ToolOutputUnverifiable _ _) -> pure ()
            other -> assertFailure (show other),
      testCase "structured-only array and present null" $ do
        let arrayTool = object ["name" .= ("arr" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)], "outputSchema" .= object ["type" .= ("array" :: Text), "items" .= object ["type" .= ("integer" :: Text)]]]
            nullTool = object ["name" .= ("nul" :: Text), "inputSchema" .= object ["type" .= ("object" :: Text)], "outputSchema" .= object ["type" .= ("null" :: Text)]]
            onCall r n _ = pure . okResult r $ ["resultType" .= ("complete" :: Text), "content" .= ([] :: [Value])] <> if n == "arr" then ["structuredContent" .= [1, 2 :: Int]] else ["structuredContent" .= Null]
        withStub (modernServer (\s r m p -> if m == "tools/list" then pure (okResult r (listPage [arrayTool, nullTool] Nothing)) else toolServer onCall s r m p)) $ \stub -> do
          c <- connectOrFail (config stub)
          l <- discoverTools c
          case l.tools of
            [a, n] -> do
              ra <- callTool c (mcpToolCall a KeyMap.empty) >>= completed
              ra.structured @?= StructuredContent (Aeson.toJSON [1, 2 :: Int])
              ra.outputCheck @?= OutputConforms
              (projectToolResult ra).toolResult.content @?= Vector.fromList [ToolResultText (TextContent "[1,2]")]
              rn <- callTool c (mcpToolCall n KeyMap.empty) >>= completed
              rn.structured @?= StructuredContent Null
              rn.outputCheck @?= OutputConforms
            other -> assertFailure (show (map (.name) other)),
      testCase "mixed content is preserved and projection reports what it drops" $ do
        let blocks =
              [ object ["type" .= ("text" :: Text), "text" .= ("hello" :: Text)],
                object ["type" .= ("image" :: Text), "data" .= ("iVBORw==" :: Text), "mimeType" .= ("image/png" :: Text)],
                object ["type" .= ("audio" :: Text), "data" .= ("UklGRg==" :: Text), "mimeType" .= ("audio/wav" :: Text)],
                object ["type" .= ("resource_link" :: Text), "uri" .= ("file:///a" :: Text), "name" .= ("a" :: Text)],
                object ["type" .= ("resource" :: Text), "resource" .= object ["uri" .= ("file:///b" :: Text), "text" .= ("b" :: Text)]],
                object ["type" .= ("hologram" :: Text)]
              ]
        withStub (modernServer (toolServer (completeWith ["content" .= blocks]))) $ \stub -> do
          c <- connectOrFail (config stub)
          l <- discoverTools c
          echo <- case [t | t <- l.tools, t.name == "echo"] of
            [t] -> pure t
            _ -> assertFailure "echo missing" >> error "unreachable"
          r <- callTool c (mcpToolCall echo KeyMap.empty) >>= completed
          length r.content @?= 6
          r.outputCheck @?= NoOutputSchema
          let p = projectToolResult r
          p.toolResult.content @?= Vector.fromList [ToolResultText (TextContent "hello"), ToolResultImage (ImageContent "\137PNG" "image/png")]
          length p.unprojected @?= 4,
      testCase "a tool-reported error is not checked against the output schema" $
        withStub (modernServer (toolServer (completeWith ["content" .= [object ["type" .= ("text" :: Text), "text" .= ("boom" :: Text)]], "isError" .= True]))) $ \stub -> do
          c <- connectOrFail (config stub)
          t <- discoverTools c >>= weatherOf
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("region", "eu")])) >>= completed
          r.isError @?= True
          r.outputCheck @?= NotCheckedToolError
          let (_, dropped) = toolResultMessageFor "call_1" "weather" r
          dropped @?= []
          (projectToolResult r).toolResult.isError @?= True
    ]

changes :: TestTree
changes =
  testCase "a list-change notification never refetches or alters a bound descriptor" $
    withStub (modernServer handler) $ \stub -> do
      c <- connectOrFail (config stub)
      t <- discoverTools c >>= weatherOf
      let call = mcpToolCall t (KeyMap.fromList [("region", "eu")])
      before <- length . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests
      r <- withToolListChanges c $ \sub -> do
        (subscriptionAcknowledged sub).toolsListChanged @?= True
        nextToolListChange sub
      r @?= Right ToolListChanged
      after <- length . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests
      after @?= before
      call.tool @?= t
  where
    handler 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 ["toolsListChanged" .= True]]), Chunk (note "notifications/tools/list_changed" []), HoldOpen])
      | otherwise = toolServer (completeWith []) s r m p

legacy :: TestTree
legacy =
  testCase "a handshake-era server lists and calls tools with its own shapes" $
    withStub handler $ \stub -> do
      c <- connectOrFail (config stub) {profile = McpLegacyStreamableHttp}
      l <- discoverTools c
      map (.name) l.tools @?= ["on_number"]
      l.rejected @?= []
      case l.tools of
        [t] -> do
          t.headerMirrors @?= []
          r <- callTool c (mcpToolCall t (KeyMap.fromList [("n", Number 1.5)])) >>= completed
          r.content @?= [TextBlock "ok"]
          [call] <- toolCalls stub
          header "Mcp-Param-N" call @?= Nothing
          header "Mcp-Name" call @?= Nothing
        _ -> assertFailure "expected one tool"
  where
    handler _ r = pure $ case rpcMethod r of
      Just "initialize" -> okResult r ["protocolVersion" .= ("2025-11-25" :: Text), "capabilities" .= object ["tools" .= object []]]
      Just "notifications/initialized" -> ReplyRaw 202 [] ""
      Just "tools/list" -> okResult r ["tools" .= take 1 badTools]
      Just "tools/call" -> okResult r ["content" .= [object ["type" .= ("text" :: Text), "text" .= ("ok" :: Text)]]]
      _ -> ReplyRaw 400 [] ""