packages feed

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

-- | Remote MCP tools: discovery, descriptor-bound invocation and rich
-- results.
--
-- A discovered 'McpTool' keeps the server's native name, its input schema
-- exactly as sent, an optional output schema and every other field. A call
-- binds one such descriptor ('McpToolCall'), so the parameter headers
-- mirrored on the wire and the output contract checked afterwards come
-- from the schema the host approved — never from a list fetched later.
--
-- Four outcomes stay distinct: a completed result (which may itself report
-- a tool failure through @isError@), an unfinished interim result returned
-- by "Baikai.Mcp.Client", a refusal or transport failure whose 'Delivery'
-- says whether the tool may have run, and a descriptor-drift rejection
-- (@-32020@) that the host resolves by listing tools again. Nothing here
-- retries a call or swaps a descriptor.
module Baikai.Mcp.Tool
  ( -- * Descriptors
    McpTool (..),
    HeaderMirror (..),
    RejectedTool (..),
    decodeTool,
    toBaikaiTool,

    -- * Discovery
    ToolPage (..),
    listToolsPage,
    ToolListing (..),
    listTools,

    -- * Invocation
    McpToolCall (..),
    mcpToolCall,
    ContentBlock (..),
    StructuredContent (..),
    OutputCheck (..),
    McpToolResult (..),
    McpToolError (..),
    callTool,
    callToolWith,
    CallToolOptions (..),
    defaultCallToolOptions,

    -- * Projection into Baikai messages
    ToolResultProjection (..),
    projectToolResult,
    toolResultMessageFor,

    -- * Change notifications
    ToolListChange (..),
    withToolListChanges,
    nextToolListChange,
  )
where

import Baikai.Content (ImageContent (..), TextContent (..), ToolResultContent (..))
import Baikai.Mcp.Client
import Baikai.Mcp.Content
import Baikai.Mcp.JsonSchema
import Baikai.Mcp.Protocol
import Baikai.Mcp.Transport (ParamHeader, paramHeader, validParamName)
import Baikai.Message (Message, ToolResult (..), toolResultMessage)
import Baikai.Tool (Tool, mkTool)
import Data.Aeson (Value (..))
import Data.Aeson qualified as Aeson
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Aeson.Types (Object)
import Data.ByteString.Base64 qualified as B64
import Data.ByteString.Lazy qualified as LBS
import Data.Char (toLower)
import Data.Foldable (toList)
import Data.List (nub)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Text.Encoding qualified as TE
import Data.Vector qualified as Vector
import GHC.Generics (Generic)

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

-- | A validated @x-mcp-header@ annotation: the header name portion and the
-- chain of property names leading to the annotated argument.
data HeaderMirror = HeaderMirror
  { headerName :: !Text,
    propertyPath :: ![Text]
  }
  deriving stock (Eq, Show, Generic)

-- | A tool as the server described it.
data McpTool = McpTool
  { -- | The server's own name, sent verbatim on invocation.
    name :: !Text,
    title :: !(Maybe Text),
    description :: !(Maybe Text),
    -- | The input JSON Schema, unchanged.
    inputSchema :: !Value,
    -- | The output JSON Schema, of any root type, when declared.
    outputSchema :: !(Maybe Value),
    annotations :: !(Maybe Object),
    -- | Parameter mirrors this connection must send (modern HTTP only).
    headerMirrors :: ![HeaderMirror],
    -- | The descriptor object as received.
    raw :: !Object
  }
  deriving stock (Eq, Show, Generic)

-- | A descriptor left out of a listing, and why.
data RejectedTool = RejectedTool
  { toolName :: !(Maybe Text),
    reason :: !Text
  }
  deriving stock (Eq, Show, Generic)

