packages feed

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

-- | Remote MCP prompts: listing, retrieval and explicit projection into
-- Baikai messages.
--
-- A prompt is a server-provided template of ordered user and assistant
-- messages. Retrieving one performs no other IO: embedded resources and
-- resource links stay data. Projection into Baikai messages is a separate,
-- explicit step that reports every block it cannot represent; a prompt can
-- never become a system instruction through this module.
module Baikai.Mcp.Prompt
  ( -- * Descriptors
    McpPrompt (..),
    PromptArgument (..),

    -- * Listing
    listPrompts,
    listAllPrompts,

    -- * Retrieval
    PromptRole (..),
    PromptMessage (..),
    PromptResult (..),
    PromptError (..),
    getPrompt,
    getPromptMap,

    -- * Projection
    PromptProjection (..),
    projectPromptMessage,
  )
where

import Baikai.Content (ImageContent (..), TextContent (..), UserContent (..))
import Baikai.Mcp.Client
import Baikai.Mcp.Content
import Baikai.Mcp.Protocol
import Baikai.Message (Message (..), UserPayload (..), assistant)
import Data.Aeson (Value (..))
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object, Parser, withObject, (.:), (.:?))
import Data.ByteString.Base64 qualified as B64
import Data.Foldable (toList)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.Encoding qualified as TE
import Data.Vector qualified as Vector
import GHC.Generics (Generic)

data PromptArgument = PromptArgument
  { name :: !Text,
    description :: !(Maybe Text),
    required :: !Bool
  }
  deriving stock (Eq, Show, Generic)

data McpPrompt = McpPrompt
  { name :: !Text,
    title :: !(Maybe Text),
    description :: !(Maybe Text),
    arguments :: ![PromptArgument],
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

promptParser :: Value -> Parser McpPrompt
promptParser = withObject "Prompt" $ \o -> do
  args <- fromMaybe [] <$> o .:? "arguments"
  parsedArgs <- traverse argParser args
  McpPrompt <$> o .: "name" <*> o .:? "title" <*> o .:? "description" <*> pure parsedArgs <*> pure o
  where
    argParser = withObject "PromptArgument" $ \a ->
      PromptArgument <$> a .: "name" <*> a .:? "description" <*> (fromMaybe False <$> a .:? "required")

listPrompts :: McpConnection -> Maybe Cursor -> IO (Either McpError (Page McpPrompt))
listPrompts c = requestPage c "prompts/list" "prompts" promptParser

listAllPrompts :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) [McpPrompt])
listAllPrompts c lim = drainPages lim (listPrompts c)

data PromptRole = PromptUser | PromptAssistant
  deriving stock (Eq, Show, Generic)

data PromptMessage = PromptMessage
  { role :: !PromptRole,
    content :: !ContentBlock
  }
  deriving stock (Eq, Show, Generic)

data PromptResult = PromptResult
  { description :: !(Maybe Text),
    -- | In server order.
    messages :: ![PromptMessage],
    continuationRounds :: !Int,
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

data PromptError
  = PromptRequestFailed !McpError
  | PromptMalformed !Text
  deriving stock (Eq, Show, Generic)

-- | Retrieve a prompt by its native name with string arguments.
getPrompt :: McpConnection -> Text -> [(Text, Text)] -> IO (Either PromptError (McpOutcome PromptResult))
getPrompt c nm args = getPromptMap c nm (Map.fromList args)

getPromptMap :: McpConnection -> Text -> Map Text Text -> IO (Either PromptError (McpOutcome PromptResult))
getPromptMap c nm args = do
  let params =
        KeyMap.fromList $
          [("name", String nm)]
            <> [("arguments", Object (KeyMap.fromList [(Key.fromText k, String v) | (k, v) <- Map.toList args])) | not (Map.null args)]
  r <- callInteractive c (mcpCall "prompts/get" params)
  pure $ case r of
    Left e -> Left (PromptRequestFailed e)
    Right (McpUnfinished u) -> Right (McpUnfinished u)
    Right (McpCompleted cr) -> McpCompleted <$> decodePrompt cr

decodePrompt :: CompleteResult -> Either PromptError PromptResult
decodePrompt cr = do
  msgs <- case KeyMap.lookup "messages" cr.result of
    Just (Array xs) -> traverse message (toList xs)
    _ -> Left (PromptMalformed "messages must be an array")
  let desc = case KeyMap.lookup "description" cr.result of
        Just (String d) -> Just d
        _ -> Nothing
  Right PromptResult {description = desc, messages = msgs, continuationRounds = cr.continuationRounds, raw = cr.result}
  where
    message = \case
      Object o -> do
        r <- case KeyMap.lookup "role" o of
          Just (String "user") -> Right PromptUser
          Just (String "assistant") -> Right PromptAssistant
          _ -> Left (PromptMalformed "a prompt message has a role other than user or assistant")
        c <- maybe (Left (PromptMalformed "a prompt message has no content")) Right (KeyMap.lookup "content" o)
        Right PromptMessage {role = r, content = decodeContentBlock c}
      _ -> Left (PromptMalformed "a prompt message is not an object")

-- | A prompt message as a Baikai message, or the reason it cannot be one.
data PromptProjection
  = Projected !Message
  | -- | Baikai has no representation for this role and block; the message
    -- is returned unchanged.
    Unprojectable !PromptMessage
  deriving stock (Eq, Show, Generic)

-- | Project user text and images and assistant text. Audio, resources,
-- links, assistant images and unknown blocks are not projected.
projectPromptMessage :: PromptMessage -> PromptProjection
projectPromptMessage m = case (m.role, m.content) of
  (PromptUser, TextBlock t) -> userWith (UserText (TextContent t))
  (PromptUser, ImageBlock d mt) -> case B64.decode (TE.encodeUtf8 d) of
    Right bytes -> userWith (UserImage (ImageContent bytes mt))
    Left _ -> Unprojectable m
  (PromptAssistant, TextBlock t) -> Projected (assistant t)
  _ -> Unprojectable m
  where
    userWith block = Projected (UserMessage UserPayload {content = Vector.singleton block, timestamp = Nothing})