packages feed

shikumi-tools-0.5.0.0: src/Shikumi/Tool/Mcp.hs

{-# LANGUAGE OverloadedRecordDot #-}

-- | Remote Model Context Protocol (MCP) tools in a shikumi tool registry.
--
-- A caller opens and closes the connection
-- (@mori:\/\/shinzui\/baikai\/packages\/baikai-mcp@); this module never does. It
-- turns the descriptors a server advertises into dynamic tools
-- ('Shikumi.Tool.mkDynToolWith') that a ReAct agent dispatches like any
-- other tool:
--
-- * The model sees an adapter-owned name, @mcp__\<server\>__\<tool\>@, and the
--   tool's input schema exactly as the server sent it. The server receives
--   its own native name and the model's argument object unchanged; the
--   server's validation stays authoritative.
--
-- * A completed result becomes a t'ToolOutput': text and images as native
--   blocks, structured JSON (a present @null@ included) as its own field,
--   every other block as its original JSON. A result the tool marked
--   @isError@ stays an error the model can read, even when it is empty.
--
-- * Everything else is an infrastructure failure. A refused or lost request,
--   a descriptor the server no longer accepts, an output that breaks or
--   escapes its declared contract, a malformed result and a call the server
--   could not finish all throw a non-retryable 'ProviderError' that ends the
--   agent's loop. Nothing is retried here, so a call whose outcome is
--   uncertain runs at most once and the caller decides what to do. Arguments
--   that are not an object, or cannot be mirrored into the headers the
--   descriptor requires, are a 'ToolArgsInvalid' observation: nothing was
--   sent. Asynchronous exceptions, cancellation included, pass through.
--
-- Because a call goes through an 'McpInvoke' closure, a host that wants a
-- different policy (for example accepting outputs whose schema the client
-- cannot check) wraps 'callTool' before handing it over.
--
-- An t'McpRegistry' owns the names it hands out. It records, per exact server
-- name, the tools that server contributed and refuses any name that would
-- shadow a local tool or another server's tool before anything changes. A
-- refresh replaces one server's tools and leaves everything else alone.
-- Registries are immutable: a failed registration or refresh returns an
-- error and the caller keeps the handle it had. Replace an agent's registry
-- only between sessions; a checkpointed session refuses a changed tool set.
module Shikumi.Tool.Mcp
  ( -- * Invocation
    McpInvoke,

    -- * Errors
    McpToolIdentity (..),
    ToolOwner (..),
    McpAdapterError (..),
    renderMcpAdapterError,

    -- * Names
    mcpToolName,
    maxToolNameLength,

    -- * Single tools
    mcpToolNamed,
    mcpToolFor,
    mcpToolOutput,
    mcpFailure,

    -- * Discovery
    McpAdaptedTool (..),
    McpDiscovery (..),
    mcpToolsFrom,
    mcpTools,

    -- * The owned registry
    McpRegistry,
    newMcpRegistry,
    mcpRegistryTools,
    mcpRegistryServers,
    mcpRegistryOwner,
    registerMcpTools,
    refreshMcpTools,
    registerMcpToolsFrom,
    refreshMcpToolsFrom,
    unregisterMcpTools,
  )
where

import Baikai qualified as B
import Baikai.Error (providerError)
import Baikai.Error qualified as BE
import Baikai.Mcp.Client (McpConnection, McpOutcome (..), Unfinished (..), UnfinishedReason (..), connectionServerName)
import Baikai.Mcp.Error (Delivery (..), McpError (..), renderMcpError)
import Baikai.Mcp.JsonSchema (SchemaViolation (..))
import Baikai.Mcp.Protocol (DrainFailure (..), DrainLimits, defaultDrainLimits)
import Baikai.Mcp.Tool
  ( ContentBlock (..),
    McpTool (..),
    McpToolCall,
    McpToolError (..),
    McpToolResult (..),
    RejectedTool,
    StructuredContent (..),
    ToolListing (..),
    callTool,
    listTools,
    mcpToolCall,
  )
import Data.Aeson (Value (..), object, (.=))
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString.Base64 qualified as B64
import Data.Char (isAlphaNum, isAscii)
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 qualified as T
import Data.Text.Encoding qualified as TE
import Data.Vector qualified as V
import Effectful.Dispatch.Static (unsafeEff_)
import Effectful.Error.Static (throwError)
import Shikumi.Error (ShikumiError (..))
import Shikumi.Tool (DynErrorPolicy (..), SomeTool, ToolError (..), ToolRegistry, mkDynToolWith, mkRegistry, registryTools, someToolName)
import Shikumi.Tool.Output (ToolOutput (..))

-- ---------------------------------------------------------------------------
-- Invocation and errors

-- | Invoke one bound tool call. Usually @'callTool' connection@; tests and
-- hosts with their own policy supply another closure.
type McpInvoke = McpToolCall -> IO (Either McpToolError (McpOutcome McpToolResult))

-- | A remote tool, by the exact server name and the server's own tool name.
data McpToolIdentity = McpToolIdentity
  { server :: !Text,
    nativeName :: !Text
  }
  deriving stock (Eq, Ord, Show)

-- | Who holds a registry name.
data ToolOwner
  = -- | A tool the registry was created with.
    LocalTool
  | McpOwned !McpToolIdentity
  deriving stock (Eq, Show)

data McpAdapterError
  = -- | The server name is empty or leaves no room for tool names.
    InvalidServerName !Text !Text
  | -- | A caller-chosen public name a provider would not accept, and why.
    InvalidPublicName !Text !Text
  | -- | Discovery listed the same native tool more than once.
    DuplicateNativeTool !McpToolIdentity
  | -- | The public name is already held; nothing was changed.
    PublicNameCollision !Text !McpToolIdentity !ToolOwner
  | -- | Two server names produce the same name segment: the segment, the
    -- registered server and the new one.
    ServerSegmentCollision !Text !Text !Text
  | ServerAlreadyRegistered !Text
  | ServerNotRegistered !Text
  | -- | Listing the server's tools failed.
    DiscoveryFailed !Text !(DrainFailure McpError)
  deriving stock (Eq, Show)

renderMcpAdapterError :: McpAdapterError -> Text
renderMcpAdapterError = \case
  InvalidServerName s why -> "invalid MCP server name " <> quote s <> ": " <> why
  InvalidPublicName n why -> "invalid tool name " <> quote n <> ": " <> why
  DuplicateNativeTool i -> "MCP server " <> quote i.server <> " listed tool " <> quote i.nativeName <> " more than once"
  PublicNameCollision n i owner ->
    "tool name "
      <> quote n
      <> " for "
      <> identityText i
      <> " is already held by "
      <> case owner of
        LocalTool -> "a local tool"
        McpOwned o -> identityText o
  ServerSegmentCollision seg old new -> "MCP servers " <> quote old <> " and " <> quote new <> " share the name segment " <> quote seg
  ServerAlreadyRegistered s -> "MCP server " <> quote s <> " is already registered; refresh it instead"
  ServerNotRegistered s -> "MCP server " <> quote s <> " is not registered"
  DiscoveryFailed s f -> "listing the tools of MCP server " <> quote s <> " failed: " <> drainText f
  where
    identityText i = "tool " <> quote i.nativeName <> " of MCP server " <> quote i.server
    drainText = \case
      DrainPageFailed n e -> "page " <> tshow n <> ": " <> renderMcpError e
      DrainRepeatedCursor n -> "page " <> tshow n <> " repeated a cursor"
      DrainTooManyPages n -> "more than " <> tshow n <> " pages"
      DrainTooManyItems n -> "more than " <> tshow n <> " tools"
      DrainTooManyBytes n -> "more than " <> tshow n <> " bytes"
      DrainDeadline n -> "the deadline passed after " <> tshow n <> " pages"

quote :: Text -> Text
quote t = "\"" <> t <> "\""

tshow :: (Show a) => a -> Text
tshow = T.pack . show

-- ---------------------------------------------------------------------------
-- Names

-- | The longest tool name the adapter produces, the limit providers share.
maxToolNameLength :: Int
maxToolNameLength = 64

-- | Replace every character outside ASCII letters, digits, @_@ and @-@.
sanitize :: Text -> Text
sanitize = T.map (\c -> if isAscii c && (isAlphaNum c || c == '_' || c == '-') then c else '_')

prefixFor :: Text -> Text
prefixFor s = "mcp__" <> sanitize s <> "__"

-- | @mcp__\<server\>__\<tool\>@ with both segments sanitized, cut to
-- 'maxToolNameLength'. Distinct tools can share a name; registration
-- rejects that rather than disambiguating.
mcpToolName :: Text -> Text -> Text
mcpToolName s native = T.take maxToolNameLength (prefixFor s <> sanitize native)

checkServer :: Text -> Either McpAdapterError ()
checkServer s
  | T.null s = Left (InvalidServerName s "it is empty")
  | T.length (prefixFor s) >= maxToolNameLength = Left (InvalidServerName s "it leaves no room for tool names")
  | otherwise = Right ()

checkPublicName :: Text -> Either McpAdapterError ()
checkPublicName n
  | T.null n = Left (InvalidPublicName n "it is empty")
  | T.length n > maxToolNameLength = Left (InvalidPublicName n "it is longer than 64 characters")
  | sanitize n /= n = Left (InvalidPublicName n "only ASCII letters, digits, '_' and '-' are allowed")
  | otherwise = Right ()

-- ---------------------------------------------------------------------------
-- Single tools

-- | Adapt one descriptor under a caller-chosen public name. The model sees
-- that name, the tool's description (or title) and its input schema.
mcpToolNamed :: Text -> McpTool -> McpInvoke -> Either McpAdapterError SomeTool
mcpToolNamed public t invoke = do
  checkPublicName public
  Right $ mkDynToolWith PropagateErrors public (fromMaybe (fromMaybe "" t.title) t.description) t.inputSchema $ \case
    Object args -> do
      r <- unsafeEff_ (invoke (mcpToolCall t args))
      case r of
        Right (McpCompleted res) -> pure (Right (mcpToolOutput res))
        Left (ToolArgumentsUnmirrorable why) -> pure (Left (ToolArgsInvalid public why))
        other -> throwError (mcpFailure public t other)
    _ -> pure (Left (ToolArgsInvalid public "the arguments must be a JSON object"))

-- | Adapt one descriptor under its 'mcpToolName'.
mcpToolFor :: Text -> McpTool -> McpInvoke -> Either McpAdapterError SomeTool
mcpToolFor s t invoke = checkServer s >> mcpToolNamed (mcpToolName s t.name) t invoke

-- | A completed result as a tool output. Native blocks keep their order;
-- audio, resources, links, undecodable images and unknown blocks are kept
-- as their original JSON.
mcpToolOutput :: McpToolResult -> ToolOutput
mcpToolOutput r =
  ToolOutput
    { result = B.ToolResult (V.fromList [b | Left b <- blocks]) r.isError,
      structuredContent = case r.structured of
        StructuredContent v -> Just v
        NoStructuredContent -> Nothing,
      extensionBlocks = [v | Right v <- blocks]
    }
  where
    rawBlocks = case KeyMap.lookup "content" r.raw of
      Just (Array xs) | V.length xs == length r.content -> map Just (toList xs)
      _ -> map (const Nothing) r.content
    blocks = zipWith carry r.content rawBlocks
    carry block original = case block of
      TextBlock t -> Left (B.ToolResultText (B.TextContent t))
      ImageBlock d m | Right bytes <- B64.decode (TE.encodeUtf8 d) -> Left (B.ToolResultImage (B.ImageContent bytes m))
      _ -> Right (fromMaybe (rebuild block) original)
    rebuild = \case
      TextBlock t -> object ["type" .= ("text" :: Text), "text" .= t]
      ImageBlock d m -> object ["type" .= ("image" :: Text), "data" .= d, "mimeType" .= m]
      AudioBlock d m -> object ["type" .= ("audio" :: Text), "data" .= d, "mimeType" .= m]
      ResourceLinkBlock o -> Object o
      EmbeddedResourceBlock o -> Object o
      OtherBlock v -> v

-- | The infrastructure error for an outcome that is not a usable result. It
-- is never retryable: an outer retry would run the tool again.
mcpFailure :: Text -> McpTool -> Either McpToolError (McpOutcome McpToolResult) -> ShikumiError
mcpFailure public t outcome = ProviderError (providerError (prefix <> detail)) {BE.httpStatus = status}
  where
    prefix = "MCP tool " <> quote public <> " (native " <> quote t.name <> "): "
    (detail, status) = case outcome of
      Left (ToolRequestFailed e) -> (renderMcpError e <> deliveryNote e.delivery, e.httpStatus)
      Left (ToolDescriptorDrift e) -> ("the server no longer accepts the approved descriptor; list tools again and re-approve: " <> renderMcpError e, e.httpStatus)
      Left (ToolArgumentsUnmirrorable why) -> ("the arguments cannot be mirrored: " <> why, Nothing)
      Left (ToolOutputViolatesSchema vs _) -> ("the tool ran, but its structured output violates its output schema: " <> violations vs, Nothing)
      Left (ToolOutputUnverifiable why _) -> ("the tool ran, but its output contract could not be checked: " <> why, Nothing)
      Left (ToolResultMalformed why) -> ("the server returned a malformed result and the tool may have run: " <> why, Nothing)
      Right (McpUnfinished u) -> (unfinished u, Nothing)
      Right (McpCompleted _) -> ("completed", Nothing)
    deliveryNote = \case
      NotSent -> " (not sent)"
      Answered -> " (refused by the server)"
      Uncertain -> ""
    violations vs = T.intercalate "; " [v.instancePath <> " " <> v.keyword <> ": " <> v.detail | v <- take 3 vs]
    unfinished u = case u.reason of
      NeedsClientInput -> "the server asked for client input this adapter cannot provide"
      RoundLimitReached -> "the server did not finish within " <> tshow u.roundsSent <> " rounds"
      ContinuationDenied why -> "a continuation round was denied: " <> why

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

-- | One adapted remote tool.
data McpAdaptedTool = McpAdaptedTool
  { identity :: !McpToolIdentity,
    publicName :: !Text,
    -- | The descriptor every call binds.
    descriptor :: !McpTool,
    tool :: !SomeTool
  }

-- | A server's checked tools, and the descriptors the client excluded.
data McpDiscovery = McpDiscovery
  { server :: !Text,
    tools :: ![McpAdaptedTool],
    rejected :: ![RejectedTool]
  }

-- | Adapt a complete listing, rejecting repeated tools and names that
-- collide after sanitizing or truncation.
mcpToolsFrom :: Text -> McpInvoke -> [McpTool] -> Either McpAdapterError [McpAdaptedTool]
mcpToolsFrom s invoke ts = do
  checkServer s
  _ <- foldDistinct (\t -> t.name) (\t _ -> DuplicateNativeTool (McpToolIdentity s t.name)) ts
  adapted <- traverse adapt ts
  _ <- foldDistinct (.publicName) (\new old -> PublicNameCollision new.publicName new.identity (McpOwned old.identity)) adapted
  Right adapted
  where
    adapt t = do
      let public = mcpToolName s t.name
      st <- mcpToolNamed public t invoke
      Right McpAdaptedTool {identity = McpToolIdentity s t.name, publicName = public, descriptor = t, tool = st}

foldDistinct :: (a -> Text) -> (a -> a -> McpAdapterError) -> [a] -> Either McpAdapterError (Map Text a)
foldDistinct key clash = go Map.empty
  where
    go seen = \case
      [] -> Right seen
      x : rest -> case Map.lookup (key x) seen of
        Just old -> Left (clash x old)
        Nothing -> go (Map.insert (key x) x seen) rest

-- | List every tool of the connection's server under the drain limits and
-- adapt the listing. Calls go through 'callTool' on the same connection.
mcpTools :: DrainLimits -> McpConnection -> IO (Either McpAdapterError McpDiscovery)
mcpTools lim c = do
  let s = connectionServerName c
  listed <- listTools c lim
  pure $ case listed of
    Left f -> Left (DiscoveryFailed s f)
    Right l -> do
      ts <- mcpToolsFrom s (callTool c) l.tools
      Right McpDiscovery {server = s, tools = ts, rejected = l.rejected}

-- ---------------------------------------------------------------------------
-- The owned registry

-- | Local tools plus the tools each registered server contributed.
data McpRegistry = McpRegistry
  { local :: !(Map Text SomeTool),
    servers :: !(Map Text McpDiscovery),
    materialized :: !ToolRegistry
  }

-- | Start from the caller's tools, which no server may shadow.
newMcpRegistry :: ToolRegistry -> McpRegistry
newMcpRegistry reg =
  McpRegistry
    { local = Map.fromList [(someToolName t, t) | t <- registryTools reg],
      servers = Map.empty,
      materialized = reg
    }

-- | The registry an agent dispatches against.
mcpRegistryTools :: McpRegistry -> ToolRegistry
mcpRegistryTools r = r.materialized

-- | Each registered server's current discovery.
mcpRegistryServers :: McpRegistry -> Map Text McpDiscovery
mcpRegistryServers r = r.servers

-- | Who holds a public name.
mcpRegistryOwner :: Text -> McpRegistry -> Maybe ToolOwner
mcpRegistryOwner n r
  | Map.member n r.local = Just LocalTool
  | otherwise =
      case [t.identity | d <- Map.elems r.servers, t <- d.tools, t.publicName == n] of
        i : _ -> Just (McpOwned i)
        [] -> Nothing

-- | Discover a server's tools and add them. Fails if the server is already
-- registered.
registerMcpTools :: McpConnection -> McpRegistry -> IO (Either McpAdapterError McpRegistry)
registerMcpTools c r = (>>= (`registerMcpToolsFrom` r)) <$> mcpTools defaultDrainLimits c

-- | Discover a registered server's tools again and replace its entry.
refreshMcpTools :: McpConnection -> McpRegistry -> IO (Either McpAdapterError McpRegistry)
refreshMcpTools c r = (>>= (`refreshMcpToolsFrom` r)) <$> mcpTools defaultDrainLimits c

-- | Add a discovery for a server that is not registered yet.
registerMcpToolsFrom :: McpDiscovery -> McpRegistry -> Either McpAdapterError McpRegistry
registerMcpToolsFrom d r
  | Map.member d.server r.servers = Left (ServerAlreadyRegistered d.server)
  | otherwise = install d r

-- | Replace a registered server's tools with a new discovery. Other
-- servers' tools and local tools are untouched.
refreshMcpToolsFrom :: McpDiscovery -> McpRegistry -> Either McpAdapterError McpRegistry
refreshMcpToolsFrom d r
  | Map.member d.server r.servers = install d r
  | otherwise = Left (ServerNotRegistered d.server)

-- | Remove a server's tools, for example after closing its connection.
unregisterMcpTools :: Text -> McpRegistry -> McpRegistry
unregisterMcpTools s r = materialize r {servers = Map.delete s r.servers}

install :: McpDiscovery -> McpRegistry -> Either McpAdapterError McpRegistry
install d r = do
  checkServer d.server
  let others = Map.delete d.server r.servers
      segment = sanitize d.server
  case [s | s <- Map.keys others, sanitize s == segment] of
    old : _ -> Left (ServerSegmentCollision segment old d.server)
    [] -> Right ()
  _ <- foldDistinct (\t -> t.identity.nativeName) (\t _ -> DuplicateNativeTool t.identity) d.tools
  let held =
        Map.fromList ([(n, LocalTool) | n <- Map.keys r.local] <> [(t.publicName, McpOwned t.identity) | o <- Map.elems others, t <- o.tools])
      check t
        | t.identity.server /= d.server = Left (InvalidServerName d.server "the discovery holds another server's tools")
        | Just owner <- Map.lookup t.publicName held = Left (PublicNameCollision t.publicName t.identity owner)
        | otherwise = Right ()
  mapM_ check d.tools
  _ <- foldDistinct (.publicName) (\new old -> PublicNameCollision new.publicName new.identity (McpOwned old.identity)) d.tools
  Right (materialize r {servers = Map.insert d.server d others})

materialize :: McpRegistry -> McpRegistry
materialize r =
  r {materialized = mkRegistry (Map.elems r.local <> [t.tool | d <- Map.elems r.servers, t <- d.tools])}