packages feed

shikumi-tools 0.4.2.2 → 0.5.0.0

raw patch · 6 files changed

+977/−9 lines, 6 filesdep +asyncdep +baikai-mcpdep +base64-bytestringdep ~shikumi-tools

Dependencies added: async, baikai-mcp, base64-bytestring, stm

Dependency ranges changed: shikumi-tools

Files

CHANGELOG.md view
@@ -2,6 +2,26 @@  ## Unreleased +## 0.5.0.0 — 2026-11-30++### Added++- `Shikumi.Tool.Mcp` adapts Model Context Protocol tools from+  `mori://shinzui/baikai/packages/baikai-mcp` `^>=0.1.0.0` as dynamic tools named+  `mcp__<server>__<tool>`. Each tool forwards native names and arguments unchanged,+  keeps text, images, structured content and other blocks, and keeps tool errors+  model-visible. Every other failure ends the loop with a non-retryable+  `ProviderError`, and no call is retried. An immutable `McpRegistry` tracks which+  server owns each name. It rejects collisions before any change and refreshes one+  server at a time.+- `mkDynToolWith` and `DynErrorPolicy`: `PropagateErrors` lets every error a dynamic+  tool throws end the loop.++### Changed (breaking)++- `SomeTool`'s `DynTool` constructor gains a `DynErrorPolicy` field. `mkDynTool` is+  unchanged.+ ## 0.4.2.2 — 2026-11-23  ### Changed
shikumi-tools.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: shikumi-tools-version: 0.4.2.2+version: 0.5.0.0 synopsis:   Typed tools and ReAct agents for shikumi LM programs (EP-11) @@ -63,13 +63,16 @@     Shikumi.Tool.Builtin.Shell     Shikumi.Tool.Builtin.Web     Shikumi.Tool.Env+    Shikumi.Tool.Mcp     Shikumi.Tool.Output     Shikumi.Tool.Web    build-depends:     aeson >=2.2 && <2.3,     baikai >=0.11.0.0 && <0.12,+    baikai-mcp ^>=0.1.0.0,     base >=4.20 && <5,+    base64-bytestring >=1.2 && <1.3,     bytestring >=0.11 && <0.13,     containers >=0.6 && <0.9,     directory >=1.3 && <1.4,@@ -104,6 +107,7 @@     EnvSpec     Fixtures     FsSpec+    McpAdapterSpec     ProgramOfThoughtSpec     ProtocolSpec     RLMExample@@ -123,7 +127,9 @@    build-depends:     aeson,+    async,     baikai >=0.11.0.0 && <0.12,+    baikai-mcp,     base,     bytestring,     containers,@@ -135,7 +141,8 @@     shikumi ^>=0.5.1.1,     shikumi-cache ^>=0.2.1.2,     shikumi-testing ^>=0.1.0.0,-    shikumi-tools ^>=0.4.2.2,+    shikumi-tools ^>=0.5.0.0,+    stm,     tasty,     tasty-hunit,     text,
src/Shikumi/Tool.hs view
@@ -34,6 +34,8 @@     lowerSomeTool,     runErased,     mkDynTool,+    DynErrorPolicy (..),+    mkDynToolWith,     runErasedOutput,     runToolCallOutput,     ToolRegistry,@@ -125,37 +127,62 @@     Text ->     Text ->     Value ->+    DynErrorPolicy ->     (forall es. (LLM :> es, Error ShikumiError :> es) => Value -> Eff es (Either ToolError ToolOutput)) ->     SomeTool +-- | What dispatch does with a t'ShikumiError' a dynamic tool's body throws.+data DynErrorPolicy+  = -- | The typed-tool policy: infrastructure errors ('isInfraToolError')+    -- abort the loop and every other error becomes a 'ToolRunFailed'+    -- observation.+    ObserveRecoverableErrors+  | -- | Every thrown error aborts the loop. For a body that already returns+    -- each failure the model may see as a value, so anything it throws is an+    -- infrastructure fault: for example a remote call whose outcome is+    -- uncertain and must not be offered back to the model for a retry.+    PropagateErrors+  deriving stock (Eq, Show)+ -- | Register a runtime schema and rich-result body without an input Haskell type.+-- Thrown errors follow 'ObserveRecoverableErrors'. mkDynTool ::   Text ->   Text ->   Value ->   (forall es. (LLM :> es, Error ShikumiError :> es) => Value -> Eff es (Either ToolError ToolOutput)) ->   SomeTool-mkDynTool = DynTool+mkDynTool n d s = DynTool n d s ObserveRecoverableErrors +-- | 'mkDynTool' with an explicit policy for thrown errors.+mkDynToolWith ::+  DynErrorPolicy ->+  Text ->+  Text ->+  Value ->+  (forall es. (LLM :> es, Error ShikumiError :> es) => Value -> Eff es (Either ToolError ToolOutput)) ->+  SomeTool+mkDynToolWith policy n d s = DynTool n d s policy+ -- | The name of an erased tool. someToolName :: SomeTool -> Text someToolName (SomeTool t) = name t-someToolName (DynTool n _ _ _) = n+someToolName (DynTool n _ _ _ _) = n  -- | The description of an erased tool. someToolDescription :: SomeTool -> Text someToolDescription (SomeTool t) = description t-someToolDescription (DynTool _ d _ _) = d+someToolDescription (DynTool _ d _ _ _) = d  -- | The derived input JSON Schema of an erased tool. someToolSchema :: SomeTool -> Value someToolSchema (SomeTool t) = toolSchemaOf t-someToolSchema (DynTool _ _ s _) = s+someToolSchema (DynTool _ _ s _ _) = s  -- | Lower an erased tool to baikai's wire tool. lowerSomeTool :: SomeTool -> B.Tool lowerSomeTool (SomeTool t) = lowerTool t-lowerSomeTool (DynTool n d s _) = emptyTool & #name .~ n & #description .~ d & #parameters .~ s+lowerSomeTool (DynTool n d s _ _) = emptyTool & #name .~ n & #description .~ d & #parameters .~ s  -- | Run an erased tool against a raw JSON arguments object: decode to the hidden -- @i@, run the body, encode the @o@ to text. A decode failure becomes@@ -169,9 +196,12 @@   Eff es (Either ToolError Text) runErased st args = fmap (fmap renderToolOutput) (runErasedOutput st args) --- | Rich dispatch; dynamic bodies share typed tools' infrastructure error policy.+-- | Rich dispatch. Typed tools and 'ObserveRecoverableErrors' dynamic tools+-- share the infrastructure error policy; a 'PropagateErrors' tool's thrown+-- errors always escape. runErasedOutput :: (LLM :> es, Error ShikumiError :> es) => SomeTool -> Value -> Eff es (Either ToolError ToolOutput)-runErasedOutput (DynTool n _ _ body) args =+runErasedOutput (DynTool _ _ _ PropagateErrors body) args = body args+runErasedOutput (DynTool n _ _ ObserveRecoverableErrors body) args =   body args `catchError` \_cs e ->     if isInfraToolError e       then throwError e
+ src/Shikumi/Tool/Mcp.hs view
@@ -0,0 +1,439 @@+{-# 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])}
test/Main.hs view
@@ -9,6 +9,7 @@ import CompactionSpec qualified import EnvSpec qualified import FsSpec qualified+import McpAdapterSpec qualified import ProgramOfThoughtSpec qualified import ProtocolSpec qualified import RLMSpec qualified@@ -39,6 +40,7 @@         SchemaSpec.tests,         ToolSpec.tests,         ToolOutputSpec.tests,+        McpAdapterSpec.tests,         EnvSpec.tests,         WebSpec.tests,         FsSpec.tests,
+ test/McpAdapterSpec.hs view
@@ -0,0 +1,470 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedRecordDot #-}++-- | The MCP adapter against the released @baikai-mcp@ client: single-tool+-- adaptation, checked names, the owned registry and a ReAct run over a real+-- connection to an in-memory stdio server.+module McpAdapterSpec (tests) where++import Baikai qualified as B+import Baikai.Error (BaikaiError (..))+import Baikai.Error qualified as BE+import Baikai.Mcp.Client (McpOutcome (..), McpStreamConfig (..), Unfinished (..), UnfinishedReason (..), defaultMcpLimits, mcpStreamConfig, withMcpStream)+import Baikai.Mcp.Client qualified as Client+import Baikai.Mcp.Content (decodeContentBlock)+import Baikai.Mcp.Error (Delivery (..), McpErrorKind (..), mcpError)+import Baikai.Mcp.Protocol (defaultDrainLimits)+import Baikai.Mcp.Tool (McpTool (..), McpToolCall (..), McpToolError (..), McpToolResult (..), OutputCheck (..), StructuredContent (..))+import Baikai.Mcp.Transport.Stream (McpStream (..))+import Control.Concurrent.Async (async, cancel)+import Control.Concurrent.STM+import Control.Exception (finally)+import Control.Lens ((^.))+import Data.Aeson (Value (..), object, toJSON, (.=))+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 (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.Either (isLeft)+import Data.Generics.Labels ()+import Data.IORef+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Text qualified as T+import Data.Vector qualified as V+import Effectful (Eff, IOE, liftIO, runEff)+import Effectful.Dispatch.Dynamic (interpret)+import Effectful.Error.Static (Error, runErrorNoCallStack, throwError)+import Fixtures (expectedWeather, weatherQuestion, weatherRegistry, weatherSignature)+import Shikumi.Agent.ReAct+import Shikumi.Error (ShikumiError (..), isTransient)+import Shikumi.LLM (LLM (..))+import Shikumi.Testing (mkTextResponse, mkToolCallResponse, runEffScript)+import Shikumi.Tool+import Shikumi.Tool.Mcp+import Shikumi.Tool.Output+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit++tests :: TestTree+tests =+  testGroup+    "MCP adapter"+    [ names,+      singleTool,+      failures,+      registry,+      agent+    ]++-- ---------------------------------------------------------------------------+-- Descriptors and scripted invocation++objectSchema :: [(Text, Text)] -> Value+objectSchema props = object ["type" .= ("object" :: Text), "properties" .= object [(Key.fromText k, object ["type" .= t]) | (k, t) <- props]]++remoteTool :: Text -> McpTool+remoteTool n =+  McpTool+    { name = n,+      title = Nothing,+      description = Just ("remote " <> n),+      inputSchema = objectSchema [("msg", "string")],+      outputSchema = Nothing,+      annotations = Nothing,+      headerMirrors = [],+      raw = KeyMap.fromList [("name", String n)]+    }++resultOf :: [Value] -> StructuredContent -> Bool -> McpToolResult+resultOf blocks structured err =+  McpToolResult+    { content = map decodeContentBlock blocks,+      structured = structured,+      isError = err,+      outputCheck = NoOutputSchema,+      raw = KeyMap.fromList ([("content", toJSON blocks)] <> [("structuredContent", v) | StructuredContent v <- [structured]]),+      continuationRounds = 0+    }++textBlock :: Text -> Value+textBlock t = object ["type" .= ("text" :: Text), "text" .= t]++-- | A closure that records each call and answers with a fixed outcome.+scripted :: Either McpToolError (McpOutcome McpToolResult) -> IO (IORef [McpToolCall], McpInvoke)+scripted outcome = do+  ref <- newIORef []+  pure (ref, \call -> modifyIORef' ref (<> [call]) >> pure outcome)++adaptOrFail :: Text -> McpTool -> McpInvoke -> IO SomeTool+adaptOrFail s t invoke = either (assertFailure . T.unpack . renderMcpAdapterError) pure (mcpToolFor s t invoke)++runTool :: SomeTool -> Value -> IO (Either ShikumiError (Either ToolError ToolOutput))+runTool t args = runEffScript [] (runErasedOutput t args)++-- ---------------------------------------------------------------------------++names :: TestTree+names =+  testGroup+    "names"+    [ testCase "sanitized and prefixed" $+        mcpToolName "git.hub" "search/code" @?= "mcp__git_hub__search_code",+      testCase "cut to 64 characters" $ do+        let n = mcpToolName "srv" (T.replicate 100 "x")+        T.length n @?= 64+        maxToolNameLength @?= 64,+      testCase "the model sees the public name, the description and the original schema" $ do+        (_, invoke) <- scripted (Right (McpCompleted (resultOf [] NoStructuredContent False)))+        t <- adaptOrFail "git" (remoteTool "status") invoke+        someToolName t @?= "mcp__git__status"+        someToolDescription t @?= "remote status"+        someToolSchema t @?= objectSchema [("msg", "string")],+      testCase "caller-chosen names are checked" $ do+        (_, invoke) <- scripted (Right (McpCompleted (resultOf [] NoStructuredContent False)))+        assertBool "overlay name accepted" (either (const False) ((== "overlay__git") . someToolName) (mcpToolNamed "overlay__git" (remoteTool "status") invoke))+        assertBool "dot refused" (isLeft (mcpToolNamed "a.b" (remoteTool "status") invoke))+        assertBool "empty server refused" (isLeft (mcpToolFor "" (remoteTool "status") invoke))+    ]++singleTool :: TestTree+singleTool =+  testGroup+    "single tool"+    [ testCase "native name and arguments are forwarded unchanged" $ do+        (calls, invoke) <- scripted (Right (McpCompleted (resultOf [textBlock "hi"] NoStructuredContent False)))+        t <- adaptOrFail "srv" (remoteTool "echo.v2") invoke+        let args = object ["msg" .= ("hi" :: Text), "nested" .= object ["n" .= (1 :: Int)]]+        r <- runTool t args+        r @?= Right (Right (textToolOutput "hi"))+        sent <- readIORef calls+        map (\c -> (c.tool.name, Object c.arguments)) sent @?= [("echo.v2", args)],+      testCase "structured-only results, a present null included, are kept" $ do+        let expect structured expected = do+              (_, invoke) <- scripted (Right (McpCompleted (resultOf [] structured False)))+              t <- adaptOrFail "srv" (remoteTool "calc") invoke+              r <- runTool t (object [])+              r @?= Right (Right (ToolOutput (B.ToolResult V.empty False) expected []))+        expect (StructuredContent (object ["sum" .= (3 :: Int)])) (Just (object ["sum" .= (3 :: Int)]))+        expect (StructuredContent Null) (Just Null)+        expect NoStructuredContent Nothing,+      testCase "a tool error stays model-visible, even when empty" $ do+        (_, invoke) <- scripted (Right (McpCompleted (resultOf [] NoStructuredContent True)))+        t <- adaptOrFail "srv" (remoteTool "fail") invoke+        r <- runTool t (object [])+        case r of+          Right (Right o) -> do+            o.result ^. #isError @?= True+            assertBool "visible" ("Tool error:" `T.isPrefixOf` renderToolOutput o)+          other -> assertFailure (show other),+      testCase "mixed blocks keep images natively and everything else as JSON" $ do+        let image = object ["type" .= ("image" :: Text), "data" .= ("aGk=" :: Text), "mimeType" .= ("image/png" :: Text)]+            badImage = object ["type" .= ("image" :: Text), "data" .= ("%%%" :: Text), "mimeType" .= ("image/png" :: Text)]+            audio = object ["type" .= ("audio" :: Text), "data" .= ("aGk=" :: Text), "mimeType" .= ("audio/wav" :: Text), "annotations" .= object ["priority" .= (1 :: Int)]]+            link = object ["type" .= ("resource_link" :: Text), "uri" .= ("file:///a" :: Text), "name" .= ("a" :: Text)]+            unknown = object ["type" .= ("hologram" :: Text)]+            structured = object ["ok" .= True]+        (_, invoke) <- scripted (Right (McpCompleted (resultOf [textBlock "caption", image, badImage, audio, link, unknown] (StructuredContent structured) False)))+        t <- adaptOrFail "srv" (remoteTool "mixed") invoke+        r <- runTool t (object [])+        r+          @?= Right+            ( Right+                ( ToolOutput+                    (B.ToolResult (V.fromList [B.ToolResultText (B.TextContent "caption"), B.ToolResultImage (B.ImageContent "hi" "image/png")]) False)+                    (Just structured)+                    [badImage, audio, link, unknown]+                )+            ),+      testCase "arguments that are not an object are refused before sending" $ do+        (calls, invoke) <- scripted (Right (McpCompleted (resultOf [] NoStructuredContent False)))+        t <- adaptOrFail "srv" (remoteTool "echo") invoke+        r <- runTool t (toJSON [1 :: Int])+        r @?= Right (Left (ToolArgsInvalid "mcp__srv__echo" "the arguments must be a JSON object"))+        readIORef calls >>= (@?= []) . map (const ()),+      testCase "unmirrorable arguments are an observation" $ do+        (_, invoke) <- scripted (Left (ToolArgumentsUnmirrorable "msg is not a string"))+        t <- adaptOrFail "srv" (remoteTool "echo") invoke+        r <- runTool t (object [])+        r @?= Right (Left (ToolArgsInvalid "mcp__srv__echo" "msg is not a string"))+    ]++failures :: TestTree+failures =+  testGroup+    "failures"+    [ testCase "an uncertain call aborts once, non-retryable, and is not replayed" $ do+        (calls, invoke) <- scripted (Left (ToolRequestFailed (mcpError TimedOut Uncertain "the request timed out")))+        t <- adaptOrFail "srv" (remoteTool "deploy") invoke+        r <- runTool t (object [])+        case r of+          Left e@(ProviderError be) -> do+            assertBool "not transient" (not (isTransient e))+            be.category @?= BE.OtherError+            assertBool "names the tool" ("mcp__srv__deploy" `T.isInfixOf` be.message)+            assertBool "says it may have run" ("may have processed" `T.isInfixOf` be.message)+          other -> assertFailure (show other)+        length <$> readIORef calls >>= (@?= 1),+      testCase "refusals, drift, contract failures and unfinished calls abort" $ do+        let violates = ToolOutputViolatesSchema [] (resultOf [] (StructuredContent Null) False)+            outcomes =+              [ Left (ToolRequestFailed (mcpError RemoteRpcError Answered "invalid params")),+                Left (ToolRequestFailed (mcpError RequestDenied NotSent "denied by policy")),+                Left (ToolDescriptorDrift (mcpError RemoteRpcError Answered "header mismatch")),+                Left violates,+                Left (ToolOutputUnverifiable "unsupported keyword" (resultOf [] (StructuredContent Null) False)),+                Left (ToolResultMalformed "content must be an array"),+                Right (McpUnfinished (Unfinished Nothing Nothing 1 NeedsClientInput))+              ]+        mapM_+          ( \o -> do+              (_, invoke) <- scripted o+              t <- adaptOrFail "srv" (remoteTool "x") invoke+              r <- runTool t (object [])+              case r of+                Left (ProviderError be) -> be.category @?= BE.OtherError+                other -> assertFailure (show o <> " gave " <> show other)+          )+          outcomes+    ]++-- ---------------------------------------------------------------------------++discoveryOf :: Text -> [Text] -> IO McpDiscovery+discoveryOf s ns = do+  (_, invoke) <- scripted (Right (McpCompleted (resultOf [textBlock s] NoStructuredContent False)))+  either (assertFailure . T.unpack . renderMcpAdapterError) (\ts -> pure (McpDiscovery s ts [])) (mcpToolsFrom s invoke (map remoteTool ns))++expectError :: Either McpAdapterError a -> IO McpAdapterError+expectError = either pure (const (assertFailure "expected an adapter error"))++registry :: TestTree+registry =+  testGroup+    "owned registry"+    [ testCase "tools that sanitize or truncate to one name are rejected" $ do+        (_, invoke) <- scripted (Right (McpCompleted (resultOf [] NoStructuredContent False)))+        e1 <- expectError (mcpToolsFrom "s" invoke [remoteTool "x.y", remoteTool "x_y"])+        e1 @?= PublicNameCollision "mcp__s__x_y" (McpToolIdentity "s" "x_y") (McpOwned (McpToolIdentity "s" "x.y"))+        let long suffix = T.replicate 70 "a" <> suffix+        e2 <- expectError (mcpToolsFrom "s" invoke [remoteTool (long "1"), remoteTool (long "2")])+        case e2 of+          PublicNameCollision {} -> pure ()+          other -> assertFailure (show other)+        e3 <- expectError (mcpToolsFrom "s" invoke [remoteTool "dup", remoteTool "dup"])+        e3 @?= DuplicateNativeTool (McpToolIdentity "s" "dup"),+      testCase "servers whose names share a segment are rejected" $ do+        a <- discoveryOf "a.b" ["one"]+        b <- discoveryOf "a_b" ["two"]+        r <- either (assertFailure . show) pure (registerMcpToolsFrom a (newMcpRegistry (mkRegistry [])))+        e <- expectError (registerMcpToolsFrom b r)+        e @?= ServerSegmentCollision "a_b" "a.b" "a_b",+      testCase "delimiters inside names cannot steal another server's name" $ do+        a <- discoveryOf "a" ["x__y"]+        b <- discoveryOf "a__x" ["y"]+        r <- either (assertFailure . show) pure (registerMcpToolsFrom a (newMcpRegistry (mkRegistry [])))+        e <- expectError (registerMcpToolsFrom b r)+        e @?= PublicNameCollision "mcp__a__x__y" (McpToolIdentity "a__x" "y") (McpOwned (McpToolIdentity "a" "x__y")),+      testCase "a local tool is never shadowed" $ do+        let localTool = mkDynTool "mcp__s__echo" "local" (object []) (\_ -> pure (Right (textToolOutput "local")))+            base = newMcpRegistry (mkRegistry [localTool])+        d <- discoveryOf "s" ["echo"]+        e <- expectError (registerMcpToolsFrom d base)+        e @?= PublicNameCollision "mcp__s__echo" (McpToolIdentity "s" "echo") LocalTool+        registryNames (mcpRegistryTools base) @?= ["mcp__s__echo"],+      testCase "refresh replaces exactly one server and is idempotent" $ do+        git1 <- discoveryOf "git" ["status", "log"]+        web <- discoveryOf "web" ["fetch"]+        let base = newMcpRegistry weatherRegistry+        r1 <- either (assertFailure . show) pure (registerMcpToolsFrom git1 base >>= registerMcpToolsFrom web)+        registryNames (mcpRegistryTools r1) @?= ["get_weather", "mcp__git__log", "mcp__git__status", "mcp__web__fetch"]+        git2 <- discoveryOf "git" ["status", "diff"]+        r2 <- either (assertFailure . show) pure (refreshMcpToolsFrom git2 r1)+        registryNames (mcpRegistryTools r2) @?= ["get_weather", "mcp__git__diff", "mcp__git__status", "mcp__web__fetch"]+        r3 <- either (assertFailure . show) pure (refreshMcpToolsFrom git2 r2)+        registryNames (mcpRegistryTools r3) @?= registryNames (mcpRegistryTools r2)+        mcpRegistryOwner "mcp__git__diff" r3 @?= Just (McpOwned (McpToolIdentity "git" "diff"))+        mcpRegistryOwner "get_weather" r3 @?= Just LocalTool+        mcpRegistryOwner "mcp__git__log" r3 @?= Nothing+        Map.keys (mcpRegistryServers r3) @?= ["git", "web"]+        registryNames (mcpRegistryTools (unregisterMcpTools "git" r3)) @?= ["get_weather", "mcp__web__fetch"],+      testCase "a failed refresh changes nothing" $ do+        git1 <- discoveryOf "git" ["status"]+        r1 <- either (assertFailure . show) pure (registerMcpToolsFrom git1 (newMcpRegistry weatherRegistry))+        clash <- discoveryOf "git" ["status", "w"]+        let bad = clash {tools = [if t.identity.nativeName == "w" then t {publicName = "get_weather"} else t | t <- clash.tools]}+        e <- expectError (refreshMcpToolsFrom bad r1)+        e @?= PublicNameCollision "get_weather" (McpToolIdentity "git" "w") LocalTool+        registryNames (mcpRegistryTools r1) @?= ["get_weather", "mcp__git__status"]+        e2 <- expectError (registerMcpToolsFrom git1 r1)+        e2 @?= ServerAlreadyRegistered "git"+        other <- discoveryOf "other" ["a"]+        e3 <- expectError (refreshMcpToolsFrom other r1)+        e3 @?= ServerNotRegistered "other"+    ]++-- ---------------------------------------------------------------------------+-- A real connection: an in-memory 2026-07-28 stdio server++data Pipe = Pipe {toServer :: TQueue (Maybe ByteString), toClient :: TQueue (Maybe ByteString)}++field :: Aeson.Key -> Value -> Maybe Value+field k = \case+  Object o -> KeyMap.lookup k o+  _ -> Nothing++paramsOf :: Value -> Object+paramsOf v = case field "params" v of+  Just (Object o) -> o+  _ -> KeyMap.empty++reply :: Value -> [(Aeson.Key, Value)] -> Value+reply req fields = object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "id" req, "result" .= object fields]++-- | Serves @echo@ (text and structured) and @add@ (structured only, with an+-- output schema), and fails @flaky@ by closing its output mid-call.+fixtureServer :: IORef [Object] -> (Value -> IO ()) -> IO () -> Value -> IO ()+fixtureServer calls send closeOutput msg = case (field "method" msg, field "id" msg) of+  (Just (String m), Just _) -> case m of+    "server/discover" -> send (reply msg ["resultType" .= ("complete" :: Text), "supportedVersions" .= ["2026-07-28" :: Text], "capabilities" .= object ["tools" .= object []]])+    "tools/list" ->+      send+        ( reply+            msg+            [ "tools"+                .= [ object ["name" .= ("echo" :: Text), "description" .= ("Echo a message." :: Text), "inputSchema" .= objectSchema [("msg", "string")]],+                     object+                       [ "name" .= ("add" :: Text),+                         "inputSchema" .= objectSchema [("a", "number"), ("b", "number")],+                         "outputSchema" .= object ["type" .= ("object" :: Text), "properties" .= object ["sum" .= object ["type" .= ("number" :: Text)]], "required" .= ["sum" :: Text]]+                       ],+                     object ["name" .= ("flaky" :: Text), "inputSchema" .= objectSchema []]+                   ]+            ]+        )+    "tools/call" -> do+      let p = paramsOf msg+          args = case KeyMap.lookup "arguments" p of+            Just (Object a) -> a+            _ -> KeyMap.empty+      modifyIORef' calls (<> [p])+      case KeyMap.lookup "name" p of+        Just "echo" ->+          let said = maybe Null id (KeyMap.lookup "msg" args)+           in send (reply msg ["content" .= [object ["type" .= ("text" :: Text), "text" .= said]], "structuredContent" .= object ["echoed" .= said]])+        Just "add" ->+          let num k = case KeyMap.lookup k args of+                Just (Number n) -> n+                _ -> 0+           in send (reply msg ["structuredContent" .= object ["sum" .= (num "a" + num "b")]])+        Just "flaky" -> closeOutput+        _ -> send (reply msg ["content" .= ([] :: [Value]), "isError" .= True])+    _ -> send (object ["jsonrpc" .= ("2.0" :: Text), "id" .= field "id" msg, "error" .= object ["code" .= (-32601 :: Int), "message" .= ("Method not found" :: Text)]])+  _ -> pure ()++withFixture :: (IORef [Object] -> Client.McpConnection -> IO a) -> IO a+withFixture k = do+  p <- Pipe <$> newTQueueIO <*> newTQueueIO+  calls <- newIORef []+  let send v = atomically (writeTQueue p.toClient (Just (BS.toStrict (Aeson.encode v) <> "\n")))+      closeOutput = atomically (writeTQueue p.toClient Nothing)+      loop buffered = case BS8.elemIndex '\n' buffered of+        Just i -> do+          mapM_ (fixtureServer calls send closeOutput) (Aeson.decodeStrict (BS.take i buffered))+          loop (BS.drop (i + 1) buffered)+        Nothing -> atomically (readTQueue p.toServer) >>= maybe (pure ()) (loop . (buffered <>))+      stream =+        McpStream+          { readChunk = maybe "" id <$> atomically (readTQueue p.toClient),+            writeChunk = \b -> atomically (writeTQueue p.toServer (Just b)),+            closeStream = Just (atomically (writeTQueue p.toServer Nothing))+          }+      cfg = (mcpStreamConfig "fixture") {probeTimeout = 1, streamLimits = defaultMcpLimits {Client.requestTimeout = 5, Client.connectTimeout = 5}}+  server <- async (loop BS.empty)+  r <- withMcpStream cfg stream (k calls) `finally` cancel server+  either (assertFailure . show) pure r++-- | Script the model and record every request context.+recording :: [B.Response] -> Eff '[LLM, Error ShikumiError, IOE] a -> IO (Either ShikumiError a, [B.Context])+recording script action = do+  scriptRef <- newIORef script+  contexts <- newIORef []+  result <-+    runEff+      . runErrorNoCallStack+      . interpret+        ( \_ -> \case+            Complete _ ctx _ -> do+              liftIO (modifyIORef' contexts (<> [ctx]))+              next <- liftIO (atomicModifyIORef' scriptRef (\case [] -> ([], Nothing); x : rest -> (rest, Just x)))+              maybe (throwError (ProviderFailure "unexpected model call")) pure next+            Stream {} -> pure []+        )+      $ action+  (result,) <$> readIORef contexts++cfgNative :: ReActConfig+cfgNative = defaultReActConfig {protocol = ProtocolNative}++agent :: TestTree+agent =+  testGroup+    "agent over a real connection"+    [ testCase "discovers two tools, calls one and submits a typed answer" $+        withFixture $ \calls c -> do+          discovered <- mcpTools defaultDrainLimits c+          d <- either (assertFailure . T.unpack . renderMcpAdapterError) pure discovered+          map (.publicName) d.tools @?= ["mcp__fixture__echo", "mcp__fixture__add", "mcp__fixture__flaky"]+          reg <- either (assertFailure . show) pure (registerMcpToolsFrom d (newMcpRegistry (mkRegistry [])))+          let tools = mcpRegistryTools reg+              args = object ["msg" .= ("bonjour" :: Text)]+              turn1 = mkToolCallResponse "call-1" "mcp__fixture__echo" args+              turn2 = mkToolCallResponse "final-1" finalToolName (toJSON expectedWeather)+          (result, requests) <- recording [turn1, turn2] (startSession weatherSignature tools cfgNative weatherQuestion >>= runSession weatherSignature tools cfgNative)+          case result of+            Right (SessionFinished answer _) -> answer @?= expectedWeather+            other -> assertFailure (show (fmap (const ()) other))+          sent <- readIORef calls+          map (KeyMap.delete "_meta") sent @?= [KeyMap.fromList [("name", String "echo"), ("arguments", args)]]+          case requests of+            [first, second] -> do+              let offered = [(t ^. #name, t ^. #parameters) | t <- V.toList (first ^. #tools)]+              lookup "mcp__fixture__echo" offered @?= Just (objectSchema [("msg", "string")])+              lookup "mcp__fixture__add" offered @?= Just (objectSchema [("a", "number"), ("b", "number")])+              let results = [p | B.ToolResultMessage p <- V.toList (second ^. #messages)]+              case results of+                [p] -> do+                  p ^. #toolCallId @?= "call-1"+                  p ^. #content+                    @?= V.fromList+                      [ B.ToolResultText (B.TextContent "bonjour"),+                        B.ToolResultText (B.TextContent "Structured JSON: {\"echoed\":\"bonjour\"}")+                      ]+                _ -> assertFailure ("expected one tool result, got " <> show (length results))+            _ -> assertFailure ("expected two model requests, got " <> show (length requests)),+      testCase "a structured-only result with a checked output schema is kept" $+        withFixture $ \_ c -> do+          d <- mcpTools defaultDrainLimits c >>= either (assertFailure . show) pure+          case [t | t <- d.tools, t.publicName == "mcp__fixture__add"] of+            [t] -> do+              r <- runTool t.tool (object ["a" .= (2 :: Int), "b" .= (3 :: Int)])+              r @?= Right (Right (ToolOutput (B.ToolResult V.empty False) (Just (object ["sum" .= (5 :: Int)])) []))+            _ -> assertFailure "add not discovered",+      testCase "a call lost mid-flight ends the run and is sent once" $+        withFixture $ \calls c -> do+          d <- mcpTools defaultDrainLimits c >>= either (assertFailure . show) pure+          reg <- either (assertFailure . show) pure (registerMcpToolsFrom d (newMcpRegistry (mkRegistry [])))+          let tools = mcpRegistryTools reg+              turn1 = mkToolCallResponse "call-1" "mcp__fixture__flaky" (object [])+          (result, requests) <- recording [turn1, mkTextResponse "unused"] (startSession weatherSignature tools cfgNative weatherQuestion >>= runSession weatherSignature tools cfgNative)+          case result of+            Left e@(ProviderError be) -> do+              assertBool "not transient" (not (isTransient e))+              assertBool "uncertain" ("may have processed" `T.isInfixOf` be.message)+            other -> assertFailure (show (fmap (const ()) other))+          length requests @?= 1+          length <$> readIORef calls >>= (@?= 1)+    ]