packages feed

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

-- | Bounded JSON Schema 2020-12 validation for MCP tool output.
--
-- MCP schemas default to JSON Schema 2020-12 and may use composition and
-- local references. A schema comes from a remote server, so evaluation is
-- bounded: every keyword and every subschema application spends one unit
-- of a fuel budget, nesting is capped, and a budget that runs out yields
-- 'Unverifiable' rather than an answer. Nothing is ever fetched: a
-- reference that does not point into the same document is 'Unverifiable'.
--
-- The validation and applicator vocabularies are implemented. Keywords
-- whose semantics this module does not implement — @$dynamicRef@,
-- @unevaluatedProperties@, @unevaluatedItems@, references to anchors,
-- nested @$id@, a dialect other than 2020-12, and @pattern@ syntax outside
-- the portable subset (no look-around, back-references or Unicode
-- property classes) — make the verdict 'Unverifiable' instead of being
-- ignored, so an unsupported contract is never reported as satisfied.
-- @format@ and the @content*@ keywords are annotations, as 2020-12
-- specifies by default.
module Baikai.Mcp.JsonSchema
  ( SchemaBudget (..),
    defaultSchemaBudget,
    SchemaVerdict (..),
    SchemaViolation (..),
    validateJson,
  )
where

import Data.Aeson (Value (..))
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Char (chr, isDigit, isHexDigit)
import Data.Foldable (toList)
import Data.List (nub)
import Data.Ratio (denominator)
import Data.Scientific (Scientific, base10Exponent, floatingOrInteger, isInteger)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Vector qualified as Vector
import GHC.Generics (Generic)
import Numeric (readHex)
import Text.Regex.TDFA (CompOption (..), Regex, defaultCompOpt, defaultExecOpt, makeRegexOptsM, matchTest)

data SchemaBudget = SchemaBudget
  { -- | Keyword evaluations and subschema applications allowed.
    maxSteps :: !Int,
    -- | Nested subschema applications allowed.
    maxDepth :: !Int,
    -- | Violations reported at most.
    maxViolations :: !Int
  }
  deriving stock (Eq, Show, Generic)

defaultSchemaBudget :: SchemaBudget
defaultSchemaBudget = SchemaBudget {maxSteps = 200000, maxDepth = 64, maxViolations = 16}

data SchemaViolation = SchemaViolation
  { -- | JSON Pointer to the offending part of the instance.
    instancePath :: !Text,
    keyword :: !Text,
    detail :: !Text
  }
  deriving stock (Eq, Show, Generic)

data SchemaVerdict
  = Conforms
  | Violates ![SchemaViolation]
  | -- | The schema could not be evaluated within budget or uses something
    -- this validator does not implement.
    Unverifiable !Text
  deriving stock (Eq, Show, Generic)

-- ---------------------------------------------------------------------------
-- Evaluation monad: fuel and early stop

data Stop = StopUnsupported Text | StopBudget Text

newtype Eval a = Eval {runEval :: Int -> Either Stop (a, Int)}

instance Functor Eval where
  fmap f (Eval g) = Eval $ \n -> case g n of
    Left s -> Left s
    Right (a, n') -> Right (f a, n')

