packages feed

baikai-mcp-0.1.0.0: src/Baikai/Mcp/Client.hs

-- | A Model Context Protocol client handle.
--
-- An 'McpConnection' is a /local/ resource: it owns the binding to one
-- server endpoint, the protocol era detected when it was opened, the host's
-- request hook, its limits and, for handshake-era servers only, the session
-- the server issued. Modern MCP (@2026-07-28@) has no handshake and no
-- session; each request carries its own version and capabilities. See
-- @docs/adr/0031-remote-mcp-connections-are-local-client-handles.md@.
--
-- Every actual transmission — discovery, a compatibility probe, the
-- handshake, each page, each continuation round, a reply to a legacy
-- server's ping and the session teardown — first passes the
-- 'McpRequestHook'. The hook can refuse the send, in which case nothing is
-- transmitted, or add headers such as credentials.
--
-- A reply that is lost leaves the remote effect unknown. Such a failure is
-- reported with 'Uncertain' delivery and is never replayed here.
module Baikai.Mcp.Client
  ( -- * Configuration
    McpServerConfig (..),
    mcpServerConfig,
    McpProfile (..),
    McpLimits (..),
    defaultMcpLimits,
    defaultClientInfo,

    -- * Request hook
    McpRequestHook (..),
    SendAttempt (..),
    AttemptPurpose (..),
    SendDecision (..),
    SendHeader,
    sendHeader,
    sendHeaderName,
    denyAll,

    -- * Lifecycle
    McpConnection,
    connectMcp,
    connectMcpWith,
    closeMcp,
    withMcpConnection,
    connectionDescription,
    connectionEra,
    connectionServerName,
    connectionBindingShape,
    BindingShape (..),
    connectionOpenListeners,

    -- * Requests
    McpCall (..),
    mcpCall,
    CompleteResult (..),
    McpOutcome (..),
    Unfinished (..),
    UnfinishedReason (..),
    callMethod,
    callInteractive,

    -- * Pages
    requestPage,

    -- * Subscriptions
    Subscription,
    subscriptionId,
    subscriptionRequested,
    subscriptionAcknowledged,
    SubscriptionEvent (..),
    SubscriptionEnd (..),
    withSubscription,
    nextSubscriptionEvent,

    -- * Errors
    module Baikai.Mcp.Error,

    -- * Caller-owned streams (stdio)
    McpStreamConfig (..),
    mcpStreamConfig,
    StreamProfile (..),
    connectMcpStream,
    withMcpStream,

    -- * Internal construction (for transports in this package)
    connectWithBinding,
    ConnectPlan (..),
  )
where

import Baikai.Mcp.Error
import Baikai.Mcp.Internal.Binding
import Baikai.Mcp.Internal.Http (HttpEndpoint, parseEndpoint, rethrowAsync)
import Baikai.Mcp.Protocol
import Baikai.Mcp.Transport
import Baikai.Mcp.Transport.HttpSse (openHttpSseBinding)
import Baikai.Mcp.Transport.Stream (McpStream, streamBinding)
import Control.Exception (SomeException, bracket, mask, onException, try)
import Control.Monad (forM_, unless, void)
import Data.Aeson (Value (..), toJSON)
import Data.Aeson qualified as Aeson
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object, Parser, parseEither)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.IORef
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, isJust)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TE
import Data.Time.Clock (NominalDiffTime)
import Data.Version (showVersion)
import GHC.Generics (Generic)
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Client.TLS qualified as TLS
import Network.HTTP.Types (Header, HeaderName)
import Paths_baikai_mcp qualified as Paths
import System.Timeout (timeout)

-- ---------------------------------------------------------------------------
-- Configuration

-- | How the client chooses a protocol era and transport.
data McpProfile
  = -- | Probe with @server/discover@; fall back to the handshake-era
    -- Streamable HTTP revision only when the probe's answer carries no
    -- recognized modern error. Credential challenges, network failures and
    -- malformed successes never cause a fallback.
    McpAuto
  | -- | Modern revisions only; a legacy server is an incompatibility.
    McpModernOnly
  | -- | A known handshake-era Streamable HTTP server; skip the probe.
    McpLegacyStreamableHttp
  | -- | The deprecated @2024-11-05@ HTTP+SSE transport, selected
    -- explicitly. Eligible for removal from the protocol; see
    -- "Baikai.Mcp.Transport.HttpSse".
    McpLegacyHttpSse
  deriving stock (Eq, Show, Generic)

-- | Finite ceilings for every operation.
data McpLimits = McpLimits
  { -- | Bytes in one reply.
    maxResponseBytes :: !Int,
    -- | Bytes in one SSE event or line.
    maxFrameBytes :: !Int,
    -- | Deadline for one operation, including its continuation rounds.
    requestTimeout :: !NominalDiffTime,
    -- | Deadline for opening a connection (probe and handshake).
    connectTimeout :: !NominalDiffTime,
    -- | How many times a state-only interim result is continued. Zero
    -- disables continuation.
    maxContinuationRounds :: !Int
  }
  deriving stock (Eq, Show, Generic)

defaultMcpLimits :: McpLimits
defaultMcpLimits =
  McpLimits
    { maxResponseBytes = 16 * 1024 * 1024,
      maxFrameBytes = 4 * 1024 * 1024,
      requestTimeout = 60,
      connectTimeout = 30,
      maxContinuationRounds = 4
    }

