baikai-mcp-0.1.0.0: test/ClientSpec.hs
-- | A consumer that uses only the public API.
module ClientSpec (tests) where
import Baikai.Mcp.Client
import Baikai.Mcp.Protocol
import Control.Exception (SomeException, try)
import Data.Aeson (Key, Value (..), object, (.=))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Parser, parseJSON)
import Data.Text (Text)
import McpStub
import System.Timeout (timeout)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))
tests :: TestTree
tests =
testGroup
"Public client"
[ pages,
subscriptions,
lifecycle
]
-- | Two pages of tool names; the second page's cursor is opaque.
pagedServer :: ModernHandler
pagedServer _ r m p = pure $ case m of
"server/discover" -> discover r
"tools/list" -> case KeyMap.lookup "cursor" p of
Nothing -> okResult r (page ["a", "b"] (Just "opaque==") 1000)
Just "opaque==" -> okResult r (page ["c"] Nothing 500)
Just _ -> rpcErrorReply 400 r (-32602) "invalid cursor" Nothing
_ -> rpcErrorReply 404 r (-32601) "no" Nothing
where
page :: [Text] -> Maybe Text -> Int -> [(Key, Value)]
page names next ttl =
["resultType" .= ("complete" :: Text), "tools" .= map (\n -> object ["name" .= n]) names, "ttlMs" .= ttl, "cacheScope" .= ("private" :: Text)]
<> maybe [] (\c -> ["nextCursor" .= c]) next
toolName :: Value -> Parser Text
toolName = \case
Object o | Just (String n) <- KeyMap.lookup "name" o -> pure n
v -> parseJSON v
pages :: TestTree
pages =
testGroup
"pages"
[ testCase "one page, then the next is denied before transmission" $
withStub (modernServer pagedServer) $ \stub -> do
let hook = McpRequestHook $ \att -> pure (maybe (SendAllowed []) (const (SendDenied "one page only")) att.cursor)
c <- connectOrFail (config stub) {requestHook = hook}
p1 <- requestPage c "tools/list" "tools" toolName Nothing
case p1 of
Right p -> do
p.items @?= ["a", "b"]
fmap cursorToText p.nextCursor @?= Just "opaque=="
p.cache @?= Just (CacheHint 1000 CachePrivate)
e <- requestPage c "tools/list" "tools" toolName p.nextCursor >>= expectErr
e.kind @?= RequestDenied
Left e -> assertFailure (show e)
methodsOf <$> stub.requests >>= (@?= ["server/discover", "tools/list"]),
testCase "a bounded drain follows the opaque cursor" $
withStub (modernServer pagedServer) $ \stub -> do
c <- connectOrFail (config stub)
r <- drainPages defaultDrainLimits (requestPage c "tools/list" "tools" toolName)
either (assertFailure . show) (@?= ["a", "b", "c"]) r
map (KeyMap.lookup "cursor" . rpcParams) . filter ((== Just "tools/list") . rpcMethod) <$> stub.requests
>>= (@?= [Nothing, Just "opaque=="])
]
data Ending = HoldIt | Graceful | ServerCancel | DropIt
listenServer :: Ending -> ModernHandler
listenServer ending _ r m _ = pure $ case m of
"server/discover" -> discover r
"tools/list" -> okResult r ["tools" .= ([] :: [Value])]
"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)])
foreign' = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/tools/list_changed" :: Text), "params" .= object ["_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= (987654 :: Int)]]])
ack = note "notifications/subscriptions/acknowledged" ["notifications" .= object ["toolsListChanged" .= True]]
end = case ending of
HoldIt -> [HoldOpen]
Graceful -> [Chunk (sseResult r ["resultType" .= ("complete" :: Text), "_meta" .= object ["io.modelcontextprotocol/subscriptionId" .= sid]])]
ServerCancel -> [Chunk (sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/cancelled" :: Text), "params" .= object ["requestId" .= sid]]))]
DropIt -> []
in ReplySse 200 [] ([Chunk ack, Chunk (note "notifications/prompts/list_changed" []), Chunk foreign', Chunk ":\n\n", Chunk (note "notifications/tools/list_changed" [])] <> end)
_ -> rpcErrorReply 404 r (-32601) "no" Nothing
requestedFilter :: SubscriptionFilter
requestedFilter = emptySubscriptionFilter {toolsListChanged = True, promptsListChanged = True}
subscriptions :: TestTree
subscriptions =
testGroup
"subscriptions"
[ testCase "acknowledged subset, filtering, and release independent of ordinary calls" $
withStub (modernServer (listenServer HoldIt)) $ \stub -> do
c <- connectOrFail (config stub)
r <- withSubscription c requestedFilter $ \sub -> do
subscriptionAcknowledged sub @?= emptySubscriptionFilter {toolsListChanged = True}
subscriptionRequested sub @?= requestedFilter
connectionOpenListeners c >>= (@?= 1)
ev <- nextSubscriptionEvent sub
case ev of
SubscriptionNotification m _ -> m @?= "notifications/tools/list_changed"
other -> assertFailure (show other)
listed <- callMethod c (mcpCall "tools/list" KeyMap.empty)
assertBool "ordinary call works while listening" (either (const False) (const True) listed)
r @?= Right ()
connectionOpenListeners c >>= (@?= 0)
waitFor 50 ((>= 1) <$> stub.clientClosed)
listed <- callMethod c (mcpCall "tools/list" KeyMap.empty)
assertBool "ordinary call works after release" (either (const False) (const True) listed)
closeMcp c,
testCase "a listen response is a graceful end" $ endsWith Graceful EndedGracefully,
testCase "notifications/cancelled from the server ends the subscription" $ endsWith ServerCancel EndedByServer,
testCase "a stream closing without either signal is a disconnect" $ endsWith DropIt Disconnected,
testCase "a timeout inside the subscription leaves no open listener" $
withStub (modernServer (listenServer HoldIt)) $ \stub -> do
c <- connectOrFail (config stub)
r <- timeout 300000 (withSubscription c requestedFilter (\sub -> nextSubscriptionEvent sub >> nextSubscriptionEvent sub))
case r of
Nothing -> pure ()
Just other -> assertFailure ("expected the timeout to fire: " <> show other)
connectionOpenListeners c >>= (@?= 0)
waitFor 50 ((>= 1) <$> stub.clientClosed)
closeMcp c,
testCase "closeMcp ends open subscriptions" $
withStub (modernServer (listenServer HoldIt)) $ \stub -> do
c <- connectOrFail (config stub)
_ <- withSubscription c requestedFilter $ \sub -> do
_ <- nextSubscriptionEvent sub
closeMcp c
ev <- nextSubscriptionEvent sub
ev @?= SubscriptionEnded EndedByClient
waitFor 50 ((>= 1) <$> stub.clientClosed)
]
where
endsWith ending expected =
withStub (modernServer (listenServer ending)) $ \stub -> do
c <- connectOrFail (config stub)
r <- withSubscription c requestedFilter $ \sub -> do
_ <- nextSubscriptionEvent sub
e1 <- nextSubscriptionEvent sub
e2 <- nextSubscriptionEvent sub
pure (e1, e2)
r @?= Right (SubscriptionEnded expected, SubscriptionEnded expected)
closeMcp c
lifecycle :: TestTree
lifecycle =
testGroup
"lifecycle"
[ testCase "a released handle refuses operations without sending" $
withStub (modernServer pagedServer) $ \stub -> do
c <- connectOrFail (config stub)
closeMcp c
closeMcp c
e <- callMethod c (mcpCall "tools/list" KeyMap.empty) >>= expectErr
e.kind @?= ConnectionReleased
e.delivery @?= NotSent
methodsOf <$> stub.requests >>= (@?= ["server/discover"]),
testCase "hook headers reach the server; protocol headers cannot be overridden" $
withStub (modernServer pagedServer) $ \stub -> do
let creds = McpRequestHook (\_ -> pure (SendAllowed [sendHeader "Authorization" "Bearer sentinel-token"]))
c <- connectOrFail (config stub) {requestHook = creds}
_ <- callMethod c (mcpCall "tools/list" KeyMap.empty)
map (header "Authorization") <$> stub.requests >>= (@?= replicate 2 (Just "Bearer sentinel-token"))
let bad = McpRequestHook (\_ -> pure (SendAllowed [sendHeader "Mcp-Method" "tools/call"]))
e <- connectMcp (config stub) {requestHook = bad} >>= expectErr
e.kind @?= InvalidInput
length <$> stub.requests >>= (@?= 2)
assertBool "the header value is not shown" (show (sendHeader "Authorization" "Bearer sentinel-token") /= "" && not (contains "sentinel" (show (sendHeader "Authorization" "Bearer sentinel-token")))),
testCase "withMcpConnection releases on exceptions" $
withStub (modernServer (listenServer HoldIt)) $ \stub -> do
r <- try @SomeException $ withMcpConnection (config stub) $ \c ->
withSubscription c requestedFilter (\_ -> ioError (userError "boom"))
assertBool "exception propagated" (either (const True) (const False) r)
waitFor 50 ((>= 1) <$> stub.clientClosed),
testCase "an endpoint with embedded credentials is refused" $ do
e <- connectMcp (mcpServerConfig "x" "https://user:secret@example.com/mcp") >>= expectErr
e.kind @?= InvalidInput
assertBool "secret not rendered" (not (contains "secret" (show e)))
]
where
contains :: String -> String -> Bool
contains needle hay = any (\i -> take (length needle) (drop i hay) == needle) [0 .. length hay]