-- | Decode a descriptor. With @checkMirrors@ (modern Streamable HTTP) the
-- @x-mcp-header@ annotations are validated and a tool with an invalid one
-- is rejected; on other bindings they are ignored, as the specification
-- allows.
decodeTool :: Bool -> Value -> Either RejectedTool McpTool
decodeTool checkMirrors = \case
  Object o -> do
    nm <- case KeyMap.lookup "name" o of
      Just (String n) | not (Text.null n) -> Right n
      _ -> Left (RejectedTool Nothing "the descriptor has no name")
    let reject :: forall a. Text -> Either RejectedTool a
        reject why = Left (RejectedTool (Just nm) why)
        optText k = case KeyMap.lookup k o of
          Just (String t) -> Right (Just t)
          Nothing -> Right Nothing
          Just Null -> Right Nothing
          Just _ -> reject (Key.toText k <> " must be a string")
    ttl <- optText "title"
    desc <- optText "description"
    input <- case KeyMap.lookup "inputSchema" o of
      Just s@(Object so) -> case KeyMap.lookup "type" so of
        Just (String "object") -> Right s
        _ -> reject "inputSchema must have type \"object\""
      _ -> reject "inputSchema must be an object"
    output <- case KeyMap.lookup "outputSchema" o of
      Nothing -> Right Nothing
      Just Null -> Right Nothing
      Just s@(Object _) -> Right (Just s)
      Just s@(Bool _) -> Right (Just s)
      Just _ -> reject "outputSchema must be a schema"
    anns <- case KeyMap.lookup "annotations" o of
      Just (Object a) -> Right (Just a)
      Nothing -> Right Nothing
      Just Null -> Right Nothing
      Just _ -> reject "annotations must be an object"
    mirrors <-
      if checkMirrors
        then either reject Right (headerMirrorsOf input)
        else Right []
    Right
      McpTool
        { name = nm,
          title = ttl,
          description = desc,
          inputSchema = input,
          outputSchema = output,
          annotations = anns,
          headerMirrors = mirrors,
          raw = o
        }
  _ -> Left (RejectedTool Nothing "the descriptor is not an object")

-- | Find and validate every @x-mcp-header@ in an input schema. An
-- annotation is valid only where a chain of @properties@ keys reaches it
-- from the root, on a property typed @string@, @integer@ or @boolean@,
-- with a valid and case-insensitively unique token.
headerMirrorsOf :: Value -> Either Text [HeaderMirror]
headerMirrorsOf schema = do
  found <- walk True [] schema
  let lowered = map (Text.map toLower . (.headerName)) found
  if length (nub lowered) /= length lowered
    then Left "x-mcp-header names are not case-insensitively unique"
    else Right found
  where
    -- @static@: reached from the root through properties keys only.
    walk :: Bool -> [Text] -> Value -> Either Text [HeaderMirror]
    walk static path = \case
      Object o -> do
        here <- case KeyMap.lookup "x-mcp-header" o of
          Nothing -> Right []
          Just ann
            | not static || null path -> Left "x-mcp-header is not on a statically reachable property"
            | otherwise -> do
                hname <- case ann of
                  String h | validParamName h -> Right h
                  _ -> Left "an x-mcp-header value is not a valid HTTP token"
                case KeyMap.lookup "type" o of
                  Just (String t) | t `elem` ["string", "integer", "boolean"] -> Right ()
                  _ -> Left ("x-mcp-header " <> hname <> " is on a property that is not a string, integer or boolean")
                Right [HeaderMirror {headerName = hname, propertyPath = reverse path}]
        nested <- fmap concat . traverse (descend o) $ KeyMap.toList o
        Right (here <> nested)
      Array xs -> concat <$> traverse (walk False path) (toList xs)
      _ -> Right []
      where
        descend _ (k, v) = case Key.toText k of
          "x-mcp-header" -> Right []
          "properties" -> case v of
            Object props -> concat <$> traverse (\(pk, ps) -> walk static (Key.toText pk : path) ps) (KeyMap.toList props)
            _ -> walk False path v
          _ -> walk False path v

-- | The model-facing tool. The input schema is passed through verbatim;
-- only the description is defaulted (to the title, else empty).
toBaikaiTool :: McpTool -> Tool
toBaikaiTool t = mkTool t.name (fromMaybe (fromMaybe "" t.title) t.description) t.inputSchema

-- ---------------------------------------------------------------------------
-- Discovery

-- | One @tools/list@ page and the descriptors excluded from it.
data ToolPage = ToolPage
  { page :: !(Page McpTool),
    rejected :: ![RejectedTool]
  }
  deriving stock (Eq, Show, Generic)

checksMirrors :: McpConnection -> Bool
checksMirrors c = isModern (connectionEra c) && connectionBindingShape c == RequestScopedHttp

-- | Request one page. The host's hook sees the cursor of every page after
-- the first and may refuse it before anything is sent.
listToolsPage :: McpConnection -> Maybe Cursor -> IO (Either McpError ToolPage)
listToolsPage c cur = do
  r <- requestPage c "tools/list" "tools" (pure . decodeTool (checksMirrors c)) cur
  pure $ flip fmap r $ \p ->
    ToolPage
      { page = p {items = [t | Right t <- p.items]},
        rejected = [x | Left x <- p.items]
      }

-- | Every tool, in server order, under the drain's ceilings.
data ToolListing = ToolListing
  { tools :: ![McpTool],
    rejected :: ![RejectedTool]
  }
  deriving stock (Eq, Show, Generic)

