baikai-mcp-0.1.0.0: test/McpStub.hs
-- | A scripted, in-process MCP server for wire tests.
--
-- Each test supplies a handler from a captured request to a reply. The
-- stub records every request (including its headers and decoded JSON),
-- counts streams the client closed before the server finished them, and
-- offers one push channel that feeds every open "channel" event stream,
-- which the HTTP+SSE fixture uses to deliver replies.
module McpStub
( Stub (..),
StubRequest (..),
StubReply (..),
SseStep (..),
withStub,
-- * Inspecting requests
rpcMethod,
rpcId,
rpcParams,
rpcMeta,
header,
-- * Building replies
ok,
okResult,
rpcErrorReply,
rpcErrorBody,
sseMessage,
sseResult,
discoverResultObject,
discover,
-- * A strict modern server
modernServer,
ModernHandler,
methodsOf,
-- * Test support
fastLimits,
config,
connectOrFail,
expectErr,
waitFor,
)
where
import Baikai.Mcp.Client
import Baikai.Mcp.Transport (decodeHeaderValue)
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM
import Control.Exception (SomeException, finally, try)
import Control.Monad (forM_, forever)
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object, Pair)
import Data.ByteString (ByteString)
import Data.ByteString.Builder qualified as Builder
import Data.ByteString.Lazy qualified as LBS
import Data.CaseInsensitive qualified as CI
import Data.IORef
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TE
import Network.HTTP.Types (Header, RequestHeaders, mkStatus)
import Network.Wai qualified as Wai
import Network.Wai.Handler.Warp qualified as Warp
import Test.Tasty.HUnit (Assertion, assertFailure)
data StubRequest = StubRequest
{ httpMethod :: !ByteString,
path :: !ByteString,
query :: !ByteString,
headers :: !RequestHeaders,
body :: !LBS.ByteString,
json :: !(Maybe Value)
}
deriving stock (Show)
data SseStep
= -- | Raw bytes, written and flushed.
Chunk !ByteString
| Pause !Int
| -- | Keep the stream open, sending comment keep-alives, until the
-- client disconnects.
HoldOpen
data StubReply
= ReplyJson !Int ![Header] !Value
| ReplyRaw !Int ![Header] !LBS.ByteString
| ReplySse !Int ![Header] ![SseStep]
| -- | An event stream fed by 'push' until the client disconnects.
ReplyChannel !Int ![Header] ![ByteString]
data Stub = Stub
{ url :: !Text,
requests :: IO [StubRequest],
-- | Event streams the client closed while the server still had more to
-- send or was holding them open.
clientClosed :: IO Int,
-- | Feed bytes to every open channel stream.
push :: ByteString -> IO ()
}
withStub :: (Stub -> StubRequest -> IO StubReply) -> (Stub -> IO a) -> IO a
withStub handler action = do
ref <- newIORef []
closedCount <- newIORef (0 :: Int)
chan <- newBroadcastTChanIO
stubRef <- newIORef (error "stub not ready")
let app request respond = do
bytes <- Wai.strictRequestBody request
let captured =
StubRequest
{ httpMethod = Wai.requestMethod request,
path = Wai.rawPathInfo request,
query = Wai.rawQueryString request,
headers = Wai.requestHeaders request,
body = bytes,
json = Aeson.decode bytes
}
atomicModifyIORef' ref (\xs -> (xs <> [captured], ()))
stub <- readIORef stubRef
reply <- handler stub captured
case reply of
ReplyJson code hs v ->
respond (Wai.responseLBS (mkStatus code "stub") (("Content-Type", "application/json") : hs) (Aeson.encode v))
ReplyRaw code hs b -> respond (Wai.responseLBS (mkStatus code "stub") hs b)
ReplySse code hs steps ->
respond . Wai.responseStream (mkStatus code "stub") (("Content-Type", "text/event-stream") : hs) $ \write flush -> do
r <- try @SomeException $ forM_ steps $ \case
Chunk b -> write (Builder.byteString b) >> flush
Pause n -> threadDelay n
HoldOpen -> forever (write (Builder.byteString ":\n") >> flush >> threadDelay 20000)
case r of
Left _ -> atomicModifyIORef' closedCount (\n -> (n + 1, ()))
Right () -> pure ()
ReplyChannel code hs initial -> do
sub <- atomically (dupTChan chan)
respond . Wai.responseStream (mkStatus code "stub") (("Content-Type", "text/event-stream") : hs) $ \write flush -> do
r <- try @SomeException $ do
forM_ initial $ \b -> write (Builder.byteString b) >> flush
forever $ do
next <- atomically (tryReadTChan sub)
case next of
Just b -> write (Builder.byteString b) >> flush
Nothing -> write (Builder.byteString ":\n") >> flush >> threadDelay 20000
case r of
Left _ -> atomicModifyIORef' closedCount (\n -> (n + 1, ()))
Right () -> pure ()
Warp.testWithApplication (pure app) $ \port -> do
let stub =
Stub
{ url = "http://127.0.0.1:" <> Text.pack (show port) <> "/mcp",
requests = readIORef ref,
clientClosed = readIORef closedCount,
push = \b -> atomically (writeTChan chan b)
}
writeIORef stubRef stub
action stub `finally` pure ()
-- ---------------------------------------------------------------------------
-- Inspecting
rpcMethod :: StubRequest -> Maybe Text
rpcMethod r = case r.json of
Just (Object o) | Just (String m) <- KeyMap.lookup "method" o -> Just m
_ -> Nothing
rpcId :: StubRequest -> Value
rpcId r = case r.json of
Just (Object o) | Just i <- KeyMap.lookup "id" o -> i
_ -> Null
rpcParams :: StubRequest -> Object
rpcParams r = case r.json of
Just (Object o) | Just (Object p) <- KeyMap.lookup "params" o -> p
_ -> KeyMap.empty
rpcMeta :: StubRequest -> Object
rpcMeta r = case KeyMap.lookup "_meta" (rpcParams r) of
Just (Object m) -> m
_ -> KeyMap.empty
header :: ByteString -> StubRequest -> Maybe ByteString
header n r = lookup (CI.mk n) r.headers
-- | Method names, or the HTTP verb for requests without a JSON-RPC body.
methodsOf :: [StubRequest] -> [Text]
methodsOf = map (\r -> maybe (TE.decodeUtf8 r.httpMethod) id (rpcMethod r))
-- ---------------------------------------------------------------------------
-- Building
ok :: Value -> StubReply
ok = ReplyJson 200 []
-- | A result response to the request.
okResult :: StubRequest -> [Pair] -> StubReply
okResult r fields = ok (object ["jsonrpc" .= ("2.0" :: Text), "id" .= rpcId r, "result" .= object fields])
rpcErrorBody :: Value -> Int -> Text -> Maybe Value -> Value
rpcErrorBody i c m d =
object
[ "jsonrpc" .= ("2.0" :: Text),
"id" .= i,
"error" .= object (["code" .= c, "message" .= m] <> maybe [] (\x -> ["data" .= x]) d)
]
rpcErrorReply :: Int -> StubRequest -> Int -> Text -> Maybe Value -> StubReply
rpcErrorReply status r c m d = ReplyJson status [] (rpcErrorBody (rpcId r) c m d)
sseMessage :: Value -> ByteString
sseMessage v = "event: message\ndata: " <> LBS.toStrict (Aeson.encode v) <> "\n\n"
sseResult :: StubRequest -> [Pair] -> ByteString
sseResult r fields = sseMessage (object ["jsonrpc" .= ("2.0" :: Text), "id" .= rpcId r, "result" .= object fields])
discoverResultObject :: [Pair]
discoverResultObject =
[ "resultType" .= ("complete" :: Text),
"supportedVersions" .= ["2026-07-28" :: Text],
"capabilities" .= object ["tools" .= object ["listChanged" .= True], "resources" .= object [], "prompts" .= object []],
"_meta" .= object ["io.modelcontextprotocol/serverInfo" .= object ["name" .= ("stub" :: Text), "version" .= ("1.0.0" :: Text)]],
"instructions" .= ("stub instructions" :: Text),
"ttlMs" .= (60000 :: Int),
"cacheScope" .= ("public" :: Text)
]
-- | The standard discovery answer.
discover :: StubRequest -> StubReply
discover r = okResult r discoverResultObject
-- ---------------------------------------------------------------------------
-- A strict modern server
-- | Handles a validated modern request: method and params.
type ModernHandler = Stub -> StubRequest -> Text -> Object -> IO StubReply
-- | Reject anything a 2026-07-28 server must reject — handshake requests,
-- missing per-request metadata, routing headers that disagree with the
-- body — and answer @server/discover@ unless the handler does.
modernServer :: ModernHandler -> Stub -> StubRequest -> IO StubReply
modernServer handler stub r
| r.httpMethod /= "POST" = pure (ReplyRaw 405 [] "")
| otherwise = case rpcMethod r of
Nothing -> pure (rpcErrorReply 400 r (-32600) "invalid request" Nothing)
Just "initialize" -> pure (rpcErrorReply 400 r (-32601) "initialize is not supported; this server speaks 2026-07-28" Nothing)
Just m -> case validate m of
Just problem -> pure (rpcErrorReply 400 r (-32020) problem Nothing)
Nothing -> handler stub r m (rpcParams r)
where
validate m =
let meta = rpcMeta r
version = case KeyMap.lookup "io.modelcontextprotocol/protocolVersion" meta of
Just (String v) -> Just v
_ -> Nothing
nameField = case m of
"tools/call" -> Just "name"
"prompts/get" -> Just "name"
"resources/read" -> Just "uri"
_ -> Nothing
bodyName =
nameField >>= \k -> case KeyMap.lookup (Key.fromText k) (rpcParams r) of
Just (String s) -> Just s
_ -> Nothing
headerName = header "Mcp-Name" r >>= either (const Nothing) Just . decodeHeaderValue
in firstProblem
[ (version == Nothing, "missing protocolVersion in _meta"),
(not (KeyMap.member "io.modelcontextprotocol/clientCapabilities" meta), "missing clientCapabilities in _meta"),
(fmap TE.decodeUtf8 (header "MCP-Protocol-Version" r) /= version, "MCP-Protocol-Version does not match _meta"),
(fmap TE.decodeUtf8 (header "Mcp-Method" r) /= Just m, "Mcp-Method does not match the body"),
(headerName /= bodyName, "Mcp-Name does not match the body"),
(header "Mcp-Session-Id" r /= Nothing, "a modern request must not carry a session")
]
firstProblem = foldr (\(bad, why) rest -> if bad then Just why else rest) Nothing
-- ---------------------------------------------------------------------------
-- Test support
fastLimits :: McpLimits
fastLimits = defaultMcpLimits {requestTimeout = 2, connectTimeout = 2}
config :: Stub -> McpServerConfig
config stub = (mcpServerConfig "stub" stub.url) {limits = fastLimits}
connectOrFail :: McpServerConfig -> IO McpConnection
connectOrFail cfg = do
r <- connectMcp cfg
case r of
Left e -> assertFailure ("connect failed: " <> show e) >> error "unreachable"
Right c -> pure c
expectErr :: Either McpError a -> IO McpError
expectErr = \case
Left e -> pure e
Right _ -> assertFailure "expected an error" >> error "unreachable"
-- | Poll a condition every 20 ms, up to @n@ times.
waitFor :: Int -> IO Bool -> Assertion
waitFor 0 _ = assertFailure "condition not reached"
waitFor n cond = do
ok' <- cond
if ok' then pure () else threadDelay 20000 >> waitFor (n - 1) cond