data McpServerConfig = McpServerConfig
  { -- | A non-secret identity for the server, shown to the request hook.
    serverName :: !Text,
    -- | The MCP endpoint URL. Must not embed credentials.
    endpoint :: !Text,
    profile :: !McpProfile,
    limits :: !McpLimits,
    requestHook :: !McpRequestHook,
    -- | Sent as @clientInfo@; 'Nothing' omits it on modern requests.
    clientInfo :: !(Maybe Implementation)
  }

-- | A configuration with the automatic profile, default limits, no
-- credentials and every request allowed.
mcpServerConfig :: Text -> Text -> McpServerConfig
mcpServerConfig nm url =
  McpServerConfig
    { serverName = nm,
      endpoint = url,
      profile = McpAuto,
      limits = defaultMcpLimits,
      requestHook = mempty,
      clientInfo = Just defaultClientInfo
    }

defaultClientInfo :: Implementation
defaultClientInfo = implementation "baikai-mcp" (Text.pack (showVersion Paths.version))

-- ---------------------------------------------------------------------------
-- Request hook

-- | Why a transmission is about to happen.
data AttemptPurpose
  = PurposeDiscovery
  | PurposeHandshake
  | PurposeRequest
  | -- | The n-th retry of a request the server answered with a state-only
    -- interim result.
    PurposeContinuation !Int
  | PurposeListen
  | PurposeNotification
  | -- | A reply to a request a legacy server sent.
    PurposeReply
  | -- | Opening the deprecated HTTP+SSE event stream.
    PurposeEventStream
  | PurposeTeardown
  deriving stock (Eq, Show, Generic)

-- | What the hook is asked to approve. Contains no argument values.
data SendAttempt = SendAttempt
  { serverName :: !Text,
    endpoint :: !Text,
    -- | @scheme://host:port@ that will receive the request.
    origin :: !Text,
    method :: !Text,
    -- | The tool or prompt name, or the resource URI.
    target :: !(Maybe Text),
    -- | Present on a request for a page after the first.
    cursor :: !(Maybe Cursor),
    purpose :: !AttemptPurpose
  }
  deriving stock (Eq, Show, Generic)

-- | An extra header to send. Its value is never shown.
data SendHeader = SendHeader !HeaderName !ByteString

instance Show SendHeader where
  show (SendHeader n _) = "SendHeader " <> show n <> " <redacted>"

sendHeader :: HeaderName -> ByteString -> SendHeader
sendHeader = SendHeader

sendHeaderName :: SendHeader -> HeaderName
sendHeaderName (SendHeader n _) = n

data SendDecision
  = SendAllowed ![SendHeader]
  | SendDenied !Text
  deriving stock (Show)

-- | Runs before every transmission. Combine hooks with '<>': the left one
-- runs first, a denial stops the chain and allowed headers accumulate.
newtype McpRequestHook = McpRequestHook {runRequestHook :: SendAttempt -> IO SendDecision}

instance Semigroup McpRequestHook where
  McpRequestHook a <> McpRequestHook b = McpRequestHook $ \att -> do
    r <- a att
    case r of
      SendDenied why -> pure (SendDenied why)
      SendAllowed hs -> do
        r' <- b att
        pure $ case r' of
          SendDenied why -> SendDenied why
          SendAllowed hs' -> SendAllowed (hs <> hs')

instance Monoid McpRequestHook where
  mempty = McpRequestHook (const (pure (SendAllowed [])))

denyAll :: Text -> McpRequestHook
denyAll why = McpRequestHook (const (pure (SendDenied why)))

-- ---------------------------------------------------------------------------
-- Connections

-- | How headers and @_meta@ are written for the current stage.
data WireMode
  = ModeModern !ProtocolVersion
  | -- | Handshake era; 'Nothing' before @initialize@ completes.
    ModeLegacy !(Maybe ProtocolVersion)

data Wire = Wire
  { config :: !McpServerConfig,
    binding :: !Binding,
    mode :: !(IORef WireMode),
    session :: !(IORef (Maybe ByteString)),
    counter :: !(IORef Integer)
  }

data McpConnection = McpConnection
  { wire :: !Wire,
    description :: !ServerDescription,
    released :: !(IORef Bool),
    expired :: !(IORef Bool),
    listeners :: !(IORef (Map Int (IO ()))),
    listenerSeq :: !(IORef Int)
  }

connectionDescription :: McpConnection -> ServerDescription
connectionDescription c = c.description

connectionEra :: McpConnection -> Era
connectionEra c = c.description.era

connectionServerName :: McpConnection -> Text
connectionServerName c = c.wire.config.serverName

connectionBindingShape :: McpConnection -> BindingShape
connectionBindingShape c = c.wire.binding.shape

-- | How many subscription streams are open on this connection.
connectionOpenListeners :: McpConnection -> IO Int
connectionOpenListeners c = Map.size <$> readIORef c.listeners

-- | Open a connection using the process-wide TLS manager.
connectMcp :: McpServerConfig -> IO (Either McpError McpConnection)
connectMcp cfg = do
  mgr <- TLS.getGlobalManager
  connectMcpWith mgr cfg

