packages feed

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

-- | Remote MCP resources: listing, templates, reads and optional change
-- notifications.
--
-- A resource is identified by a URI, which is not assumed to be a file
-- path. A read returns every content item the server sent, each with its
-- own URI and MIME type, as text or decoded bytes. The application decides
-- what to read and whether any of it enters a model's context; nothing
-- here follows a link or reads a URI on its own.
module Baikai.Mcp.Resource
  ( -- * Descriptors
    McpResource (..),
    McpResourceTemplate (..),

    -- * Listing
    listResources,
    listAllResources,
    listResourceTemplates,
    listAllResourceTemplates,

    -- * Reading
    ResourceContents (..),
    ResourceBody (..),
    ResourceRead (..),
    ReadOptions (..),
    defaultReadOptions,
    ResourceError (..),
    readResource,
    readResourceWith,

    -- * Change notifications
    ResourceEvent (..),
    withResourceUpdates,
    nextResourceEvent,
  )
where

import Baikai.Mcp.Client
import Baikai.Mcp.Protocol
import Data.Aeson (Value (..))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object, Parser, withObject, (.:), (.:?))
import Data.ByteString (ByteString)
import Data.ByteString.Base64 qualified as B64
import Data.Foldable (toList)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TE
import GHC.Generics (Generic)

-- ---------------------------------------------------------------------------
-- Descriptors

data McpResource = McpResource
  { uri :: !Text,
    name :: !Text,
    title :: !(Maybe Text),
    description :: !(Maybe Text),
    mimeType :: !(Maybe Text),
    size :: !(Maybe Integer),
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

-- | A family of resources addressed by an RFC 6570 URI template.
data McpResourceTemplate = McpResourceTemplate
  { uriTemplate :: !Text,
    name :: !Text,
    title :: !(Maybe Text),
    description :: !(Maybe Text),
    mimeType :: !(Maybe Text),
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

resourceParser :: Value -> Parser McpResource
resourceParser = withObject "Resource" $ \o ->
  McpResource
    <$> o .: "uri"
    <*> o .: "name"
    <*> o .:? "title"
    <*> o .:? "description"
    <*> o .:? "mimeType"
    <*> o .:? "size"
    <*> pure o

templateParser :: Value -> Parser McpResourceTemplate
templateParser = withObject "ResourceTemplate" $ \o ->
  McpResourceTemplate
    <$> o .: "uriTemplate"
    <*> o .: "name"
    <*> o .:? "title"
    <*> o .:? "description"
    <*> o .:? "mimeType"
    <*> pure o

-- ---------------------------------------------------------------------------
-- Listing

-- | One page of @resources/list@.
listResources :: McpConnection -> Maybe Cursor -> IO (Either McpError (Page McpResource))
listResources c = requestPage c "resources/list" "resources" resourceParser

listAllResources :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) [McpResource])
listAllResources c lim = drainPages lim (listResources c)

-- | One page of @resources/templates/list@.
listResourceTemplates :: McpConnection -> Maybe Cursor -> IO (Either McpError (Page McpResourceTemplate))
listResourceTemplates c = requestPage c "resources/templates/list" "resourceTemplates" templateParser

listAllResourceTemplates :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) [McpResourceTemplate])
listAllResourceTemplates c lim = drainPages lim (listResourceTemplates c)

-- ---------------------------------------------------------------------------
-- Reading

