baikai-mcp-0.1.0.0: src/Baikai/Mcp/Protocol.hs
-- | The Model Context Protocol wire vocabulary shared by every feature module.
--
-- This module is pure. It owns the JSON-RPC 2.0 envelope, request
-- identifiers, protocol versions and eras, the per-request @_meta@ fields,
-- result-type discrimination (including interim @input_required@ results),
-- cache hints, opaque pagination cursors and the bounded drain over pages.
-- It does no IO except in 'drainPages', which only sequences a page fetcher
-- the caller supplies.
--
-- Target revision: MCP @2026-07-28@. Earlier revisions are named
-- /legacy/: they open with an @initialize@ handshake and their results carry
-- no @resultType@.
module Baikai.Mcp.Protocol
( -- * Protocol versions and eras
ProtocolVersion (..),
latestModernVersion,
modernVersions,
legacyStreamableVersions,
httpSseVersions,
legacyVersions,
Era (..),
eraVersion,
isModern,
-- * Identities and capabilities
Implementation (..),
implementation,
ServerCapabilities (..),
capabilityPresent,
ServerDescription (..),
-- * Request identifiers and envelopes
RequestId (..),
renderRequestId,
encodeRequest,
encodeNotification,
encodeResultResponse,
encodeErrorResponse,
IncomingMessage (..),
decodeMessage,
-- * Request metadata
requestMeta,
withRequestMeta,
metaProtocolVersion,
metaClientCapabilities,
metaClientInfo,
metaServerInfo,
metaSubscriptionId,
-- * Errors reported by the peer
RpcError (..),
rpcError,
parseError,
invalidRequestCode,
methodNotFound,
invalidParams,
internalError,
headerMismatch,
missingRequiredClientCapability,
unsupportedProtocolVersion,
legacyResourceNotFound,
isModernErrorCode,
unsupportedVersionsOffered,
-- * Result types
ResultKind (..),
decodeResultKind,
interimMethods,
supportsInterim,
InputRequired (..),
-- * Cache hints
CacheScope (..),
CacheHint (..),
cacheableMethods,
decodeCacheHint,
-- * Pagination
Cursor,
cursorFromText,
cursorToText,
Page (..),
DrainLimits (..),
defaultDrainLimits,
DrainFailure (..),
drainPages,
-- * Subscriptions
SubscriptionFilter (..),
emptySubscriptionFilter,
subscriptionNotificationMethods,
-- * Discovery and handshake results
decodeDiscoverResult,
decodeInitializeResult,
clipText,
)
where
import Control.Monad (unless, when)
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), object, withObject, (.:), (.:?), (.=))
import Data.Aeson qualified as Aeson
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap (KeyMap)
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object, Parser, parseEither)
import Data.ByteString.Lazy qualified as LBS
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, isNothing)
import Data.Scientific (floatingOrInteger)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import GHC.Generics (Generic)
-- ---------------------------------------------------------------------------
-- Versions and eras
-- | A protocol revision name such as @2026-07-28@.
newtype ProtocolVersion = ProtocolVersion {versionText :: Text}
deriving stock (Eq, Ord, Show, Generic)
deriving newtype (ToJSON, FromJSON)
-- | The revision this client targets.
latestModernVersion :: ProtocolVersion
latestModernVersion = ProtocolVersion "2026-07-28"
-- | Modern revisions this client implements, most preferred first. Modern
-- revisions carry version and capabilities on every request.
modernVersions :: [ProtocolVersion]
modernVersions = [latestModernVersion]
-- | Handshake-era revisions spoken over Streamable HTTP, most preferred first.
legacyStreamableVersions :: [ProtocolVersion]
legacyStreamableVersions = map ProtocolVersion ["2025-11-25", "2025-06-18", "2025-03-26"]
-- | Revisions spoken over the deprecated two-endpoint HTTP+SSE transport.
httpSseVersions :: [ProtocolVersion]
httpSseVersions = [ProtocolVersion "2024-11-05"]
-- | Every handshake-era revision this client accepts from @initialize@.
legacyVersions :: [ProtocolVersion]
legacyVersions = legacyStreamableVersions <> httpSseVersions
-- | Which generation of the protocol a connection speaks. The era is a
-- property of the server and is fixed for the life of a connection.
data Era
= -- | Per-request metadata, no handshake, no session.
Modern ProtocolVersion
| -- | @initialize@ handshake at the negotiated version.
Legacy ProtocolVersion
deriving stock (Eq, Show, Generic)
eraVersion :: Era -> ProtocolVersion
eraVersion = \case
Modern v -> v
Legacy v -> v
isModern :: Era -> Bool
isModern = \case
Modern _ -> True
Legacy _ -> False
-- ---------------------------------------------------------------------------
-- Identities
-- | A self-reported implementation identity (@clientInfo@ / @serverInfo@).
-- Display and logging only; never a basis for security decisions.
data Implementation = Implementation
{ name :: !Text,
version :: !Text,
title :: !(Maybe Text)
}
deriving stock (Eq, Show, Generic)
implementation :: Text -> Text -> Implementation
implementation n v = Implementation {name = n, version = v, title = Nothing}
instance ToJSON Implementation where
toJSON i =
object $
["name" .= i.name, "version" .= i.version]
<> maybe [] (\t -> ["title" .= t]) i.title
instance FromJSON Implementation where
parseJSON = withObject "Implementation" $ \o ->
Implementation <$> o .: "name" <*> o .: "version" <*> o .:? "title"
-- | Server capabilities, kept as the raw object the server sent so that
-- capabilities this client does not model are not lost.
newtype ServerCapabilities = ServerCapabilities {raw :: Object}
deriving stock (Eq, Show, Generic)
instance FromJSON ServerCapabilities where
parseJSON = withObject "ServerCapabilities" (pure . ServerCapabilities)
-- | Whether the server advertised a top-level capability such as @tools@.
capabilityPresent :: Text -> ServerCapabilities -> Bool
capabilityPresent k caps = case KeyMap.lookup (Key.fromText k) caps.raw of
Nothing -> False
Just Null -> False
Just _ -> True
-- | What a server said about itself when the connection was opened, from
-- @server/discover@ (modern) or @initialize@ (legacy).
data ServerDescription = ServerDescription
{ era :: !Era,
supportedVersions :: ![ProtocolVersion],
capabilities :: !ServerCapabilities,
serverInfo :: !(Maybe Implementation),
instructions :: !(Maybe Text),
cache :: !(Maybe CacheHint)
}
deriving stock (Eq, Show, Generic)
-- ---------------------------------------------------------------------------
-- Request identifiers and envelopes
-- | A JSON-RPC request identifier. Never null.
data RequestId
= RequestIdNumber !Integer
| RequestIdText !Text
deriving stock (Eq, Ord, Show, Generic)
instance ToJSON RequestId where
toJSON = \case
RequestIdNumber n -> toJSON n
RequestIdText t -> toJSON t
instance FromJSON RequestId where
parseJSON = \case
String t -> pure (RequestIdText t)
Number n -> case floatingOrInteger @Double n of
Right i -> pure (RequestIdNumber i)
Left _ -> fail "request id must be an integer or a string"
_ -> fail "request id must be an integer or a string"
renderRequestId :: RequestId -> Text
renderRequestId = \case
RequestIdNumber n -> Text.pack (show n)
RequestIdText t -> clipText 64 t
-- | A request envelope. @params@ is omitted when empty.
encodeRequest :: RequestId -> Text -> Object -> Value
encodeRequest rid method params =
Object . KeyMap.fromList $
[("jsonrpc", String "2.0"), ("id", toJSON rid), ("method", String method)]
<> [("params", Object params) | not (KeyMap.null params)]
-- | A notification envelope (no identifier).
encodeNotification :: Text -> Object -> Value
encodeNotification method params =
Object . KeyMap.fromList $
[("jsonrpc", String "2.0"), ("method", String method)]
<> [("params", Object params) | not (KeyMap.null params)]
-- | A response to a request the server sent (legacy profiles only).
encodeResultResponse :: RequestId -> Object -> Value
encodeResultResponse rid result =
object ["jsonrpc" .= ("2.0" :: Text), "id" .= rid, "result" .= result]
encodeErrorResponse :: RequestId -> RpcError -> Value
encodeErrorResponse rid err =
object ["jsonrpc" .= ("2.0" :: Text), "id" .= rid, "error" .= err]
-- | A message received from a server.
data IncomingMessage
= -- | A response. The identifier is absent only on an error response
-- to a request the server could not read.
IncomingResponse !(Maybe RequestId) !(Either RpcError Object)
| IncomingNotification !Text !Object
| -- | A server-initiated request. Only legacy profiles permit these.
IncomingRequest !RequestId !Text !Object
deriving stock (Eq, Show, Generic)
-- | Decode one JSON-RPC 2.0 message. Rejects a wrong or missing @jsonrpc@
-- member, a frame with both @result@ and @error@, a null request
-- identifier and a non-object @params@ or @result@.
decodeMessage :: Value -> Either Text IncomingMessage
decodeMessage = first' . parseEither parser
where
first' = either (Left . clipText 200 . Text.pack) Right
parser = withObject "JSON-RPC message" $ \o -> do
v <- o .:? "jsonrpc"
unless (v == Just ("2.0" :: Text)) (fail "jsonrpc member must be \"2.0\"")
let has k = KeyMap.member k o
case (has "method", has "result", has "error") of
(True, False, False) -> do
method <- o .: "method"
params <- fromMaybe KeyMap.empty <$> o .:? "params"
case KeyMap.lookup "id" o of
Nothing -> pure (IncomingNotification method params)
Just Null -> fail "request id must not be null"
Just idv -> do
rid <- parseJSON idv
pure (IncomingRequest rid method params)
(False, True, False) -> do
rid <- responseId o
case rid of
Nothing -> fail "a result response must carry an id"
Just _ -> pure ()
r <- o .: "result"
pure (IncomingResponse rid (Right r))
(False, False, True) -> do
rid <- responseId o
e <- o .: "error"
pure (IncomingResponse rid (Left e))
(False, True, True) -> fail "a response must not carry both result and error"
_ -> fail "not a JSON-RPC request, notification or response"
responseId o = case KeyMap.lookup "id" o of
Nothing -> pure Nothing
Just Null -> pure Nothing
Just idv -> Just <$> parseJSON idv
-- ---------------------------------------------------------------------------
-- Request metadata
metaProtocolVersion, metaClientCapabilities, metaClientInfo, metaServerInfo, metaSubscriptionId :: Aeson.Key
metaProtocolVersion = "io.modelcontextprotocol/protocolVersion"
metaClientCapabilities = "io.modelcontextprotocol/clientCapabilities"
metaClientInfo = "io.modelcontextprotocol/clientInfo"
metaServerInfo = "io.modelcontextprotocol/serverInfo"
metaSubscriptionId = "io.modelcontextprotocol/subscriptionId"
-- | The per-request protocol fields of a modern request. The client
-- advertises no capabilities: it answers no sampling, elicitation or roots
-- requests.
requestMeta :: ProtocolVersion -> Maybe Implementation -> Object
requestMeta v info =
KeyMap.fromList $
[ (metaProtocolVersion, toJSON v),
(metaClientCapabilities, Object KeyMap.empty)
]
<> maybe [] (\i -> [(metaClientInfo, toJSON i)]) info
-- | Merge the protocol fields into @params._meta@. Protocol fields win over
-- any same-named key the caller supplied.
withRequestMeta :: Object -> Object -> Object
withRequestMeta meta params =
let existing = case KeyMap.lookup "_meta" params of
Just (Object m) -> m
_ -> KeyMap.empty
in KeyMap.insert "_meta" (Object (meta <> existing)) params
-- ---------------------------------------------------------------------------
-- Peer errors
-- | A JSON-RPC error object reported by the server. The message is clipped
-- and oversized @data@ is dropped on decoding, so the value is safe to
-- render.
data RpcError = RpcError
{ code :: !Int,
message :: !Text,
errorData :: !(Maybe Value)
}
deriving stock (Eq, Show, Generic)
rpcError :: Int -> Text -> RpcError
rpcError c m = RpcError {code = c, message = m, errorData = Nothing}
instance FromJSON RpcError where
parseJSON = withObject "JSON-RPC error" $ \o -> do
c <- o .: "code"
m <- fromMaybe "" <$> o .:? "message"
d <- o .:? "data"
let bounded = case d of
Just v | LBS.length (Aeson.encode v) <= 8192 -> Just v
_ -> Nothing
pure RpcError {code = c, message = clipText 512 m, errorData = bounded}
instance ToJSON RpcError where
toJSON e =
object $
["code" .= e.code, "message" .= e.message]
<> maybe [] (\d -> ["data" .= d]) e.errorData
parseError, invalidRequestCode, methodNotFound, invalidParams, internalError :: Int
parseError = -32700
invalidRequestCode = -32600
methodNotFound = -32601
invalidParams = -32602
internalError = -32603
-- | Modern error codes defined by the 2026-07-28 revision.
headerMismatch, missingRequiredClientCapability, unsupportedProtocolVersion :: Int
headerMismatch = -32020
missingRequiredClientCapability = -32021
unsupportedProtocolVersion = -32022
-- | Resource-not-found code used by 2025-11-25 and earlier.
legacyResourceNotFound :: Int
legacyResourceNotFound = -32002
-- | Whether an error code identifies a modern server.
isModernErrorCode :: Int -> Bool
isModernErrorCode c = c `elem` [headerMismatch, missingRequiredClientCapability, unsupportedProtocolVersion]
-- | The versions an @UnsupportedProtocolVersionError@ lists, when the
-- error is one and its data is well formed.
unsupportedVersionsOffered :: RpcError -> Maybe [ProtocolVersion]
unsupportedVersionsOffered e
| e.code /= unsupportedProtocolVersion = Nothing
| otherwise = case e.errorData of
Just (Object d) | Just v <- KeyMap.lookup "supported" d -> either (const Nothing) Just (parseEither parseJSON v)
_ -> Nothing
-- ---------------------------------------------------------------------------
-- Result types
-- | The two result types defined by the core protocol.
data ResultKind
= ResultComplete
| ResultInputRequired !InputRequired
deriving stock (Eq, Show, Generic)
-- | An interim result: the server needs more before it can finish.
data InputRequired = InputRequired
{ -- | Requests the server wants the client to answer (sampling,
-- elicitation, roots), keyed by server-assigned identifiers. This
-- client advertises none of those capabilities and never answers them.
inputRequests :: !(Maybe (Map Text Value)),
-- | Opaque state to echo byte for byte on a retry.
requestState :: !(Maybe Text)
}
deriving stock (Eq, Show, Generic)
-- | Methods on which a server may return an interim result.
interimMethods :: [Text]
interimMethods = ["tools/call", "resources/read", "prompts/get"]
supportsInterim :: Text -> Bool
supportsInterim m = m `elem` interimMethods
-- | Discriminate a result object. An absent @resultType@ is @complete@
-- (earlier revisions omit it); an unknown one is invalid; an interim
-- result must carry @inputRequests@, @requestState@ or both, and is only
-- valid for 'interimMethods'.
decodeResultKind :: Text -> Object -> Either Text ResultKind
decodeResultKind method o = case KeyMap.lookup "resultType" o of
Nothing -> Right ResultComplete
Just (String "complete") -> Right ResultComplete
Just (String "input_required")
| not (supportsInterim method) ->
Left ("the server returned an input_required result for " <> method <> ", which does not allow one")
| otherwise -> do
reqs <- case KeyMap.lookup "inputRequests" o of
Nothing -> Right Nothing
Just Null -> Right Nothing
Just (Object m)
| KeyMap.null m -> Right Nothing
| otherwise -> Right (Just (Map.fromList [(Key.toText k, v) | (k, v) <- KeyMap.toList m]))
Just _ -> Left "inputRequests must be an object"
st <- case KeyMap.lookup "requestState" o of
Nothing -> Right Nothing
Just Null -> Right Nothing
Just (String s) -> Right (Just s)
Just _ -> Left "requestState must be a string"
when (isNothing reqs && isNothing st) $
Left "an input_required result must carry inputRequests or requestState"
Right (ResultInputRequired InputRequired {inputRequests = reqs, requestState = st})
Just (String other) -> Left ("unsupported resultType " <> clipText 64 other)
Just _ -> Left "resultType must be a string"
-- ---------------------------------------------------------------------------
-- Cache hints
data CacheScope = CachePublic | CachePrivate
deriving stock (Eq, Show, Generic)
-- | A freshness hint. Returned to the caller; this package keeps no cache.
data CacheHint = CacheHint
{ -- | Milliseconds the result may be considered fresh. Negative values
-- from the server are clamped to zero.
ttlMs :: !Integer,
scope :: !CacheScope
}
deriving stock (Eq, Show, Generic)
-- | Methods whose complete results carry cache hints.
cacheableMethods :: [Text]
cacheableMethods =
["server/discover", "tools/list", "prompts/list", "resources/list", "resources/templates/list", "resources/read"]
-- | Read @ttlMs@ and @cacheScope@. Both absent is 'Nothing' (earlier
-- revisions omit them). A present but ill-typed field, an unknown scope,
-- or only one of the two is an error.
decodeCacheHint :: Object -> Either Text (Maybe CacheHint)
decodeCacheHint o = case (KeyMap.lookup "ttlMs" o, KeyMap.lookup "cacheScope" o) of
(Nothing, Nothing) -> Right Nothing
(Just (Number n), Just (String s)) -> do
ttl <- case floatingOrInteger @Double n of
Right i -> Right (max 0 i)
Left _ -> Left "ttlMs must be an integer"
sc <- case s of
"public" -> Right CachePublic
"private" -> Right CachePrivate
_ -> Left "cacheScope must be \"public\" or \"private\""
Right (Just CacheHint {ttlMs = ttl, scope = sc})
(Just _, Just _) -> Left "ttlMs must be a number and cacheScope a string"
_ -> Left "ttlMs and cacheScope must appear together"
-- ---------------------------------------------------------------------------
-- Pagination
-- | An opaque pagination cursor. Never parsed or modified; an empty string
-- is a valid cursor.
newtype Cursor = Cursor Text
deriving stock (Eq, Ord, Generic)
instance Show Cursor where
show (Cursor t) = "Cursor " <> show (clipText 32 t)
cursorFromText :: Text -> Cursor
cursorFromText = Cursor
cursorToText :: Cursor -> Text
cursorToText (Cursor t) = t
-- | One page of a list result.
data Page a = Page
{ items :: ![a],
nextCursor :: !(Maybe Cursor),
cache :: !(Maybe CacheHint),
-- | Size of the response that carried the page, for byte budgets.
responseBytes :: !Int
}
deriving stock (Eq, Show, Generic, Functor)
-- | Ceilings for draining every page of a list.
data DrainLimits = DrainLimits
{ maxPages :: !Int,
maxItems :: !Int,
maxBytes :: !Int,
-- | Wall-clock budget for the whole drain.
maxElapsed :: !NominalDiffTime
}
deriving stock (Eq, Show, Generic)
defaultDrainLimits :: DrainLimits
defaultDrainLimits = DrainLimits {maxPages = 32, maxItems = 4096, maxBytes = 16 * 1024 * 1024, maxElapsed = 120}
-- | Why a drain stopped early. @e@ is the page fetcher's own error.
data DrainFailure e
= DrainPageFailed !Int !e
| DrainRepeatedCursor !Int
| DrainTooManyPages !Int
| DrainTooManyItems !Int
| DrainTooManyBytes !Int
| DrainDeadline !Int
deriving stock (Eq, Show, Generic)
-- | Fetch pages until one has no @nextCursor@, preserving order. Stops,
-- discarding what was collected, on the first fetch error, a cursor seen
-- before, or when a limit would be exceeded. Page and deadline limits are
-- checked /before/ a fetch, so no request is sent past them.
drainPages :: DrainLimits -> (Maybe Cursor -> IO (Either e (Page a))) -> IO (Either (DrainFailure e) [a])
drainPages lim fetch = do
start <- getCurrentTime
let go n seen cursor itemCount byteCount acc
| n >= lim.maxPages = pure (Left (DrainTooManyPages n))
| otherwise = do
now <- getCurrentTime
if diffUTCTime now start > lim.maxElapsed
then pure (Left (DrainDeadline n))
else do
r <- fetch cursor
case r of
Left e -> pure (Left (DrainPageFailed (n + 1) e))
Right page -> do
let items' = itemCount + length page.items
bytes' = byteCount + page.responseBytes
acc' = page.items : acc
if
| items' > lim.maxItems -> pure (Left (DrainTooManyItems items'))
| bytes' > lim.maxBytes -> pure (Left (DrainTooManyBytes bytes'))
| otherwise -> case page.nextCursor of
Nothing -> pure (Right (concat (reverse acc')))
Just c
| Set.member c seen -> pure (Left (DrainRepeatedCursor (n + 1)))
| otherwise -> go (n + 1) (Set.insert c seen) (Just c) items' bytes' acc'
go 0 Set.empty Nothing 0 0 []
-- ---------------------------------------------------------------------------
-- Subscriptions
-- | Which change notifications a @subscriptions/listen@ stream carries.
data SubscriptionFilter = SubscriptionFilter
{ toolsListChanged :: !Bool,
promptsListChanged :: !Bool,
resourcesListChanged :: !Bool,
resourceSubscriptions :: ![Text]
}
deriving stock (Eq, Show, Generic)
emptySubscriptionFilter :: SubscriptionFilter
emptySubscriptionFilter = SubscriptionFilter False False False []
instance ToJSON SubscriptionFilter where
toJSON f =
object $
["toolsListChanged" .= True | f.toolsListChanged]
<> ["promptsListChanged" .= True | f.promptsListChanged]
<> ["resourcesListChanged" .= True | f.resourcesListChanged]
<> ["resourceSubscriptions" .= f.resourceSubscriptions | not (null f.resourceSubscriptions)]
instance FromJSON SubscriptionFilter where
parseJSON = withObject "SubscriptionFilter" $ \o ->
SubscriptionFilter
<$> (fromMaybe False <$> o .:? "toolsListChanged")
<*> (fromMaybe False <$> o .:? "promptsListChanged")
<*> (fromMaybe False <$> o .:? "resourcesListChanged")
<*> (fromMaybe [] <$> o .:? "resourceSubscriptions")
-- | The notification methods a filter admits.
subscriptionNotificationMethods :: SubscriptionFilter -> [Text]
subscriptionNotificationMethods f =
["notifications/tools/list_changed" | f.toolsListChanged]
<> ["notifications/prompts/list_changed" | f.promptsListChanged]
<> ["notifications/resources/list_changed" | f.resourcesListChanged]
<> ["notifications/resources/updated" | not (null f.resourceSubscriptions)]
-- ---------------------------------------------------------------------------
-- Discovery and handshake
-- | Decode a @server/discover@ result.
decodeDiscoverResult :: Object -> Either Text ServerDescription
decodeDiscoverResult o = do
(vs, caps, info, instr) <- mapLeft' $ parseEither p o
hint <- decodeCacheHint o
when (null vs) (Left "supportedVersions is empty")
Right
ServerDescription
{ era = Modern latestModernVersion,
supportedVersions = vs,
capabilities = caps,
serverInfo = info,
instructions = instr,
cache = hint
}
where
p obj = do
vs <- obj .: "supportedVersions"
caps <- fromMaybe (ServerCapabilities KeyMap.empty) <$> obj .:? "capabilities"
info <- resultServerInfo obj
instr <- obj .:? "instructions"
pure (vs :: [ProtocolVersion], caps, info, instr)
-- | Decode an @initialize@ result into the negotiated version and server
-- description. The caller checks the version against its allowlist.
decodeInitializeResult :: Object -> Either Text (ProtocolVersion, ServerDescription)
decodeInitializeResult o = mapLeft' $ flip parseEither o $ \obj -> do
v <- obj .: "protocolVersion"
caps <- fromMaybe (ServerCapabilities KeyMap.empty) <$> obj .:? "capabilities"
info <- obj .:? "serverInfo"
instr <- obj .:? "instructions"
pure
( v,
ServerDescription
{ era = Legacy v,
supportedVersions = [v],
capabilities = caps,
serverInfo = info,
instructions = instr,
cache = Nothing
}
)
resultServerInfo :: Object -> Parser (Maybe Implementation)
resultServerInfo obj = do
meta <- obj .:? "_meta"
case meta of
Just (m :: KeyMap Value) | Just v <- KeyMap.lookup metaServerInfo m -> Just <$> parseJSON v
_ -> pure Nothing
mapLeft' :: Either String a -> Either Text a
mapLeft' = either (Left . clipText 200 . Text.pack) Right
-- | Truncate text to a character budget, marking the cut.
clipText :: Int -> Text -> Text
clipText n t
| Text.length t <= n = t
| otherwise = Text.take n t <> "…"