-- | Open a connection with a caller-supplied HTTP manager.
connectMcpWith :: HTTP.Manager -> McpServerConfig -> IO (Either McpError McpConnection)
connectMcpWith mgr cfg = case parseEndpoint cfg.endpoint of
  Left why -> pure (Left (mcpError InvalidInput NotSent why))
  Right ep -> case cfg.profile of
    McpLegacyHttpSse -> connectHttpSse mgr cfg ep
    McpAuto -> connectWithBinding cfg (streamableHttpBinding mgr ep) PlanProbeThenLegacy
    McpModernOnly -> connectWithBinding cfg (streamableHttpBinding mgr ep) PlanModernOnly
    McpLegacyStreamableHttp -> connectWithBinding cfg (streamableHttpBinding mgr ep) (PlanHandshake legacyStreamableVersions)

connectHttpSse :: HTTP.Manager -> McpServerConfig -> HttpEndpoint -> IO (Either McpError McpConnection)
connectHttpSse mgr cfg ep = do
  let probeBinding = streamableHttpBinding mgr ep
      att =
        SendAttempt
          { serverName = cfg.serverName,
            endpoint = probeBinding.endpointText,
            origin = probeBinding.origin,
            method = "GET",
            target = Nothing,
            cursor = Nothing,
            purpose = PurposeEventStream
          }
  decision <- approve cfg att
  case decision of
    Left e -> pure (Left e)
    Right hdrs -> do
      opened <-
        openHttpSseBinding
          mgr
          ep
          (wireLimits cfg.limits)
          (micros cfg.limits.connectTimeout)
          hdrs
      case opened of
        Left e -> pure (Left e)
        Right b -> connectWithBinding cfg b (PlanHandshake (httpSseVersions <> legacyStreamableVersions))

-- | How a stream connection chooses its era.
data StreamProfile
  = -- | Probe with @server/discover@ and fall back to @initialize@ on any
    -- non-modern error or silence within 'probeTimeout'.
    StreamDetect
  | -- | Modern revisions only; never send @initialize@.
    StreamModernOnly
  | -- | A known handshake-era server; skip the probe.
    StreamLegacyOnly
  deriving stock (Eq, Show, Generic)

-- | Configuration for a connection over a caller-owned stream. A stdio
-- server takes its credentials from its environment, so the hook here
-- authorizes sends but its headers are ignored.
data McpStreamConfig = McpStreamConfig
  { -- | A non-secret identity for the server, shown to the request hook.
    streamName :: !Text,
    streamProfile :: !StreamProfile,
    -- | How long the probe waits before treating silence as legacy.
    probeTimeout :: !NominalDiffTime,
    streamLimits :: !McpLimits,
    streamRequestHook :: !McpRequestHook,
    streamClientInfo :: !(Maybe Implementation)
  }

mcpStreamConfig :: Text -> McpStreamConfig
mcpStreamConfig nm =
  McpStreamConfig
    { streamName = nm,
      streamProfile = StreamDetect,
      probeTimeout = 5,
      streamLimits = defaultMcpLimits,
      streamRequestHook = mempty,
      streamClientInfo = Just defaultClientInfo
    }

-- | Open a connection over a stream the caller owns. The caller keeps the
-- process; releasing the connection runs the stream's close action.
connectMcpStream :: McpStreamConfig -> McpStream -> IO (Either McpError McpConnection)
connectMcpStream sc s = do
  let label = "stream:" <> sc.streamName
      cfg =
        McpServerConfig
          { serverName = sc.streamName,
            endpoint = label,
            profile = McpAuto,
            limits = sc.streamLimits,
            requestHook = sc.streamRequestHook,
            clientInfo = sc.streamClientInfo
          }
      plan = case sc.streamProfile of
        StreamDetect -> PlanStreamProbe sc.probeTimeout legacyStreamableVersions
        StreamModernOnly -> PlanModernOnly
        StreamLegacyOnly -> PlanHandshake legacyStreamableVersions
  b <- streamBinding label (wireLimits sc.streamLimits) s
  connectWithBinding cfg b plan

-- | Open, run and always release.
withMcpStream :: McpStreamConfig -> McpStream -> (McpConnection -> IO a) -> IO (Either McpError a)
withMcpStream sc s k =
  bracket (connectMcpStream sc s) (either (const (pure ())) closeMcp) $ \case
    Left e -> pure (Left e)
    Right c -> Right <$> k c

-- | What opening a connection does on its binding.
data ConnectPlan
  = -- | @server/discover@, falling back to the handshake when allowed.
    PlanProbeThenLegacy
  | PlanModernOnly
  | -- | @initialize@ offering the first version, accepting any listed.
    PlanHandshake ![ProtocolVersion]
  | -- | Probe, and treat a non-modern error or silence within the given
    -- time as a legacy server (byte streams, which have no HTTP status).
    PlanStreamProbe !NominalDiffTime ![ProtocolVersion]

-- | Open a connection over an already-constructed binding. The binding is
-- released if opening fails.
connectWithBinding :: McpServerConfig -> Binding -> ConnectPlan -> IO (Either McpError McpConnection)
connectWithBinding cfg b plan = do
  m <- newIORef (ModeLegacy Nothing)
  s <- newIORef Nothing
  n <- newIORef 0
  let w = Wire {config = cfg, binding = b, mode = m, session = s, counter = n}
  forM_ b.unsolicited $ \ref -> writeIORef ref (answerServerRequest w)
  r <-
    ( timeout (micros cfg.limits.connectTimeout) (open w plan)
        >>= pure . fromMaybe (Left (mcpError TimedOut Uncertain "opening the MCP connection timed out"))
    )
      `onException` b.release
  case r of
    Left e -> b.release >> pure (Left e)
    Right desc -> do
      rel <- newIORef False
      ex <- newIORef False
      ls <- newIORef Map.empty
      sq <- newIORef 0
      pure (Right McpConnection {wire = w, description = desc, released = rel, expired = ex, listeners = ls, listenerSeq = sq})