-- | List all pages. A failure, a repeated cursor or an exceeded limit
-- discards the partial listing.
listTools :: McpConnection -> DrainLimits -> IO (Either (DrainFailure McpError) ToolListing)
listTools c lim = do
  r <- drainPages lim $ \cur -> do
    p <- listToolsPage c cur
    pure $ flip fmap p $ \tp -> tp.page {items = map Right tp.page.items <> map Left tp.rejected}
  pure $ flip fmap r $ \xs -> ToolListing {tools = [t | Right t <- xs], rejected = [x | Left x <- xs]}

-- ---------------------------------------------------------------------------
-- Results

-- | Structured content keeps a present @null@ distinct from absence.
data StructuredContent
  = NoStructuredContent
  | StructuredContent !Value
  deriving stock (Eq, Show, Generic)

-- | What was established about the structured result.
data OutputCheck
  = -- | The tool declares no output schema.
    NoOutputSchema
  | OutputConforms
  | -- | The tool reported an execution error; no contract applies.
    NotCheckedToolError
  deriving stock (Eq, Show, Generic)

data McpToolResult = McpToolResult
  { content :: ![ContentBlock],
    structured :: !StructuredContent,
    isError :: !Bool,
    outputCheck :: !OutputCheck,
    -- | The result object as received.
    raw :: !Object,
    continuationRounds :: !Int
  }
  deriving stock (Eq, Show, Generic)

data McpToolError
  = -- | The request failed; 'Delivery' says whether the tool may have run.
    ToolRequestFailed !McpError
  | -- | The server rejected the call's routing headers (@-32020@) before
    -- running it, usually because the tool's schema changed. List tools
    -- again and decide whether the new descriptor is still approved.
    ToolDescriptorDrift !McpError
  | -- | The arguments cannot be mirrored into the headers the descriptor
    -- requires. Nothing was sent.
    ToolArgumentsUnmirrorable !Text
  | -- | The tool ran, but its structured output breaks the declared
    -- contract. The result is kept for inspection.
    ToolOutputViolatesSchema ![SchemaViolation] !McpToolResult
  | -- | The tool ran, but its output contract could not be checked: the
    -- schema uses unsupported features or exceeds the evaluation budget,
    -- or structured content is missing.
    ToolOutputUnverifiable !Text !McpToolResult
  | -- | The result is not a tool result.
    ToolResultMalformed !Text
  deriving stock (Eq, Show, Generic)

-- ---------------------------------------------------------------------------
-- Invocation

-- | A call bound to the descriptor it was approved against.
data McpToolCall = McpToolCall
  { tool :: !McpTool,
    arguments :: !Object
  }
  deriving stock (Eq, Show, Generic)

mcpToolCall :: McpTool -> Object -> McpToolCall
mcpToolCall t args = McpToolCall {tool = t, arguments = args}

data CallToolOptions = CallToolOptions
  { schemaBudget :: !SchemaBudget,
    -- | Receives request-scoped notifications such as progress.
    onNotification :: !(Maybe (Text -> Object -> IO ()))
  }

defaultCallToolOptions :: CallToolOptions
defaultCallToolOptions = CallToolOptions {schemaBudget = defaultSchemaBudget, onNotification = Nothing}

callTool :: McpConnection -> McpToolCall -> IO (Either McpToolError (McpOutcome McpToolResult))
callTool c = callToolWith c defaultCallToolOptions

-- | Invoke a bound tool. A state-only interim result is continued by the
-- client with the same name, arguments and header mirrors on every round.
callToolWith :: McpConnection -> CallToolOptions -> McpToolCall -> IO (Either McpToolError (McpOutcome McpToolResult))
callToolWith c opts call = case mirrorHeaders of
  Left why -> pure (Left (ToolArgumentsUnmirrorable why))
  Right hs -> do
    let params = KeyMap.fromList [("name", String call.tool.name), ("arguments", Object call.arguments)]
        req = (mcpCall "tools/call" params) {paramHeaders = hs, onNotification = opts.onNotification}
    r <- callInteractive c req
    pure $ case r of
      Left e
        | fmap (.code) e.rpc == Just headerMismatch -> Left (ToolDescriptorDrift e)
        | otherwise -> Left (ToolRequestFailed e)
      Right (McpUnfinished u) -> Right (McpUnfinished u)
      Right (McpCompleted cr) -> McpCompleted <$> interpret opts call.tool cr
  where
    mirrorHeaders :: Either Text [ParamHeader]
    mirrorHeaders
      | not (checksMirrors c) = Right []
      | otherwise = fmap concat . traverse mirror $ call.tool.headerMirrors
    mirror m = maybe [] pure <$> paramHeader m.headerName (lookupPath m.propertyPath (Object call.arguments))
    lookupPath [] v = Just v
    lookupPath (k : ks) (Object o) = KeyMap.lookup (Key.fromText k) o >>= lookupPath ks
    lookupPath _ _ = Nothing