instance Applicative Eval where
  pure a = Eval $ \n -> Right (a, n)
  Eval f <*> Eval g = Eval $ \n -> case f n of
    Left s -> Left s
    Right (h, n') -> case g n' of
      Left s -> Left s
      Right (a, n'') -> Right (h a, n'')

instance Monad Eval where
  Eval g >>= k = Eval $ \n -> case g n of
    Left s -> Left s
    Right (a, n') -> runEval (k a) n'

tick :: Eval ()
tick = Eval $ \n -> if n <= 0 then Left (StopBudget "the schema evaluation budget was exhausted") else Right ((), n - 1)

unsupported :: Text -> Eval a
unsupported why = Eval (const (Left (StopUnsupported why)))

data Ctx = Ctx {root :: !Value, depth :: !Int, budget :: !SchemaBudget}

-- | Validate an instance against a schema document.
validateJson :: SchemaBudget -> Value -> Value -> SchemaVerdict
validateJson b schema inst =
  case checkRoot schema of
    Just why -> Unverifiable why
    Nothing -> case runEval (validate (Ctx schema 0 b) [] schema inst) b.maxSteps of
      Left (StopUnsupported why) -> Unverifiable why
      Left (StopBudget why) -> Unverifiable why
      Right ([], _) -> Conforms
      Right (vs, _) -> Violates (take b.maxViolations vs)

checkRoot :: Value -> Maybe Text
checkRoot = \case
  Object o -> case KeyMap.lookup "$schema" o of
    Nothing -> Nothing
    Just (String s)
      | s `elem` ["https://json-schema.org/draft/2020-12/schema", "https://json-schema.org/draft/2020-12/schema#"] -> Nothing
      | otherwise -> Just ("the schema dialect " <> Text.take 80 s <> " is not supported")
    Just _ -> Just "$schema must be a string"
  Bool _ -> Nothing
  _ -> Just "a schema must be an object or a boolean"

type Path = [Text]

pointer :: Path -> Text
pointer [] = ""
pointer ps = Text.concat (map (\p -> "/" <> Text.replace "/" "~1" (Text.replace "~" "~0" p)) (reverse ps))

violation :: Path -> Text -> Text -> [SchemaViolation]
violation p k d = [SchemaViolation {instancePath = pointer p, keyword = k, detail = d}]

unsupportedKeywords :: [Text]
unsupportedKeywords = ["$dynamicRef", "$dynamicAnchor", "$recursiveRef", "$recursiveAnchor", "unevaluatedProperties", "unevaluatedItems"]

validate :: Ctx -> Path -> Value -> Value -> Eval [SchemaViolation]
validate ctx path schema inst = do
  tick
  if ctx.depth > ctx.budget.maxDepth
    then Eval (const (Left (StopBudget "the schema nests too deeply")))
    else case schema of
      Bool True -> pure []
      Bool False -> pure (violation path "false" "no value is allowed here")
      Object o -> do
        mapM_ (\k -> if Key.toText k `elem` unsupportedKeywords then unsupported ("the keyword " <> Key.toText k <> " is not supported") else pure ()) (KeyMap.keys o)
        case KeyMap.lookup "$id" o of
          Just _ | ctx.depth > 0 -> unsupported "nested $id is not supported"
          _ -> pure ()
        case KeyMap.lookup "$schema" o of
          Just _ | ctx.depth > 0 -> unsupported "a nested $schema is not supported"
          _ -> pure ()
        let ctx' = ctx {depth = ctx.depth + 1}
        concat
          <$> sequence
            [ refKeyword ctx' path o inst,
              typeKeyword path o inst,
              enumKeywords path o inst,
              numberKeywords path o inst,
              stringKeywords path o inst,
              arrayKeywords ctx' path o inst,
              objectKeywords ctx' path o inst,
              combinators ctx' path o inst
            ]
      _ -> unsupported "a subschema must be an object or a boolean"

-- | Apply a subschema; True when it holds.
holds :: Ctx -> Path -> Value -> Value -> Eval Bool
holds ctx p s v = null <$> validate ctx p s v

refKeyword :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
refKeyword ctx path o inst = case KeyMap.lookup "$ref" o of
  Nothing -> pure []
  Just (String ref) -> case resolvePointer ctx.root ref of
    Left why -> unsupported why
    Right target -> validate ctx path target inst
  Just _ -> unsupported "$ref must be a string"

-- | Resolve a same-document reference (@#@ followed by a JSON Pointer).
resolvePointer :: Value -> Text -> Either Text Value
resolvePointer root ref
  | not ("#" `Text.isPrefixOf` ref) = Left ("the reference " <> Text.take 80 ref <> " is not local and is never fetched")
  | otherwise =
      let frag = percentDecode (Text.drop 1 ref)
       in if Text.null frag
            then Right root
            else
              if not ("/" `Text.isPrefixOf` frag)
                then Left "references to anchors are not supported"
                else walk root (map unescape (drop 1 (Text.splitOn "/" frag)))
  where
    unescape = Text.replace "~0" "~" . Text.replace "~1" "/"
    walk v [] = Right v
    walk (Object m) (k : ks) = maybe (Left ("unresolvable reference " <> Text.take 80 ref)) (`walk` ks) (KeyMap.lookup (Key.fromText k) m)
    walk (Array xs) (k : ks)
      | Text.all isDigit k, not (Text.null k), Just x <- xs Vector.!? read (Text.unpack k) = walk x ks
    walk _ _ = Left ("unresolvable reference " <> Text.take 80 ref)

percentDecode :: Text -> Text
percentDecode t = case Text.breakOn "%" t of
  (a, rest)
    | Text.null rest -> a
    | otherwise ->
        let hex = Text.take 2 (Text.drop 1 rest)
         in case readHex (Text.unpack hex) of
              [(n, "")] | Text.length hex == 2, Text.all isHexDigit hex -> a <> Text.singleton (chr n) <> percentDecode (Text.drop 3 rest)
              _ -> a <> "%" <> percentDecode (Text.drop 1 rest)

typeName :: Value -> [Text]
typeName = \case
  Null -> ["null"]
  Bool _ -> ["boolean"]
  String _ -> ["string"]
  Array _ -> ["array"]
  Object _ -> ["object"]
  Number n -> if isInteger n || isWhole n then ["number", "integer"] else ["number"]
  where
    isWhole n = case floatingOrInteger @Double n of
      Right (_ :: Integer) -> True
      Left _ -> False

typeKeyword :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
typeKeyword path o inst = case KeyMap.lookup "type" o of
  Nothing -> pure []
  Just t -> do
    tick
    allowed <- case t of
      String s -> pure [s]
      Array xs -> traverse (\case String s -> pure s; _ -> unsupported "type entries must be strings") (toList xs)
      _ -> unsupported "type must be a string or an array"
    pure $
      if any (`elem` typeName inst) allowed
        then []
        else violation path "type" ("expected " <> Text.intercalate " or " allowed)

enumKeywords :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
enumKeywords path o inst = do
  e <- case KeyMap.lookup "enum" o of
    Nothing -> pure []
    Just (Array xs) -> tick >> pure (if inst `elem` toList xs then [] else violation path "enum" "not one of the allowed values")
    Just _ -> unsupported "enum must be an array"
  c <- case KeyMap.lookup "const" o of
    Nothing -> pure []
    Just v -> tick >> pure (if v == inst then [] else violation path "const" "not the required value")
  pure (e <> c)

numberKeywords :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
numberKeywords path o = \case
  Number n -> concat <$> traverse (check n) ["multipleOf", "maximum", "exclusiveMaximum", "minimum", "exclusiveMinimum"]
  _ -> pure []
  where
    check n k = case KeyMap.lookup (Key.fromText k) o of
      Nothing -> pure []
      Just (Number b) -> do
        tick
        ok <- case k of
          "multipleOf"
            | b <= 0 -> unsupported "multipleOf must be positive"
            | tooLarge n || tooLarge b -> unsupported "a number is too large to check multipleOf"
            | otherwise -> pure (denominator (toRational n / toRational b) == 1)
          "maximum" -> pure (n <= b)
          "exclusiveMaximum" -> pure (n < b)
          "minimum" -> pure (n >= b)
          _ -> pure (n > b)
        pure (if ok then [] else violation path k ("violates " <> k))
      Just _ -> unsupported (k <> " must be a number")
    tooLarge :: Scientific -> Bool
    tooLarge s = abs (base10Exponent s) > 400

stringKeywords :: Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
stringKeywords path o = \case
  String s -> do
    lenV <- concat <$> traverse (lengthCheck s) [("maxLength", (<=)), ("minLength", (>=))]
    patV <- case KeyMap.lookup "pattern" o of
      Nothing -> pure []
      Just (String p) -> do
        tick
        re <- compilePattern p
        pure (if matchTest re (Text.unpack s) then [] else violation path "pattern" "does not match the pattern")
      Just _ -> unsupported "pattern must be a string"
    pure (lenV <> patV)
  _ -> pure []
  where
    lengthCheck s (k, cmp) = case KeyMap.lookup k o of
      Nothing -> pure []
      Just (Number n) | Right i <- floatingOrInteger @Double n -> do
        tick
        pure (if toInteger (Text.length s) `cmp` i then [] else violation path (Key.toText k) ("violates " <> Key.toText k))
      Just _ -> unsupported (Key.toText k <> " must be an integer")

countKeyword :: KeyMap.KeyMap Value -> Key.Key -> Eval (Maybe Integer)
countKeyword o k = case KeyMap.lookup k o of
  Nothing -> pure Nothing
  Just (Number n) | Right i <- floatingOrInteger @Double n -> pure (Just i)
  Just _ -> unsupported (Key.toText k <> " must be an integer")

arrayKeywords :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
arrayKeywords ctx path o = \case
  Array arr -> do
    let xs = toList arr
        n = toInteger (length xs)
    maxI <- countKeyword o "maxItems"
    minI <- countKeyword o "minItems"
    let sizeV =
          [v | Just m <- [maxI], n > m, v <- violation path "maxItems" "too many items"]
            <> [v | Just m <- [minI], n < m, v <- violation path "minItems" "too few items"]
    uniqV <- case KeyMap.lookup "uniqueItems" o of
      Just (Bool True) -> do
        tick
        if n > 2000 then unsupported "uniqueItems over more than 2000 items is not checked" else pure ()
        pure (if length (nub xs) == length xs then [] else violation path "uniqueItems" "items are not unique")
      _ -> pure []
    prefix <- case KeyMap.lookup "prefixItems" o of
      Nothing -> pure []
      Just (Array ps) -> pure (toList ps)
      Just _ -> unsupported "prefixItems must be an array"
    prefixV <- concat <$> sequence [validate ctx (Text.pack (show i) : path) s x | (i, s, x) <- zip3 [0 :: Int ..] prefix xs]
    itemsV <- case KeyMap.lookup "items" o of
      Nothing -> pure []
      Just (Array _) -> unsupported "array-form items is draft-07 syntax, not 2020-12"
      Just s -> concat <$> sequence [validate ctx (Text.pack (show i) : path) s x | (i, x) <- drop (length prefix) (zip [0 :: Int ..] xs)]
    containsV <- case KeyMap.lookup "contains" o of
      Nothing -> pure []
      Just s -> do
        matches <- length . filter id <$> traverse (\(i, x) -> holds ctx (Text.pack (show i) : path) s x) (zip [0 :: Int ..] xs)
        maxC <- countKeyword o "maxContains"
        minC <- countKeyword o "minContains"
        let lo = maybe 1 id minC
            m = toInteger matches
        pure $
          [v | m < lo, v <- violation path "contains" "too few items match contains"]
            <> [v | Just hi <- [maxC], m > hi, v <- violation path "maxContains" "too many items match contains"]
    pure (sizeV <> uniqV <> prefixV <> itemsV <> containsV)
  _ -> pure []

objectKeywords :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
objectKeywords ctx path o = \case
  Object m -> do
    let names = map Key.toText (KeyMap.keys m)
        n = toInteger (length names)
    maxP <- countKeyword o "maxProperties"
    minP <- countKeyword o "minProperties"
    let sizeV =
          [v | Just x <- [maxP], n > x, v <- violation path "maxProperties" "too many properties"]
            <> [v | Just x <- [minP], n < x, v <- violation path "minProperties" "too few properties"]
    required <- case KeyMap.lookup "required" o of
      Nothing -> pure []
      Just (Array rs) -> traverse (\case String r -> pure r; _ -> unsupported "required entries must be strings") (toList rs)
      Just _ -> unsupported "required must be an array"
    let reqV = concat [violation path "required" ("missing property " <> r) | r <- required, r `notElem` names]
    depReqV <- case KeyMap.lookup "dependentRequired" o of
      Nothing -> pure []
      Just (Object deps) ->
        pure
          [ v
          | (k, Array needs) <- KeyMap.toList deps,
            Key.toText k `elem` names,
            String need <- toList needs,
            need `notElem` names,
            v <- violation path "dependentRequired" ("missing property " <> need)
          ]
      Just _ -> unsupported "dependentRequired must be an object"
    props <- case KeyMap.lookup "properties" o of
      Nothing -> pure KeyMap.empty
      Just (Object ps) -> pure ps
      Just _ -> unsupported "properties must be an object"
    patterns <- case KeyMap.lookup "patternProperties" o of
      Nothing -> pure []
      Just (Object ps) -> traverse (\(k, s) -> (,s) <$> compilePattern (Key.toText k)) (KeyMap.toList ps)
      Just _ -> unsupported "patternProperties must be an object"
    propV <- concat <$> sequence [validate ctx (Key.toText k : path) s v | (k, s) <- KeyMap.toList props, Just v <- [KeyMap.lookup k m]]
    patV <- concat <$> sequence [validate ctx (Key.toText k : path) s v | (k, v) <- KeyMap.toList m, (re, s) <- patterns, matchTest re (Text.unpack (Key.toText k))]
    addV <- case KeyMap.lookup "additionalProperties" o of
      Nothing -> pure []
      Just s ->
        concat
          <$> sequence
            [ validate ctx (Key.toText k : path) s v
            | (k, v) <- KeyMap.toList m,
              not (KeyMap.member k props),
              not (any (\(re, _) -> matchTest re (Text.unpack (Key.toText k))) patterns)
            ]
    namesV <- case KeyMap.lookup "propertyNames" o of
      Nothing -> pure []
      Just s -> concat <$> sequence [validate ctx (nm : path) s (String nm) | nm <- names]
    depSchV <- case KeyMap.lookup "dependentSchemas" o of
      Nothing -> pure []
      Just (Object deps) -> concat <$> sequence [validate ctx path s (Object m) | (k, s) <- KeyMap.toList deps, KeyMap.member k m]
      Just _ -> unsupported "dependentSchemas must be an object"
    pure (sizeV <> reqV <> depReqV <> propV <> patV <> addV <> namesV <> depSchV)
  _ -> pure []

combinators :: Ctx -> Path -> KeyMap.KeyMap Value -> Value -> Eval [SchemaViolation]
combinators ctx path o inst = do
  allV <- withList "allOf" $ \ss -> concat <$> traverse (\s -> validate ctx path s inst) ss
  anyV <- withList "anyOf" $ \ss -> do
    oks <- traverse (\s -> holds ctx path s inst) ss
    pure (if or oks then [] else violation path "anyOf" "matches none of the alternatives")
  oneV <- withList "oneOf" $ \ss -> do
    oks <- traverse (\s -> holds ctx path s inst) ss
    pure $ case length (filter id oks) of
      1 -> []
      0 -> violation path "oneOf" "matches none of the alternatives"
      _ -> violation path "oneOf" "matches more than one alternative"
  notV <- case KeyMap.lookup "not" o of
    Nothing -> pure []
    Just s -> do
      ok <- holds ctx path s inst
      pure (if ok then violation path "not" "matches a forbidden schema" else [])
  condV <- case KeyMap.lookup "if" o of
    Nothing -> pure []
    Just s -> do
      ok <- holds ctx path s inst
      case KeyMap.lookup (if ok then "then" else "else") o of
        Nothing -> pure []
        Just branch -> validate ctx path branch inst
  pure (allV <> anyV <> oneV <> notV <> condV)
  where
    withList k f = case KeyMap.lookup k o of
      Nothing -> pure []
      Just (Array ss) | not (null ss) -> f (toList ss)
      Just _ -> unsupported (Key.toText k <> " must be a non-empty array")

-- ---------------------------------------------------------------------------
-- Patterns

-- | Compile an ECMA-262 pattern when it uses only syntax whose meaning is
-- the same under the POSIX engine used here. Searches, not anchored,
-- exactly as JSON Schema specifies.
compilePattern :: Text -> Eval Regex
compilePattern p = do
  tick
  case translate (Text.unpack p) of
    Left why -> unsupported ("the pattern uses " <> why <> ", which is not supported")
    Right posix -> case makeRegexOptsM (defaultCompOpt {multiline = False}) defaultExecOpt posix of
      Nothing -> unsupported "the pattern could not be parsed"
      Just re -> pure re

translate :: String -> Either Text String
translate = go False
  where
    go _ [] = Right []
    go inClass s = case s of
      ('\\' : c : rest) -> (<>) <$> escape inClass c rest <*> go inClass (dropEscapeTail c rest)
      ('(' : '?' : ':' : rest) | not inClass -> ('(' :) <$> go False rest
      ('(' : '?' : _) | not inClass -> Left "a look-around or named group"
      (q : '?' : rest) | not inClass, q `elem` ("*+?}" :: String) -> (q :) <$> go False rest
      ('.' : rest) | not inClass -> ("[^\n\r\x2028\x2029]" <>) <$> go False rest
      ('[' : rest) | not inClass -> ('[' :) <$> go True rest
      (']' : rest) | inClass -> (']' :) <$> go False rest
      (c : rest) -> (c :) <$> go inClass rest
    dropEscapeTail c rest
      | c == 'u' = drop 4 rest
      | c == 'x' = drop 2 rest
      | otherwise = rest
    classBody c = case c of
      'd' -> Right "0-9"
      'w' -> Right "A-Za-z0-9_"
      's' -> Right " \t\n\r\f\v"
      _ -> Left ""
    escape inClass c rest = case c of
      _ | c `elem` ("dws" :: String) -> fmap (\b -> if inClass then b else "[" <> b <> "]") (classBody c)
      _
        | c `elem` ("DWS" :: String) ->
            if inClass
              then Left "a negated class escape inside brackets"
              else fmap (\b -> "[^" <> b <> "]") (classBody (toLowerAscii c))
      'n' -> lit inClass '\n'
      't' -> lit inClass '\t'
      'r' -> lit inClass '\r'
      'f' -> lit inClass '\f'
      'v' -> lit inClass '\v'
      'u' -> case readHex (take 4 rest) of
        [(n, "")] | length (take 4 rest) == 4 -> lit inClass (chr n)
        _ -> Left "a malformed \\u escape"
      'x' -> case readHex (take 2 rest) of
        [(n, "")] | length (take 2 rest) == 2 -> lit inClass (chr n)
        _ -> Left "a malformed \\x escape"
      _ | isDigit c -> Left "a back-reference"
      _ | c `elem` ("bBpPkc" :: String) -> Left ("the escape \\" <> Text.singleton c)
      _ -> lit inClass c
    lit inClass ch
      | inClass, ch `elem` ("]-^" :: String) = Left "an escaped bracket, hyphen or caret inside brackets"
      | otherwise = Right (literal inClass ch)
    literal inClass ch
      | inClass = [ch]
      | ch `elem` (".[]()*+?{}|^$\\" :: String) = ['[', ch, ']']
      | otherwise = [ch]
    toLowerAscii ch = if ch >= 'A' && ch <= 'Z' then toEnum (fromEnum ch + 32) else ch