open :: Wire -> ConnectPlan -> IO (Either McpError ServerDescription)
open w = \case
  PlanModernOnly -> do
    v <- probe w Nothing latestModernVersion
    case v of
      ProbeModern d -> pure (Right d)
      ProbeLegacy e -> pure (Left (setMessage ("the server does not speak a modern MCP revision (" <> e.message <> ")") e {kind = IncompatibleServer}))
      ProbeFailed e -> pure (Left e)
  PlanProbeThenLegacy -> do
    v <- probe w Nothing latestModernVersion
    case v of
      ProbeModern d -> pure (Right d)
      ProbeLegacy _ -> handshake w legacyStreamableVersions
      ProbeFailed e -> pure (Left e)
  PlanHandshake vs -> handshake w vs
  PlanStreamProbe wait vs -> do
    v <- probe w (Just wait) latestModernVersion
    case v of
      ProbeModern d -> pure (Right d)
      ProbeLegacy _ -> handshake w vs
      ProbeFailed e -> pure (Left e)

data ProbeVerdict
  = ProbeModern ServerDescription
  | -- | The answer identifies a handshake-era server.
    ProbeLegacy McpError
  | ProbeFailed McpError

-- | Send @server/discover@ at a version. On @UnsupportedProtocolVersion@
-- retry once with an implemented version the server lists.
probe :: Wire -> Maybe NominalDiffTime -> ProtocolVersion -> IO ProbeVerdict
probe w silenceIsLegacy v = do
  writeIORef w.mode (ModeModern v)
  r <- case silenceIsLegacy of
    Nothing -> sendOnce w PurposeDiscovery "server/discover" KeyMap.empty [] Nothing
    Just wait -> fromMaybe (Left silent) <$> timeout (micros wait) (sendOnce w PurposeDiscovery "server/discover" KeyMap.empty [] Nothing)
  case r of
    Right reply -> case reply.outcome of
      Right obj -> case decodeResultKind "server/discover" obj >> decodeDiscoverResult obj of
        Left why -> pure (ProbeFailed ((mcpError MalformedReply Answered ("unreadable server/discover result: " <> why)) {httpStatus = reply.status}))
        Right d -> case [x | x <- modernVersions, x `elem` d.supportedVersions] of
          (chosen : _) -> do
            writeIORef w.mode (ModeModern chosen)
            pure (ProbeModern d {era = Modern chosen})
          [] -> pure (ProbeFailed (incompatible reply.status d.supportedVersions))
      Left e
        | Just offered <- unsupportedVersionsOffered e ->
            case [x | x <- modernVersions, x `elem` offered, x /= v] of
              (other : _) -> probe w silenceIsLegacy other
              [] -> pure (ProbeFailed ((incompatible reply.status offered) {rpc = Just e}))
        | isModernErrorCode e.code -> pure (ProbeFailed (remote reply e))
        | maybe True legacyStatus reply.status -> pure (ProbeLegacy (remote reply e))
        | otherwise -> pure (ProbeFailed (remote reply e))
    Left e
      | e.kind == HttpFailure, e.delivery == Answered, maybe False legacyStatus e.httpStatus, e.httpStatus /= Just 401, e.httpStatus /= Just 403 -> pure (ProbeLegacy e)
      | e.kind == TimedOut, isJust silenceIsLegacy, e.message == silent.message -> pure (ProbeLegacy e)
      | otherwise -> pure (ProbeFailed e)
  where
    legacyStatus s = (s >= 200 && s < 300) || s `elem` [400, 404, 405]
    silent = mcpError TimedOut Uncertain "the server did not answer server/discover"
    incompatible st vs =
      (mcpError IncompatibleServer Answered ("the server supports none of the implemented protocol versions; it offers " <> Text.intercalate ", " (map (.versionText) vs)))
        { httpStatus = st
        }

-- | The handshake of 2025-11-25 and earlier.
handshake :: Wire -> [ProtocolVersion] -> IO (Either McpError ServerDescription)
handshake w allowed = do
  writeIORef w.mode (ModeLegacy Nothing)
  let preferred = case allowed of
        (v : _) -> v
        [] -> ProtocolVersion "2025-11-25"
      info = fromMaybe defaultClientInfo w.config.clientInfo
      params =
        KeyMap.fromList
          [ ("protocolVersion", toJSON preferred),
            ("capabilities", Object KeyMap.empty),
            ("clientInfo", toJSON info)
          ]
  r <- sendOnce w PurposeHandshake "initialize" params [] Nothing
  case r of
    Left e -> pure (Left e)
    Right reply -> case reply.outcome of
      Left e -> pure (Left (remote reply e))
      Right obj -> case decodeInitializeResult obj of
        Left why -> pure (Left ((mcpError MalformedReply Answered ("unreadable initialize result: " <> why)) {httpStatus = reply.status}))
        Right (v, desc)
          | v `notElem` allowed ->
              pure (Left ((mcpError IncompatibleServer Answered ("the server negotiated the unsupported protocol version " <> clipText 32 v.versionText)) {httpStatus = reply.status}))
          | otherwise -> do
              writeIORef w.session reply.sessionId
              writeIORef w.mode (ModeLegacy (Just v))
              sent <- notify w "notifications/initialized" KeyMap.empty
              pure (desc <$ sent)