interpret :: CallToolOptions -> McpTool -> CompleteResult -> Either McpToolError McpToolResult
interpret opts t cr = do
  blocks <- case KeyMap.lookup "content" cr.result of
    Just (Array xs) -> Right (map decodeContentBlock (toList xs))
    Nothing -> Right []
    Just _ -> Left (ToolResultMalformed "content must be an array")
  err <- case KeyMap.lookup "isError" cr.result of
    Nothing -> Right False
    Just (Bool b) -> Right b
    Just _ -> Left (ToolResultMalformed "isError must be a boolean")
  let structured = maybe NoStructuredContent StructuredContent (KeyMap.lookup "structuredContent" cr.result)
      base =
        McpToolResult
          { content = blocks,
            structured = structured,
            isError = err,
            outputCheck = NoOutputSchema,
            raw = cr.result,
            continuationRounds = cr.continuationRounds
          }
  case (err, t.outputSchema) of
    (True, _) -> Right base {outputCheck = NotCheckedToolError}
    (False, Nothing) -> Right base
    (False, Just schema) -> case structured of
      NoStructuredContent -> Left (ToolOutputUnverifiable "the tool declares an output schema but returned no structured content" base)
      StructuredContent v -> case validateJson opts.schemaBudget schema v of
        Conforms -> Right base {outputCheck = OutputConforms}
        Violates vs -> Left (ToolOutputViolatesSchema vs base)
        Unverifiable why -> Left (ToolOutputUnverifiable why base)

-- ---------------------------------------------------------------------------
-- Projection

-- | A tool result as a Baikai tool result, with what could not be carried.
data ToolResultProjection = ToolResultProjection
  { toolResult :: !ToolResult,
    -- | Blocks Baikai's tool results cannot represent (audio, resources,
    -- unknown types, undecodable images). Never silently dropped.
    unprojected :: ![ContentBlock]
  }
  deriving stock (Eq, Show, Generic)

-- | Project text and images. When the result has no content blocks but
-- carries structured content, that content is rendered as one JSON text
-- block, as the specification asks servers to do themselves.
projectToolResult :: McpToolResult -> ToolResultProjection
projectToolResult r =
  ToolResultProjection
    { toolResult = ToolResult {content = Vector.fromList (projected <> structuredText), isError = r.isError},
      unprojected = [b | (b, Nothing) <- zip r.content (map project r.content)]
    }
  where
    projected = [x | Just x <- map project r.content]
    structuredText = case (r.content, r.structured) of
      ([], StructuredContent v) -> [ToolResultText (TextContent (TE.decodeUtf8 (LBS.toStrict (Aeson.encode v))))]
      _ -> []
    project = \case
      TextBlock t -> Just (ToolResultText (TextContent t))
      ImageBlock d m -> case B64.decode (TE.encodeUtf8 d) of
        Right bytes -> Just (ToolResultImage (ImageContent bytes m))
        Left _ -> Nothing
      _ -> Nothing

-- | The tool-result message answering a model's tool call. The caller
-- supplies the model's tool-call identifier and the name the model used.
toolResultMessageFor :: Text -> Text -> McpToolResult -> (Message, [ContentBlock])
toolResultMessageFor callId modelName r =
  let p = projectToolResult r
   in (toolResultMessage callId modelName p.toolResult, p.unprojected)

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

data ToolListChange
  = -- | The server reported that its tool list changed. Nothing has been
    -- fetched; list again when the owner decides to.
    ToolListChanged
  | ToolListStreamEnded !SubscriptionEnd
  deriving stock (Eq, Show, Generic)

-- | Listen for @notifications/tools/list_changed@ on a modern connection.
-- The action receives the subscription; the acknowledged filter says
-- whether the server agreed to send tool changes at all.
withToolListChanges :: McpConnection -> (Subscription -> IO a) -> IO (Either McpError a)
withToolListChanges c = withSubscription c emptySubscriptionFilter {toolsListChanged = True}

nextToolListChange :: Subscription -> IO ToolListChange
nextToolListChange s = do
  ev <- nextSubscriptionEvent s
  case ev of
    SubscriptionNotification "notifications/tools/list_changed" _ -> pure ToolListChanged
    SubscriptionNotification _ _ -> nextToolListChange s
    SubscriptionEnded e -> pure (ToolListStreamEnded e)