baikai-mcp-0.1.0.0: src/Baikai/Mcp/Internal/Http.hs
-- | HTTP plumbing shared by the Streamable HTTP and HTTP+SSE bindings.
--
-- This module is internal. Its contents may change in any release.
module Baikai.Mcp.Internal.Http
( -- * Endpoints
HttpEndpoint (..),
parseEndpoint,
sameOrigin,
-- * Responses
withOpened,
openResponse,
openFailure,
bodyFailure,
readBounded,
contentType,
responseHeader,
statusOf,
rethrowAsync,
-- * Server-sent events
EventReader,
newEventReader,
nextEvent,
eventReaderBytes,
)
where
import Baikai.Mcp.Error
import Baikai.Mcp.Internal.Sse
import Baikai.Provider.Transport.Classify (classifyTransportException)
import Baikai.Url qualified as Url
import Control.Exception (SomeAsyncException, SomeException, fromException, mask, onException, throwIO, try)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as BS8
import Data.IORef
import Data.Text (Text)
import Data.Text qualified as Text
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Types (HeaderName, hContentType, statusCode)
-- | A validated MCP endpoint.
data HttpEndpoint = HttpEndpoint
{ request :: !HTTP.Request,
-- | Scheme, host and path, without credentials or query.
rendered :: !Text,
-- | @scheme://host:port@.
origin :: !Text,
scheme :: !Text,
host :: !Text,
port :: !Int
}
-- | Accept an @http@ or @https@ URL without userinfo. The host is read by
-- "Baikai.Url", the one host parser every credential decision uses.
parseEndpoint :: Text -> Either Text HttpEndpoint
parseEndpoint raw = do
parts <- maybe (Left "the MCP endpoint has no host") Right (Url.parseUrl raw)
sch <- case Url.scheme parts of
Just s | s == "http" || s == "https" -> Right s
Just s -> Left ("the MCP endpoint uses the unsupported scheme " <> s)
Nothing -> Left "the MCP endpoint has no scheme; start it with https:// or http://"
if Url.hasUserInfo parts
then Left "the MCP endpoint must not embed credentials; supply them through the request hook"
else Right ()
req <- either (const (Left "the MCP endpoint is not a valid URL")) Right (HTTP.parseRequest @(Either SomeException) (Text.unpack (Text.strip raw)))
let p = case Url.port parts of
Just n -> n
Nothing -> if sch == "https" then 443 else 80
h = Url.host parts
Right
HttpEndpoint
{ request = req,
rendered = Url.renderEndpoint parts,
origin = sch <> "://" <> h <> ":" <> Text.pack (show p),
scheme = sch,
host = h,
port = p
}
sameOrigin :: HttpEndpoint -> HttpEndpoint -> Bool
sameOrigin a b = a.origin == b.origin
-- | Re-throw asynchronous exceptions (cancellation, timeouts) untouched.
rethrowAsync :: SomeException -> IO ()
rethrowAsync e = case fromException @SomeAsyncException e of
Just _ -> throwIO e
Nothing -> pure ()
-- | Open a response and always close it. A failure to open is classified
-- by phase; a synchronous failure while the continuation reads the body
-- is a lost reply.
withOpened :: HTTP.Manager -> HTTP.Request -> (HTTP.Response HTTP.BodyReader -> IO (Either McpError a)) -> IO (Either McpError a)
withOpened mgr req k = mask $ \restore -> do
r <- try (restore (HTTP.responseOpen req mgr))
case r of
Left e -> rethrowAsync e >> pure (Left (openFailure e))
Right resp -> do
x <- try (restore (k resp)) `onException` HTTP.responseClose resp
HTTP.responseClose resp
case x of
Left e -> rethrowAsync e >> pure (Left (bodyFailure e))
Right v -> pure v
-- | Open a response whose lifetime the caller manages.
openResponse :: HTTP.Manager -> HTTP.Request -> IO (Either McpError (HTTP.Response HTTP.BodyReader))
openResponse mgr req = do
r <- try (HTTP.responseOpen req mgr)
case r of
Left e -> rethrowAsync e >> pure (Left (openFailure e))
Right resp -> pure (Right resp)
-- | A failure before a response arrived. Only failures that certainly
-- precede transmission are 'NotSent'.
openFailure :: SomeException -> McpError
openFailure e =
(mcpError TransportFailure delivery ("could not complete the HTTP exchange: " <> describe e))
{ transport = classifyTransportException e
}
where
delivery = case fromException e of
Just (HTTP.InvalidUrlException _ _) -> NotSent
Just (HTTP.HttpExceptionRequest _ c) -> case c of
HTTP.ConnectionFailure _ -> NotSent
HTTP.ConnectionTimeout -> NotSent
HTTP.InvalidDestinationHost _ -> NotSent
HTTP.InvalidRequestHeader _ -> NotSent
HTTP.ProxyConnectException {} -> NotSent
HTTP.TlsNotSupported -> NotSent
_ -> Uncertain
Nothing -> Uncertain
-- | A failure while reading a response body.
bodyFailure :: SomeException -> McpError
bodyFailure e =
(mcpError TransportFailure Uncertain ("the response was interrupted: " <> describe e))
{ transport = classifyTransportException e
}
describe :: SomeException -> Text
describe e = case fromException e of
Just (HTTP.HttpExceptionRequest _ c) -> Text.pack (takeWhile (/= ' ') (show c))
Just (HTTP.InvalidUrlException _ _) -> "invalid URL"
Nothing -> Text.take 120 (Text.pack (takeWhile (/= '\n') (show e)))
-- | Read a whole body, refusing more than the limit. 'Left' carries the
-- number of bytes read when the limit was reached.
readBounded :: Int -> HTTP.BodyReader -> IO (Either Int ByteString)
readBounded limit br = go 0 []
where
go n acc = do
chunk <- HTTP.brRead br
if BS.null chunk
then pure (Right (BS.concat (reverse acc)))
else
let n' = n + BS.length chunk
in if n' > limit then pure (Left n') else go n' (chunk : acc)
-- | The media type of a response, lower-cased, without parameters.
contentType :: HTTP.Response a -> Maybe ByteString
contentType resp =
BS8.map toLowerAscii . BS8.strip . BS8.takeWhile (/= ';') <$> lookup hContentType (HTTP.responseHeaders resp)
where
toLowerAscii c = if c >= 'A' && c <= 'Z' then toEnum (fromEnum c + 32) else c
responseHeader :: HeaderName -> HTTP.Response a -> Maybe ByteString
responseHeader n resp = lookup n (HTTP.responseHeaders resp)
statusOf :: HTTP.Response a -> Int
statusOf = statusCode . HTTP.responseStatus
-- | Reads events from a response body under a frame limit and, optionally,
-- a total byte limit.
data EventReader = EventReader
{ body :: !HTTP.BodyReader,
parser :: !(IORef SseParser),
pending :: !(IORef [SseEvent]),
total :: !(IORef Int),
maxTotal :: !(Maybe Int),
finished :: !(IORef Bool)
}
newEventReader :: Int -> Maybe Int -> HTTP.BodyReader -> IO EventReader
newEventReader frame maxT br = do
p <- newIORef (newSseParser frame)
q <- newIORef []
t <- newIORef 0
f <- newIORef False
pure EventReader {body = br, parser = p, pending = q, total = t, maxTotal = maxT, finished = f}
eventReaderBytes :: EventReader -> IO Int
eventReaderBytes r = readIORef r.total
-- | The next event; @Right Nothing@ at end of stream.
nextEvent :: EventReader -> IO (Either McpError (Maybe SseEvent))
nextEvent r = do
queued <- readIORef r.pending
case queued of
(e : es) -> writeIORef r.pending es >> pure (Right (Just e))
[] -> do
done <- readIORef r.finished
if done
then pure (Right Nothing)
else do
chunk <- HTTP.brRead r.body
if BS.null chunk
then writeIORef r.finished True >> pure (Right Nothing)
else do
n <- atomicModifyIORef' r.total (\t -> let t' = t + BS.length chunk in (t', t'))
case r.maxTotal of
Just m | n > m -> do
writeIORef r.finished True
pure (Left (mcpError LimitExceeded Uncertain "the response exceeded the configured size limit"))
_ -> do
st <- readIORef r.parser
case feedSse st chunk of
Left why -> do
writeIORef r.finished True
pure (Left (mcpError LimitExceeded Uncertain (Text.pack why)))
Right (st', evs) -> do
writeIORef r.parser st'
writeIORef r.pending evs
nextEvent r