-- ---------------------------------------------------------------------------
-- Sending

micros :: NominalDiffTime -> Int
micros t = max 1 (floor (realToFrac t * 1000000 :: Double))

wireLimits :: McpLimits -> WireLimits
wireLimits l = WireLimits {maxResponseBytes = l.maxResponseBytes, maxFrameBytes = l.maxFrameBytes}

-- | Ask the hook and check its headers.
approve :: McpServerConfig -> SendAttempt -> IO (Either McpError [Header])
approve cfg att = do
  d <- runRequestHook cfg.requestHook att
  pure $ case d of
    SendDenied why -> Left (mcpError RequestDenied NotSent ("the request hook refused " <> att.method <> ": " <> clipText 200 why))
    SendAllowed hs
      | any (isProtocolControlledHeader . sendHeaderName) hs ->
          Left (mcpError InvalidInput NotSent "the request hook supplied a header this client controls")
      | otherwise -> Right [(n, v) | SendHeader n v <- hs]

attemptFor :: Wire -> AttemptPurpose -> Text -> Object -> SendAttempt
attemptFor w p method params =
  SendAttempt
    { serverName = w.config.serverName,
      endpoint = w.binding.endpointText,
      origin = w.binding.origin,
      method = method,
      target = routingName method params,
      cursor = case KeyMap.lookup "cursor" params of
        Just (String c) -> Just (cursorFromText c)
        _ -> Nothing,
      purpose = p
    }

-- | Protocol headers for the current mode.
protocolHeaders :: Wire -> WireMode -> Text -> Object -> [ParamHeader] -> IO [Header]
protocolHeaders w m method params mirrors
  | w.binding.shape /= RequestScopedHttp = pure []
  | otherwise = case m of
      ModeModern v ->
        pure $
          [(hProtocolVersion, TE.encodeUtf8 v.versionText), (hMcpMethod, TE.encodeUtf8 method)]
            <> [(hMcpName, encodeHeaderValue n) | Just n <- [routingName method params]]
            <> [(paramHeaderField p, paramHeaderValue p) | p <- mirrors]
      ModeLegacy mv -> do
        s <- readIORef w.session
        pure $
          [(hProtocolVersion, TE.encodeUtf8 v.versionText) | Just v <- [mv], v.versionText >= "2025-06-18"]
            <> [(hSessionId, sid) | Just sid <- [s]]

