baikai-mcp-0.1.0.0: src/Baikai/Mcp/Transport.hs
-- | Streamable HTTP framing: routing headers, the Base64 header sentinel,
-- parameter mirrors and the request-scoped HTTP binding.
--
-- Every modern request is its own @POST@. The reply is one JSON object or
-- a Server-Sent Events stream scoped to that request; notifications on the
-- stream precede the correlated response. Closing the response cancels the
-- request, so no @notifications/cancelled@ is ever sent over HTTP. The
-- binding never follows a redirect: the endpoint the host authorized is the
-- only one that receives its credentials.
module Baikai.Mcp.Transport
( -- * Header values
encodeHeaderValue,
decodeHeaderValue,
-- * Routing headers
hProtocolVersion,
hMcpMethod,
hMcpName,
hSessionId,
isProtocolControlledHeader,
routingName,
-- * Parameter mirrors
ParamHeader,
paramHeader,
paramHeaderField,
paramHeaderValue,
validParamName,
jsSafeIntegerBound,
-- * The Streamable HTTP binding
streamableHttpBinding,
)
where
import Baikai.Mcp.Error
import Baikai.Mcp.Internal.Binding
import Baikai.Mcp.Internal.Http
import Baikai.Mcp.Internal.Sse (SseEvent (..))
import Baikai.Mcp.Protocol
import Control.Exception (SomeException, try)
import Data.Aeson (Value (..))
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Base64 qualified as B64
import Data.ByteString.Char8 qualified as BS8
import Data.CaseInsensitive qualified as CI
import Data.Char (isAlphaNum, isAscii, ord)
import Data.IORef
import Data.Scientific (floatingOrInteger)
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, HeaderName, hAccept, hContentType)
-- ---------------------------------------------------------------------------
-- Header values
sentinelPrefix, sentinelSuffix :: Text
sentinelPrefix = "=?base64?"
sentinelSuffix = "?="
-- | Encode a value for an @Mcp-Name@ or @Mcp-Param-*@ header. A value that
-- is not plain visible ASCII, has leading or trailing whitespace, or
-- already looks like the sentinel is sent as
-- @=?base64?{Base64 of UTF-8}?=@.
encodeHeaderValue :: Text -> ByteString
encodeHeaderValue t
| plain = TE.encodeUtf8 t
| otherwise = TE.encodeUtf8 sentinelPrefix <> B64.encode (TE.encodeUtf8 t) <> TE.encodeUtf8 sentinelSuffix
where
plain =
Text.all safeChar t
&& not (edgeSpace (Text.take 1 t))
&& not (edgeSpace (Text.takeEnd 1 t))
&& not (Text.isPrefixOf sentinelPrefix t && Text.isSuffixOf sentinelSuffix t)
safeChar c = isAscii c && ((ord c >= 0x20 && ord c <= 0x7E) || c == '\t')
edgeSpace s = s == " " || s == "\t"
-- | The inverse of 'encodeHeaderValue', as a server validating mirrors
-- would apply it.
decodeHeaderValue :: ByteString -> Either Text Text
decodeHeaderValue raw =
case TE.decodeUtf8' raw of
Left _ -> Left "header value is not UTF-8"
Right t
| Text.isPrefixOf sentinelPrefix t,
Text.isSuffixOf sentinelSuffix t,
Text.length t >= Text.length sentinelPrefix + Text.length sentinelSuffix ->
let inner = Text.dropEnd (Text.length sentinelSuffix) (Text.drop (Text.length sentinelPrefix) t)
in case B64.decode (TE.encodeUtf8 inner) of
Left _ -> Left "invalid Base64 in a sentinel-encoded header"
Right bytes -> either (const (Left "sentinel-encoded header is not UTF-8")) Right (TE.decodeUtf8' bytes)
| otherwise -> Right t
-- ---------------------------------------------------------------------------
-- Routing headers
hProtocolVersion, hMcpMethod, hMcpName, hSessionId :: HeaderName
hProtocolVersion = "MCP-Protocol-Version"
hMcpMethod = "Mcp-Method"
hMcpName = "Mcp-Name"
hSessionId = "Mcp-Session-Id"
-- | Headers this package sets itself. A request hook may not supply them.
isProtocolControlledHeader :: HeaderName -> Bool
isProtocolControlledHeader n =
n
`elem` [ hProtocolVersion,
hMcpMethod,
hMcpName,
hSessionId,
hContentType,
hAccept,
"Content-Length",
"Transfer-Encoding",
"Host",
"Connection",
"Last-Event-ID"
]
|| BS.isPrefixOf "mcp-" (CI.foldedCase n)
-- | The value mirrored into @Mcp-Name@: the tool or prompt name, or the
-- resource URI, for the three methods that require it.
routingName :: Text -> KeyMap.KeyMap Value -> Maybe Text
routingName method params = case method of
"tools/call" -> str "name"
"prompts/get" -> str "name"
"resources/read" -> str "uri"
_ -> Nothing
where
str k = case KeyMap.lookup k params of
Just (String s) -> Just s
_ -> Nothing
-- ---------------------------------------------------------------------------
-- Parameter mirrors
-- | A validated @Mcp-Param-{Name}@ header. Built only by 'paramHeader'.
data ParamHeader = ParamHeader {field :: !HeaderName, value :: !ByteString}
deriving stock (Eq, Show)
paramHeaderField :: ParamHeader -> HeaderName
paramHeaderField p = p.field
paramHeaderValue :: ParamHeader -> ByteString
paramHeaderValue p = p.value
-- | Whether an @x-mcp-header@ value is a valid HTTP field-name token.
validParamName :: Text -> Bool
validParamName t = not (Text.null t) && Text.all tchar t
where
tchar c = isAscii c && (isAlphaNum c || c `elem` ("!#$%&'*+-.^_`|~" :: String))
-- | The largest integer a mirror may carry: 2^53 - 1.
jsSafeIntegerBound :: Integer
jsSafeIntegerBound = 2 ^ (53 :: Int) - 1
-- | Mirror one argument value. 'Nothing' for an absent or null value, which
-- must not be mirrored. Strings, booleans and safe integers are encoded;
-- any other value is refused rather than sent unmirrored.
paramHeader :: Text -> Maybe Value -> Either Text (Maybe ParamHeader)
paramHeader nm mv
| not (validParamName nm) = Left ("x-mcp-header name " <> clipText 64 nm <> " is not a valid HTTP token")
| otherwise = case mv of
Nothing -> Right Nothing
Just Null -> Right Nothing
Just (String s) -> mk (encodeHeaderValue s)
Just (Bool b) -> mk (if b then "true" else "false")
Just (Number n) -> case floatingOrInteger @Double n of
Right i
| abs i <= jsSafeIntegerBound -> mk (BS8.pack (show i))
| otherwise -> Left ("the value mirrored to " <> nm <> " is outside the safe integer range")
Left _ -> Left ("the value mirrored to " <> nm <> " is not an integer")
Just _ -> Left ("the value mirrored to " <> nm <> " is not a string, integer or boolean")
where
mk v = Right (Just ParamHeader {field = CI.mk ("Mcp-Param-" <> TE.encodeUtf8 nm), value = v})
-- ---------------------------------------------------------------------------
-- The binding
-- | The request-scoped Streamable HTTP binding, for both the modern
-- revision and handshake-era revisions (which add a session header).
streamableHttpBinding :: HTTP.Manager -> HttpEndpoint -> Binding
streamableHttpBinding mgr ep =
Binding
{ shape = RequestScopedHttp,
endpointText = ep.rendered,
origin = ep.origin,
exchange = httpExchange mgr ep,
post = httpPost mgr ep,
openStream = Just (httpOpenStream mgr ep),
terminate = Just (httpDelete mgr ep),
release = pure (),
unsolicited = Nothing
}
baseRequest :: HttpEndpoint -> HTTP.Request
baseRequest ep =
ep.request
{ HTTP.redirectCount = 0,
HTTP.responseTimeout = HTTP.responseTimeoutNone,
HTTP.checkResponse = \_ _ -> pure ()
}
postRequest :: HttpEndpoint -> [Header] -> BS.ByteString -> HTTP.Request
postRequest ep hdrs body =
(baseRequest ep)
{ HTTP.method = "POST",
HTTP.requestHeaders =
[ (hContentType, "application/json"),
(hAccept, "application/json, text/event-stream")
]
<> hdrs,
HTTP.requestBody = HTTP.RequestBodyBS body
}
httpExchange :: HTTP.Manager -> HttpEndpoint -> WireLimits -> Exchange -> IO (Either McpError Reply)
httpExchange mgr ep lim ex =
withOpened mgr (postRequest ep ex.headers ex.body) $ \resp ->
readReply lim ex resp
-- | Interpret the response to one request.
readReply :: WireLimits -> Exchange -> HTTP.Response HTTP.BodyReader -> IO (Either McpError Reply)
readReply lim ex resp
| st == 401 || st == 403 = do
_ <- readBounded 65536 (HTTP.responseBody resp)
pure . Left $
(mcpError HttpFailure Answered (if st == 401 then "the server requires authorization" else "the server refused the credentials"))
{ httpStatus = Just st,
challenge = TE.decodeUtf8Lenient <$> responseHeader "WWW-Authenticate" resp
}
| st >= 300 && st < 400 = pure . Left $ (mcpError HttpFailure Answered "the server answered with a redirect, which is not followed") {httpStatus = Just st}
| st >= 200 && st < 300, contentType resp == Just "text/event-stream" = readStream
| st >= 200 && st < 300 = do
b <- readBounded lim.maxResponseBytes (HTTP.responseBody resp)
case b of
Left _ -> pure (Left (mcpError LimitExceeded Uncertain "the response exceeded the configured size limit"))
Right bytes
| BS.null bytes -> pure (Left ((mcpError MalformedReply Uncertain "the server returned no response to a request") {httpStatus = Just st}))
| otherwise -> pure (decodeReply bytes)
| otherwise = do
b <- readBounded (min lim.maxResponseBytes 1048576) (HTTP.responseBody resp)
pure $ case b of
Right bytes
| Right (IncomingResponse rid (Left e)) <- decodeFrame bytes,
maybe True (== ex.requestId) rid ->
Right Reply {outcome = Left e, bytes = BS.length bytes, status = Just st, sessionId = session}
_ -> Left ((mcpError HttpFailure Answered ("the server answered HTTP " <> Text.pack (show st))) {httpStatus = Just st})
where
st = statusOf resp
session = responseHeader hSessionId resp
decodeReply bytes = case decodeFrame bytes of
Left why -> Left ((mcpError MalformedReply Uncertain why) {httpStatus = Just st})
Right (IncomingResponse rid r)
| rid == Just ex.requestId || (rid == Nothing && isLeft' r) ->
Right Reply {outcome = r, bytes = BS.length bytes, status = Just st, sessionId = session}
| otherwise -> Left ((mcpError MalformedReply Uncertain "the response carries an unrelated request id") {httpStatus = Just st})
Right _ -> Left ((mcpError MalformedReply Uncertain "the server returned a message that is not a response") {httpStatus = Just st})
readStream = do
reader <- newEventReader lim.maxFrameBytes (Just lim.maxResponseBytes) (HTTP.responseBody resp)
let loop = do
ev <- nextEvent reader
case ev of
Left e -> pure (Left e {httpStatus = Just st})
Right Nothing -> pure (Left ((mcpError TransportFailure Uncertain "the response stream ended before the reply") {httpStatus = Just st}))
Right (Just e)
| e.eventName /= "" && e.eventName /= "message" -> loop
| otherwise -> case decodeFrame e.eventData of
Left why -> pure (Left ((mcpError MalformedReply Uncertain why) {httpStatus = Just st}))
Right (IncomingNotification m p) -> ex.onNotification m p >> loop
Right (IncomingRequest rid m p) -> ex.onServerRequest rid m p >> loop
Right (IncomingResponse rid r)
| rid == Just ex.requestId -> do
n <- eventReaderBytes reader
pure (Right Reply {outcome = r, bytes = n, status = Just st, sessionId = session})
| otherwise -> pure (Left ((mcpError MalformedReply Uncertain "the stream carried a response to an unrelated request id") {httpStatus = Just st}))
loop
isLeft' = either (const True) (const False)
decodeFrame :: ByteString -> Either Text IncomingMessage
decodeFrame bytes = case Aeson.eitherDecodeStrict bytes of
Left _ -> Left "the server sent a message that is not valid JSON"
Right v -> decodeMessage v
httpPost :: HTTP.Manager -> HttpEndpoint -> [Header] -> BS.ByteString -> IO (Either McpError ())
httpPost mgr ep hdrs body =
withOpened mgr (postRequest 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 server answered HTTP " <> Text.pack (show st) <> " to a notification")) {httpStatus = Just st})
-- | Open a long-lived response stream for @subscriptions/listen@. The
-- caller owns the stream and must 'close' it.
httpOpenStream :: HTTP.Manager -> HttpEndpoint -> WireLimits -> Exchange -> IO (Either McpError MessageStream)
httpOpenStream mgr ep lim ex = do
opened <- openResponse mgr (postRequest ep ex.headers ex.body)
case opened of
Left e -> pure (Left e)
Right resp
| statusOf resp >= 200 && statusOf resp < 300 && contentType resp == Just "text/event-stream" -> do
reader <- newEventReader lim.maxFrameBytes Nothing (HTTP.responseBody resp)
closed <- newIORef False
let close = do
was <- atomicModifyIORef' closed (True,)
if was then pure () else HTTP.responseClose resp
next = do
isClosed <- readIORef closed
if isClosed
then pure (StreamEnded Nothing)
else do
r <- tryRead (nextEvent reader)
case r of
Left e -> pure (StreamEnded (Just e))
Right (Left e) -> pure (StreamEnded (Just e))
Right (Right Nothing) -> pure (StreamEnded Nothing)
Right (Right (Just e))
| e.eventName /= "" && e.eventName /= "message" -> next
| otherwise -> case decodeFrame e.eventData of
Left why -> pure (StreamEnded (Just (mcpError MalformedReply Uncertain why)))
Right m -> pure (StreamMessage m)
pure (Right MessageStream {next = next, close = close})
| otherwise -> do
r <- readReply lim ex resp
HTTP.responseClose resp
case r of
Left e -> pure (Left e)
Right reply -> do
delivered <- newIORef False
let next = do
was <- atomicModifyIORef' delivered (True,)
pure $
if was
then StreamEnded Nothing
else StreamMessage (IncomingResponse (Just ex.requestId) reply.outcome)
pure (Right MessageStream {next = next, close = pure ()})
where
tryRead act = do
r <- try @SomeException act
case r of
Left e -> rethrowAsync e >> pure (Left (bodyFailure e))
Right v -> pure (Right v)
httpDelete :: HTTP.Manager -> HttpEndpoint -> [Header] -> IO ()
httpDelete mgr ep hdrs = do
_ <-
withOpened mgr ((baseRequest ep) {HTTP.method = "DELETE", HTTP.requestHeaders = hdrs}) $ \resp -> do
_ <- readBounded 65536 (HTTP.responseBody resp)
pure (Right ())
pure ()