baikai-mcp-0.1.0.0: src/Baikai/Mcp/Transport/HttpSse.hs
-- | The deprecated two-endpoint HTTP+SSE transport of revision
-- @2024-11-05@.
--
-- The client opens one long-lived @GET@ event stream. Its first event,
-- @endpoint@, names the URL to which the client @POST@s every message; the
-- server answers each @POST@ with @202 Accepted@ and delivers the actual
-- replies as @message@ events on the @GET@ stream.
--
-- MCP @2026-07-28@ lists this transport as Deprecated and eligible for
-- removal three months after its feature lifecycle policy becomes final.
-- It is selected only by explicit configuration and lives in this one
-- module so that it can be removed without touching any other profile.
--
-- The advertised message endpoint must have the same origin as the
-- configured endpoint. Otherwise the connection is refused before anything
-- — in particular a credential — is sent to it.
module Baikai.Mcp.Transport.HttpSse
( openHttpSseBinding,
)
where
import Baikai.Mcp.Error
import Baikai.Mcp.Internal.Binding
import Baikai.Mcp.Internal.Http
import Baikai.Mcp.Internal.Mux qualified as Mux
import Baikai.Mcp.Internal.Sse (SseEvent (..))
import Baikai.Mcp.Protocol
import Control.Concurrent.Async (async, cancel)
import Control.Exception (SomeException, finally, mask, onException, try)
import Data.Aeson qualified as Aeson
import Data.ByteString qualified as BS
import Data.IORef
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TE
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Types (Header, hAccept, hContentType)
import Network.URI (parseURIReference, relativeTo)
import System.Timeout (timeout)
-- | Open the event stream with the given (hook-approved) headers, wait at
-- most @waitMicros@ for the @endpoint@ event and return a multiplexed
-- binding. @postHeaders@ supplies the headers each later @POST@ carries
-- beyond those the client passes per exchange.
openHttpSseBinding :: HTTP.Manager -> HttpEndpoint -> WireLimits -> Int -> [Header] -> IO (Either McpError Binding)
openHttpSseBinding mgr ep lim waitMicros hdrs = mask $ \restore -> do
let getReq =
ep.request
{ HTTP.method = "GET",
HTTP.redirectCount = 0,
HTTP.responseTimeout = HTTP.responseTimeoutNone,
HTTP.checkResponse = \_ _ -> pure (),
HTTP.requestHeaders = (hAccept, "text/event-stream") : hdrs
}
opened <- restore (openResponse mgr getReq)
case opened of
Left e -> pure (Left e)
Right resp -> do
let closeResp = HTTP.responseClose resp
r <- restore (handshake resp) `onException` closeResp
case r of
Left e -> closeResp >> pure (Left e)
Right (reader, messageEp) -> do
handlerRef <- newIORef (\_ _ _ -> pure ())
mux <- Mux.newMux (\rid m p -> readIORef handlerRef >>= \h -> h rid m p)
readerThread <- async (restore (readLoop reader mux) `finally` closeResp)
released <- newIORef False
let release = do
was <- atomicModifyIORef' released (True,)
if was then pure () else cancel readerThread
pure . Right $
Binding
{ shape = MultiplexedHttp,
endpointText = ep.rendered,
origin = ep.origin,
exchange = sseExchange mgr messageEp mux,
post = ssePost mgr messageEp,
openStream = Nothing,
terminate = Nothing,
release = release,
unsolicited = Just handlerRef
}
where
handshake resp
| statusOf resp == 401 || statusOf resp == 403 =
pure . Left $
(mcpError HttpFailure Answered "the server requires authorization for its event stream")
{ httpStatus = Just (statusOf resp),
challenge = TE.decodeUtf8Lenient <$> responseHeader "WWW-Authenticate" resp
}
| statusOf resp /= 200 || contentType resp /= Just "text/event-stream" =
pure . Left $
(mcpError HttpFailure Answered "the endpoint did not open an HTTP+SSE event stream")
{ httpStatus = Just (statusOf resp)
}
| otherwise = do
reader <- newEventReader lim.maxFrameBytes Nothing (HTTP.responseBody resp)
first <- timeout waitMicros (nextEvent reader)
pure $ case first of
Nothing -> Left (mcpError TimedOut NotSent "the event stream sent no endpoint event in time")
Just (Left e) -> Left e {delivery = NotSent}
Just (Right Nothing) -> Left (mcpError TransportFailure NotSent "the event stream ended before its endpoint event")
Just (Right (Just ev))
| ev.eventName /= "endpoint" -> Left (mcpError MalformedReply NotSent "the event stream did not begin with an endpoint event")
| otherwise -> (reader,) <$> resolveMessageEndpoint ep (TE.decodeUtf8Lenient ev.eventData)
-- | Resolve the advertised endpoint against the configured one and insist
-- on the same origin.
resolveMessageEndpoint :: HttpEndpoint -> Text -> Either McpError HttpEndpoint
resolveMessageEndpoint ep advertised = do
let base = HTTP.getUri ep.request
ref <- maybe (Left bad) Right (parseURIReference (Text.unpack (Text.strip advertised)))
let resolved = ref `relativeTo` base
target <- either (const (Left bad)) Right (parseEndpoint (Text.pack (show resolved)))
if sameOrigin target ep
then Right target
else Left (mcpError IncompatibleServer NotSent "the server advertised a message endpoint on a different origin; refusing to send to it")
where
bad = mcpError MalformedReply NotSent "the server advertised an unusable message endpoint"
readLoop :: EventReader -> Mux.Mux -> IO ()
readLoop reader mux = do
r <- try @SomeException loop
case r of
Left e -> Mux.failAll mux (bodyFailure e)
Right () -> pure ()
where
loop = do
ev <- nextEvent reader
case ev of
Left e -> Mux.failAll mux e
Right Nothing -> Mux.failAll mux (mcpError TransportFailure Uncertain "the server closed the event stream")
Right (Just e)
| e.eventName /= "" && e.eventName /= "message" -> loop
| otherwise -> case Aeson.eitherDecodeStrict e.eventData >>= either (Left . Text.unpack) Right . decodeMessage of
Left _ -> Mux.failAll mux (mcpError MalformedReply Uncertain "the server sent an unreadable message on the event stream")
Right msg -> Mux.dispatch mux (BS.length e.eventData) msg >> loop
messageRequest :: HttpEndpoint -> [Header] -> BS.ByteString -> HTTP.Request
messageRequest ep hdrs body =
ep.request
{ HTTP.method = "POST",
HTTP.redirectCount = 0,
HTTP.responseTimeout = HTTP.responseTimeoutNone,
HTTP.checkResponse = \_ _ -> pure (),
HTTP.requestHeaders = (hContentType, "application/json") : hdrs,
HTTP.requestBody = HTTP.RequestBodyBS body
}
ssePost :: HTTP.Manager -> HttpEndpoint -> [Header] -> BS.ByteString -> IO (Either McpError ())
ssePost mgr ep hdrs body =
withOpened mgr (messageRequest ep hdrs body) $ \resp -> do
_ <- readBounded 65536 (HTTP.responseBody resp)
let st = statusOf resp
pure $
if st >= 200 && st < 300
then Right ()
else
Left
( (mcpError HttpFailure Answered ("the message endpoint answered HTTP " <> Text.pack (show st)))
{ httpStatus = Just st,
challenge = TE.decodeUtf8Lenient <$> responseHeader "WWW-Authenticate" resp
}
)
sseExchange :: HTTP.Manager -> HttpEndpoint -> Mux.Mux -> WireLimits -> Exchange -> IO (Either McpError Reply)
sseExchange mgr ep mux _lim ex = do
reg <- Mux.register mux ex.requestId
case reg of
Left e -> pure (Left e)
Right waiter ->
( do
posted <- ssePost mgr ep ex.headers ex.body
case posted of
Left e -> pure (Left e)
Right () -> Mux.await waiter
)
`finally` Mux.unregister mux ex.requestId