-- | Send one request and return its correlated reply.
sendOnce :: Wire -> AttemptPurpose -> Text -> Object -> [ParamHeader] -> Maybe (Text -> Object -> IO ()) -> IO (Either McpError Reply)
sendOnce w p method params mirrors sink = do
  approved <- approve w.config (attemptFor w p method params)
  case approved of
    Left e -> pure (Left e)
    Right extra -> do
      m <- readIORef w.mode
      rid <- RequestIdNumber <$> atomicModifyIORef' w.counter (\c -> (c + 1, c + 1))
      phs <- protocolHeaders w m method params mirrors
      let params' = case m of
            ModeModern v -> withRequestMeta (requestMeta v w.config.clientInfo) params
            ModeLegacy _ -> params
          ex =
            Exchange
              { requestId = rid,
                method = method,
                body = BS.toStrict (Aeson.encode (encodeRequest rid method params')),
                headers = phs <> extra,
                onNotification = fromMaybe (\_ _ -> pure ()) sink,
                onServerRequest = answerServerRequest w
              }
      w.binding.exchange (wireLimits w.config.limits) ex

-- | Send a notification (legacy handshake only on HTTP).
notify :: Wire -> Text -> Object -> IO (Either McpError ())
notify w method params = do
  approved <- approve w.config (attemptFor w PurposeNotification method params)
  case approved of
    Left e -> pure (Left e)
    Right extra -> do
      m <- readIORef w.mode
      phs <- protocolHeaders w m method params []
      w.binding.post (phs <> extra) (BS.toStrict (Aeson.encode (encodeNotification method params)))

-- | Answer a request a legacy server sent: @ping@ gets an empty result;
-- anything else is a method this client does not implement.
answerServerRequest :: Wire -> RequestId -> Text -> Object -> IO ()
answerServerRequest w rid method _ = do
  approved <- approve w.config (attemptFor w PurposeReply method KeyMap.empty)
  case approved of
    Left _ -> pure ()
    Right extra -> do
      m <- readIORef w.mode
      phs <- protocolHeaders w m method KeyMap.empty []
      let reply
            | method == "ping" = encodeResultResponse rid KeyMap.empty
            | otherwise = encodeErrorResponse rid (rpcError methodNotFound "this client implements no server-initiated requests")
      r <- try @SomeException (w.binding.post (phs <> extra) (BS.toStrict (Aeson.encode reply)))
      either rethrowAsync (const (pure ())) r

remote :: Reply -> RpcError -> McpError
remote reply e =
  (mcpError RemoteRpcError Answered ("the server returned an error: " <> e.message))
    { httpStatus = reply.status,
      rpc = Just e
    }

-- ---------------------------------------------------------------------------
-- Requests

-- | A request for 'callMethod' or 'callInteractive'.
data McpCall = McpCall
  { method :: !Text,
    -- | Parameters without the protocol @_meta@ fields, which the client
    -- adds for the connection's era.
    params :: !Object,
    -- | Parameter mirrors for a modern @tools/call@ over HTTP.
    paramHeaders :: ![ParamHeader],
    -- | Receives request-scoped notifications (progress, logging).
    onNotification :: !(Maybe (Text -> Object -> IO ()))
  }

mcpCall :: Text -> Object -> McpCall
mcpCall m p = McpCall {method = m, params = p, paramHeaders = [], onNotification = Nothing}

-- | A completed result.
data CompleteResult = CompleteResult
  { -- | The whole result object, including fields this package does not
    -- model.
    result :: !Object,
    responseBytes :: !Int,
    -- | The server's freshness hint. Always 'Nothing' for a result reached
    -- through continuation rounds, which must not be cached.
    cache :: !(Maybe CacheHint),
    serverInfo :: !(Maybe Implementation),
    -- | Continuation rounds sent before the result completed.
    continuationRounds :: !Int
  }
  deriving stock (Eq, Show, Generic)

data UnfinishedReason
  = -- | The server asked for input (sampling, elicitation, roots) this
    -- client does not provide.
    NeedsClientInput
  | -- | The round limit was spent while the server kept answering with
    -- state alone.
    RoundLimitReached
  | -- | The request hook refused a continuation round.
    ContinuationDenied !Text
  deriving stock (Eq, Show, Generic)

-- | An interim result returned to the caller unanswered.
data Unfinished = Unfinished
  { inputRequests :: !(Maybe (Map Text Value)),
    requestState :: !(Maybe Text),
    roundsSent :: !Int,
    reason :: !UnfinishedReason
  }
  deriving stock (Eq, Show, Generic)

data McpOutcome a
  = McpCompleted !a
  | McpUnfinished !Unfinished
  deriving stock (Eq, Show, Generic, Functor)

-- | Fail early on a released or expired handle.
guarded :: McpConnection -> IO (Either McpError a) -> IO (Either McpError a)
guarded c act = do
  rel <- readIORef c.released
  ex <- readIORef c.expired
  if
    | rel -> pure (Left (mcpError ConnectionReleased NotSent "the MCP connection has been released"))
    | ex -> pure (Left (mcpError SessionExpired NotSent "the server's session has expired; open a new connection"))
    | otherwise -> act

withDeadline :: NominalDiffTime -> IO (Either McpError a) -> IO (Either McpError a)
withDeadline t act =
  fromMaybe (Left (mcpError TimedOut Uncertain "the MCP request timed out")) <$> timeout (micros t) act

-- | Turn a session-scoped 404 into an expiry and mark the handle.
noteExpiry :: McpConnection -> McpError -> IO McpError
noteExpiry c e = do
  s <- readIORef c.wire.session
  if isJust s && e.httpStatus == Just 404
    then do
      writeIORef c.expired True
      pure (setMessage "the server no longer recognizes this session; open a new connection" e {kind = SessionExpired})
    else pure e

-- | Send a request that may return an interim result. A state-only
-- interim result is continued — same method and parameters, the state
-- echoed exactly, a new request identifier — while rounds remain and the
-- hook allows each round. Interim results carrying input requests are
-- returned unanswered.
callInteractive :: McpConnection -> McpCall -> IO (Either McpError (McpOutcome CompleteResult))
callInteractive c call = guarded c . withDeadline c.wire.config.limits.requestTimeout $ go 0 Nothing
  where
    lim = c.wire.config.limits.maxContinuationRounds
    go :: Int -> Maybe Text -> IO (Either McpError (McpOutcome CompleteResult))
    go rounds st = do
      let purpose = if rounds == 0 then PurposeRequest else PurposeContinuation rounds
          params' = maybe call.params (\s -> KeyMap.insert "requestState" (String s) call.params) st
      r <- sendOnce c.wire purpose call.method params' call.paramHeaders call.onNotification
      case r of
        Left e
          | rounds > 0,
            e.kind == RequestDenied ->
              pure (Right (McpUnfinished Unfinished {inputRequests = Nothing, requestState = st, roundsSent = rounds - 1, reason = ContinuationDenied e.message}))
          | otherwise -> Left <$> noteExpiry c e
        Right reply -> case reply.outcome of
          Left e -> Left <$> noteExpiry c (remote reply e)
          Right obj -> case decodeResultKind call.method obj of
            Left why -> pure (Left ((mcpError MalformedReply Uncertain why) {httpStatus = reply.status}))
            Right ResultComplete -> case completeResult call.method rounds reply obj of
              Left why -> pure (Left ((mcpError MalformedReply Answered why) {httpStatus = reply.status}))
              Right cr -> pure (Right (McpCompleted cr))
            Right (ResultInputRequired ir) -> case (ir.inputRequests, ir.requestState) of
              (Just _, _) -> pure (Right (McpUnfinished (unfinished ir rounds NeedsClientInput)))
              (Nothing, Just s)
                | rounds >= lim -> pure (Right (McpUnfinished (unfinished ir rounds RoundLimitReached)))
                | otherwise -> go (rounds + 1) (Just s)
              (Nothing, Nothing) -> pure (Left (mcpError MalformedReply Answered "an interim result carried nothing to continue"))
    unfinished ir rounds why = Unfinished {inputRequests = ir.inputRequests, requestState = ir.requestState, roundsSent = rounds, reason = why}

completeResult :: Text -> Int -> Reply -> Object -> Either Text CompleteResult
completeResult method rounds reply obj = do
  hint <-
    if method `elem` cacheableMethods
      then decodeCacheHint obj
      else Right Nothing
  let info = case KeyMap.lookup "_meta" obj of
        Just (Object meta) | Just v <- KeyMap.lookup metaServerInfo meta -> either (const Nothing) Just (parseEither Aeson.parseJSON v)
        _ -> Nothing
  Right
    CompleteResult
      { result = obj,
        responseBytes = reply.bytes,
        cache = if rounds == 0 then hint else Nothing,
        serverInfo = info,
        continuationRounds = rounds
      }

-- | Send a request whose result is always complete. An interim result is
-- reported as an error.
callMethod :: McpConnection -> McpCall -> IO (Either McpError CompleteResult)
callMethod c call = do
  r <- callInteractive c call
  pure $ case r of
    Left e -> Left e
    Right (McpCompleted cr) -> Right cr
    Right (McpUnfinished u) ->
      Left (mcpError UnsupportedOperation Answered ("the server left " <> call.method <> " unfinished (" <> Text.pack (show u.reason) <> "); use callInteractive"))

-- | Request one page of a paginated list. @field@ names the array of
-- items; each item is decoded with the given parser.
requestPage :: McpConnection -> Text -> Aeson.Key -> (Value -> Parser a) -> Maybe Cursor -> IO (Either McpError (Page a))
requestPage c method field itemParser cur = do
  let params = maybe KeyMap.empty (\x -> KeyMap.singleton "cursor" (String (cursorToText x))) cur
  r <- callMethod c (mcpCall method params)
  pure $
    r >>= \cr -> case parseEither (pageParser cr) cr.result of
      Left why -> Left (mcpError MalformedReply Answered ("unreadable " <> method <> " page: " <> clipText 200 (Text.pack why)))
      Right p -> Right p
  where
    pageParser cr obj = do
      raw <- case KeyMap.lookup field obj of
        Just (Array xs) -> pure (foldr (:) [] xs)
        Just _ -> fail (show field <> " must be an array")
        Nothing -> fail ("missing " <> show field)
      xs <- traverse itemParser raw
      nc <- case KeyMap.lookup "nextCursor" obj of
        Nothing -> pure Nothing
        Just Null -> pure Nothing
        Just (String s) -> pure (Just (cursorFromText s))
        Just _ -> fail "nextCursor must be a string"
      pure Page {items = xs, nextCursor = nc, cache = cr.cache, responseBytes = cr.responseBytes}

-- ---------------------------------------------------------------------------
-- Lifecycle

-- | Release the connection: end open subscriptions, end a legacy session
-- (through the hook) and release the binding. Safe to call more than once.
closeMcp :: McpConnection -> IO ()
closeMcp c = mask $ \_ -> do
  was <- atomicModifyIORef' c.released (True,)
  unless was $ do
    ls <- atomicModifyIORef' c.listeners (Map.empty,)
    forM_ (Map.elems ls) $ \closeIt -> void (try @SomeException closeIt)
    s <- readIORef c.wire.session
    case (s, c.wire.binding.terminate) of
      (Just _, Just term) -> do
        approved <- approve c.wire.config (attemptFor c.wire PurposeTeardown "DELETE" KeyMap.empty)
        case approved of
          Left _ -> pure ()
          Right extra -> do
            m <- readIORef c.wire.mode
            phs <- protocolHeaders c.wire m "DELETE" KeyMap.empty []
            void (timeout (micros (min 5 c.wire.config.limits.requestTimeout)) (try @SomeException (term (phs <> extra))))
      _ -> pure ()
    c.wire.binding.release

-- | Open, run and always release.
withMcpConnection :: McpServerConfig -> (McpConnection -> IO a) -> IO (Either McpError a)
withMcpConnection cfg k =
  bracket (connectMcp cfg) (either (const (pure ())) closeMcp) $ \case
    Left e -> pure (Left e)
    Right c -> Right <$> k c

-- ---------------------------------------------------------------------------
-- Subscriptions

data SubscriptionEnd
  = -- | The server answered the listen request: a graceful end.
    EndedGracefully
  | -- | The server sent @notifications/cancelled@ for the subscription.
    EndedByServer
  | -- | The client released the subscription.
    EndedByClient
  | -- | The stream closed with neither signal.
    Disconnected
  | EndedWithError !McpError
  deriving stock (Eq, Show, Generic)

data SubscriptionEvent
  = SubscriptionNotification !Text !Object
  | SubscriptionEnded !SubscriptionEnd
  deriving stock (Eq, Show, Generic)

data Subscription = Subscription
  { sid :: !RequestId,
    requested :: !SubscriptionFilter,
    acknowledged :: !SubscriptionFilter,
    stream :: !MessageStream,
    ended :: !(IORef (Maybe SubscriptionEnd))
  }

subscriptionId :: Subscription -> RequestId
subscriptionId s = s.sid

subscriptionRequested :: Subscription -> SubscriptionFilter
subscriptionRequested s = s.requested

-- | What the server agreed to deliver: possibly a subset of the request.
subscriptionAcknowledged :: Subscription -> SubscriptionFilter
subscriptionAcknowledged s = s.acknowledged

-- | Open a @subscriptions/listen@ stream, wait for its acknowledgment and
-- run the action. The stream is closed when the action returns or throws,
-- and by 'closeMcp'. Modern connections only.
withSubscription :: McpConnection -> SubscriptionFilter -> (Subscription -> IO a) -> IO (Either McpError a)
withSubscription c flt k = guarded c $ case (c.description.era, c.wire.binding.openStream) of
  (Modern v, Just openIt) -> mask $ \restore -> do
    opened <- restore (withDeadline c.wire.config.limits.requestTimeout (openListen v openIt))
    case opened of
      Left e -> pure (Left e)
      Right sub -> do
        key <- atomicModifyIORef' c.listenerSeq (\n -> (n + 1, n + 1))
        let closeIt = do
              _ <- atomicModifyIORef' sub.ended (\e -> (Just (fromMaybe EndedByClient e), ()))
              sub.stream.close
        atomicModifyIORef' c.listeners (\m -> (Map.insert key closeIt m, ()))
        let cleanup = atomicModifyIORef' c.listeners (\m -> (Map.delete key m, ())) >> closeIt
        x <- restore (k sub) `onException` cleanup
        cleanup
        pure (Right x)
  _ -> pure (Left (mcpError UnsupportedOperation NotSent "subscriptions/listen requires a modern connection with a streaming binding"))
  where
    openListen v openIt = do
      let method = "subscriptions/listen"
          params = KeyMap.singleton "notifications" (toJSON flt)
      approved <- approve c.wire.config (attemptFor c.wire PurposeListen method params)
      case approved of
        Left e -> pure (Left e)
        Right extra -> do
          rid <- RequestIdNumber <$> atomicModifyIORef' c.wire.counter (\n -> (n + 1, n + 1))
          phs <- protocolHeaders c.wire (ModeModern v) method params []
          let ex =
                Exchange
                  { requestId = rid,
                    method = method,
                    body = BS.toStrict (Aeson.encode (encodeRequest rid method (withRequestMeta (requestMeta v c.wire.config.clientInfo) params))),
                    headers = phs <> extra,
                    onNotification = \_ _ -> pure (),
                    onServerRequest = \_ _ _ -> pure ()
                  }
          s <- openIt (wireLimits c.wire.config.limits) ex
          case s of
            Left e -> pure (Left e)
            Right ms -> do
              ack <- awaitAck rid ms `onException` ms.close
              case ack of
                Left e -> ms.close >> pure (Left e)
                Right acked -> do
                  e <- newIORef Nothing
                  pure (Right Subscription {sid = rid, requested = flt, acknowledged = acked, stream = ms, ended = e})
    awaitAck rid ms = do
      item <- ms.next
      case item of
        StreamEnded Nothing -> pure (Left (mcpError TransportFailure Uncertain "the subscription stream ended before its acknowledgment"))
        StreamEnded (Just e) -> pure (Left e)
        StreamMessage (IncomingResponse _ (Left e)) -> pure (Left ((mcpError RemoteRpcError Answered ("the server refused the subscription: " <> e.message)) {rpc = Just e}))
        StreamMessage (IncomingResponse _ (Right _)) -> pure (Left (mcpError MalformedReply Answered "the subscription ended before its acknowledgment"))
        StreamMessage (IncomingRequest {}) -> awaitAck rid ms
        StreamMessage (IncomingNotification m p)
          | notificationSubscription p /= Just rid -> awaitAck rid ms
          | m /= "notifications/subscriptions/acknowledged" ->
              pure (Left (mcpError MalformedReply Answered "the server sent a notification before acknowledging the subscription"))
          | otherwise -> case KeyMap.lookup "notifications" p of
              Just v | Right f <- parseEither Aeson.parseJSON v -> pure (Right f)
              _ -> pure (Left (mcpError MalformedReply Answered "the subscription acknowledgment has no readable filter"))

notificationSubscription :: Object -> Maybe RequestId
notificationSubscription p = case KeyMap.lookup "_meta" p of
  Just (Object meta) | Just v <- KeyMap.lookup metaSubscriptionId meta -> either (const Nothing) Just (parseEither Aeson.parseJSON v)
  _ -> Nothing

-- | The next notification the acknowledged filter admits, or the end of
-- the subscription. Notifications for other subscriptions or of types not
-- acknowledged are skipped. Blocks until something arrives.
nextSubscriptionEvent :: Subscription -> IO SubscriptionEvent
nextSubscriptionEvent s = do
  done <- readIORef s.ended
  case done of
    Just e -> pure (SubscriptionEnded e)
    Nothing -> do
      item <- s.stream.next
      done' <- readIORef s.ended
      case (done', item) of
        (Just e, _) -> pure (SubscriptionEnded e)
        (_, StreamEnded Nothing) -> finish Disconnected
        (_, StreamEnded (Just e)) -> finish (EndedWithError e)
        (_, StreamMessage (IncomingResponse rid r))
          | rid == Just s.sid -> finish (either (\e -> EndedWithError ((mcpError RemoteRpcError Answered e.message) {rpc = Just e})) (const EndedGracefully) r)
          | otherwise -> nextSubscriptionEvent s
        (_, StreamMessage (IncomingRequest {})) -> nextSubscriptionEvent s
        (_, StreamMessage (IncomingNotification m p))
          | m == "notifications/cancelled",
            either (const Nothing) Just (maybe (Left "") (parseEither Aeson.parseJSON) (KeyMap.lookup "requestId" p)) == Just s.sid ->
              finish EndedByServer
          | notificationSubscription p /= Just s.sid -> nextSubscriptionEvent s
          | m `elem` subscriptionNotificationMethods s.acknowledged -> pure (SubscriptionNotification m p)
          | otherwise -> nextSubscriptionEvent s
  where
    finish e = do
      writeIORef s.ended (Just e)
      s.stream.close
      pure (SubscriptionEnded e)