-- | One item of a read: its own URI and MIME type and either text or
-- decoded bytes.
data ResourceContents = ResourceContents
  { uri :: !Text,
    mimeType :: !(Maybe Text),
    body :: !ResourceBody,
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

data ResourceBody
  = TextBody !Text
  | BlobBody !ByteString
  deriving stock (Eq, Show, Generic)

data ResourceRead = ResourceRead
  { -- | Every item, in server order. May be empty for an existing
    -- resource with no content.
    contents :: ![ResourceContents],
    -- | 'Nothing' for a result reached through continuation rounds.
    cache :: !(Maybe CacheHint),
    continuationRounds :: !Int,
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

newtype ReadOptions = ReadOptions
  { -- | Refuse a blob whose Base64 text is longer than this, before
    -- decoding it.
    maxBlobChars :: Int
  }

defaultReadOptions :: ReadOptions
defaultReadOptions = ReadOptions {maxBlobChars = 8 * 1024 * 1024}

data ResourceError
  = -- | The server reported that the resource does not exist (@-32602@
    -- naming the URI, or the historical @-32002@).
    ResourceNotFound !McpError
  | ResourceRequestFailed !McpError
  | -- | The result is not a readable resource result.
    ResourceMalformed !Text
  deriving stock (Eq, Show, Generic)

readResource :: McpConnection -> Text -> IO (Either ResourceError (McpOutcome ResourceRead))
readResource c = readResourceWith c defaultReadOptions

-- | Read one URI. A state-only interim result is continued by the client.
readResourceWith :: McpConnection -> ReadOptions -> Text -> IO (Either ResourceError (McpOutcome ResourceRead))
readResourceWith c opts target = do
  r <- callInteractive c (mcpCall "resources/read" (KeyMap.singleton "uri" (String target)))
  pure $ case r of
    Left e
      | notFound e -> Left (ResourceNotFound e)
      | otherwise -> Left (ResourceRequestFailed e)
    Right (McpUnfinished u) -> Right (McpUnfinished u)
    Right (McpCompleted cr) -> McpCompleted <$> decodeRead opts cr
  where
    notFound e = case e.rpc of
      Just err
        | err.code == legacyResourceNotFound -> True
        | err.code == invalidParams -> case err.errorData of
            Just (Object d) -> KeyMap.lookup "uri" d == Just (String target)
            _ -> False
      _ -> False

decodeRead :: ReadOptions -> CompleteResult -> Either ResourceError ResourceRead
decodeRead opts cr = do
  items <- case KeyMap.lookup "contents" cr.result of
    Just (Array xs) -> traverse item (toList xs)
    _ -> Left (ResourceMalformed "contents must be an array")
  Right ResourceRead {contents = items, cache = cr.cache, continuationRounds = cr.continuationRounds, raw = cr.result}
  where
    item = \case
      Object o -> do
        u <- case KeyMap.lookup "uri" o of
          Just (String s) -> Right s
          _ -> Left (ResourceMalformed "a content item has no uri")
        let mt = case KeyMap.lookup "mimeType" o of
              Just (String m) -> Just m
              _ -> Nothing
        case (KeyMap.lookup "text" o, KeyMap.lookup "blob" o) of
          (Just (String t), Nothing) -> Right ResourceContents {uri = u, mimeType = mt, body = TextBody t, raw = o}
          (Nothing, Just (String b))
            | Text.length b > opts.maxBlobChars -> Left (ResourceMalformed "a blob exceeds the configured size limit")
            | otherwise -> case B64.decode (TE.encodeUtf8 b) of
                Right bs -> Right ResourceContents {uri = u, mimeType = mt, body = BlobBody bs, raw = o}
                Left _ -> Left (ResourceMalformed "a blob is not valid Base64")
          _ -> Left (ResourceMalformed "a content item must carry exactly one of text and blob")
      _ -> Left (ResourceMalformed "a content item is not an object")

-- ---------------------------------------------------------------------------
-- Change notifications

data ResourceEvent
  = -- | A subscribed resource changed; read it again when appropriate.
    ResourceUpdated !Text
  | ResourceListChanged
  | ResourceStreamEnded !SubscriptionEnd
  deriving stock (Eq, Show, Generic)

-- | Listen for updates to the given URIs and, optionally, list changes,
-- on a modern connection. The acknowledged filter may be a subset.
withResourceUpdates :: McpConnection -> [Text] -> Bool -> (Subscription -> IO a) -> IO (Either McpError a)
withResourceUpdates c uris listChanges =
  withSubscription c emptySubscriptionFilter {resourceSubscriptions = uris, resourcesListChanged = listChanges}

nextResourceEvent :: Subscription -> IO ResourceEvent
nextResourceEvent s = do
  ev <- nextSubscriptionEvent s
  case ev of
    SubscriptionNotification "notifications/resources/updated" p
      | Just (String u) <- KeyMap.lookup "uri" p -> pure (ResourceUpdated u)
    SubscriptionNotification "notifications/resources/list_changed" _ -> pure ResourceListChanged
    SubscriptionNotification _ _ -> nextResourceEvent s
    SubscriptionEnded e -> pure (ResourceStreamEnded e)