effectful-mcp (empty) → 0.1.0.0
raw patch · 8 files changed
+1107/−0 lines, 8 filesdep +aesondep +basedep +base64-bytestring
Dependencies added: aeson, base, base64-bytestring, bytestring, containers, effectful, effectful-core, effectful-mcp, scientific, stm, streamly-core, tasty, tasty-hunit, text
Files
- CHANGELOG.md +10/−0
- LICENSE +29/−0
- README.md +71/−0
- effectful-mcp.cabal +83/−0
- src/Effectful/MCP/JsonRpc.hs +135/−0
- src/Effectful/MCP/Server.hs +306/−0
- src/Effectful/MCP/Tool.hs +156/−0
- test/Main.hs +317/−0
+ CHANGELOG.md view
@@ -0,0 +1,10 @@+# Revision history for effectful-mcp++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* An MCP server over stdio: `server/discover`, `tools/list` and+ `tools/call`, concurrent requests and cancellation.+* Revision 2026-07-28 of the protocol, and the earlier revisions for the+ clients that start with `initialize`; both on one connection.+* Tools as `Eff` actions, with text, image or structured results.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,71 @@+# effectful-mcp++A server of the [Model Context Protocol](https://modelcontextprotocol.io)+(MCP), revision 2026-07-28 and the earlier ones, for+[Effectful](https://hackage.haskell.org/package/effectful): declare tools as+`Eff` actions, and serve them over stdio.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Data.Aeson (FromJSON (parseJSON), object, withObject, (.:), (.=))+import Data.Text (Text)+import Effectful (runEff)+import Effectful.Concurrent (runConcurrent)+import Effectful.MCP.Server (implementation, serveStdio, serverConfig)+import Effectful.MCP.Tool (textResult, tool, withArguments)++newtype Greeting = Greeting Text++instance FromJSON Greeting where+ parseJSON = withObject "Greeting" $ \fields -> Greeting <$> fields .: "name"++main :: IO ()+main =+ runEff . runConcurrent . serveStdio $+ serverConfig+ (implementation "greeter" "0.1.0")+ [ tool "greet" "Greet someone" schema $+ withArguments (\(Greeting name) -> pure (textResult ("Hello, " <> name)))+ ]+ where+ schema =+ object+ [ "type" .= ("object" :: Text)+ , "properties" .= object ["name" .= object ["type" .= ("string" :: Text)]]+ , "required" .= ["name" :: Text]+ ]+```++## What it does++- Revision 2026-07-28: every request carries its protocol version and the+ capabilities of the client in `_meta`, and is served on its own. Clients+ that speak both eras, such as current versions of Claude Code, probe+ with `server/discover` first and use this revision.+- The earlier revisions (2025-11-25 and before): `initialize` selects them+ for the connection, and `tools/list`, `tools/call` and `ping` are then+ answered as they describe. Clients that only know them, such as the+ Claude desktop application at the time of writing, are served this way.+- Both at once on one connection, as revision 2026-07-28 allows: what a+ request carries tells which it is.+- `server/discover`, `tools/list` (in a fixed order, with cache hints) and+ `tools/call`.+- Tool failures, including arguments that do not decode, come back as+ results with `isError`, which the model can act on; protocol errors use+ the JSON-RPC codes of the specification.+- Requests are served concurrently; `notifications/cancelled` stops one.+ When the input ends, running requests get a grace period to finish.+- Not yet: resources, prompts, subscriptions, multi round-trip requests,+ progress, the Streamable HTTP transport.++Requests run in threads of their own, forked as Effectful forks them: a tool+that changes a local `State` changes its own copy. Use shared effects for+state that must outlive a call.++Tested with GHC 9.8.4, 9.10.3 and 9.12.4, effectful 2.7.1, streamly-core+0.3.3.++## License++BSD-3-Clause. See [LICENSE](LICENSE).
+ effectful-mcp.cabal view
@@ -0,0 +1,83 @@+cabal-version: 3.12+name: effectful-mcp+version: 0.1.0.0+synopsis: Model Context Protocol servers in Effectful+description:+ A server of the Model Context Protocol (MCP) for Effectful: declare tools+ as Eff actions, and serve them over stdio, concurrently, with+ cancellation. It speaks revision 2026-07-28 of the protocol and, to the+ clients that only know them, the earlier ones.++homepage: https://github.com/GuillaumedeVolpiano/effectful-mcp+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: AI, Network, Control+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/effectful-mcp.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ DuplicateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ NoFieldSelectors+ OverloadedRecordDot+ OverloadedStrings+ RoleAnnotations++ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ Effectful.MCP.JsonRpc+ Effectful.MCP.Server+ Effectful.MCP.Tool++ build-depends:+ , aeson ^>=2.3+ , base >=4.19 && <4.22+ , base64-bytestring ^>=1.2+ , bytestring ^>=0.12+ , containers >=0.6.7 && <0.8+ , effectful ^>=2.7+ , effectful-core ^>=2.7.1+ , scientific ^>=0.3+ , streamly-core ^>=0.3.3+ , text ^>=2.1++test-suite effectful-mcp-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , aeson+ , base+ , bytestring+ , effectful+ , effectful-core+ , effectful-mcp+ , stm ^>=2.5+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10+ , text
+ src/Effectful/MCP/JsonRpc.hs view
@@ -0,0 +1,135 @@+-- |+-- Module : Effectful.MCP.JsonRpc+-- Description : JSON-RPC 2.0 messages, as an MCP server sees them+-- License : BSD-3-Clause+--+-- MCP messages are JSON-RPC 2.0 messages, with two restrictions: a request+-- identifier is never @null@, and there is no batch.+module Effectful.MCP.JsonRpc+ ( -- * Incoming messages+ RequestId (..)+ , Incoming (..)+ , decodeIncoming++ -- * Outgoing messages+ , ErrorObject (..)+ , encodeResult+ , encodeError++ -- * Error codes+ , parseError+ , invalidRequest+ , methodNotFound+ , invalidParams+ , internalError+ , unsupportedProtocolVersion+ ) where++import Data.Aeson (FromJSON (..), Object, ToJSON (..), Value (..),+ eitherDecodeStrict, encode, object, (.=))+import Data.Aeson.KeyMap (empty, member)+import Data.Aeson.KeyMap qualified as JK (lookup)+import Data.Aeson.Types (parseMaybe)+import Data.ByteString (ByteString)+import Data.ByteString.Lazy (toStrict)+import Data.Maybe (catMaybes)+import Data.Scientific (floatingOrInteger)+import Data.Text (Text, pack)++-- | A request identifier: a string or an integer.+data RequestId = RequestIdText Text | RequestIdNumber Integer+ deriving stock (Eq, Ord, Show)++instance ToJSON RequestId where+ toJSON = \case+ RequestIdText text -> String text+ RequestIdNumber number -> Number (fromInteger number)++instance FromJSON RequestId where+ parseJSON = \case+ String text -> pure (RequestIdText text)+ Number number | Right integer <- floatingOrInteger @Double number -> pure (RequestIdNumber integer)+ _ -> fail "a request id is a string or an integer"++-- | A message read from the client.+data Incoming+ = -- | A request: its identifier, its method and its parameters.+ Request RequestId Text Object+ | -- | A notification: its method and its parameters.+ Notification Text Object+ | -- | A response, which a client must not send on stdio.+ Response+ | -- | A message that cannot be served, with the error to answer, and+ -- the identifier when it could be read.+ Invalid (Maybe RequestId) ErrorObject+ deriving stock (Eq, Show)++-- | Read one message.+decodeIncoming :: ByteString -> Incoming+decodeIncoming bytes = case eitherDecodeStrict bytes of+ Left err -> Invalid Nothing (parseError ("Parse error: " <> pack err))+ Right (Object fields) -> fromObject fields+ Right (Array _) -> Invalid Nothing (invalidRequest "Batches are not supported")+ Right _ -> Invalid Nothing (invalidRequest "A message is a JSON object")+ where+ fromObject fields+ | JK.lookup "jsonrpc" fields /= Just (String "2.0") = Invalid identifier (invalidRequest "jsonrpc must be \"2.0\"")+ | otherwise = case (JK.lookup "method" fields, JK.lookup "id" fields) of+ (Just (String method), Nothing) -> withParams (Notification method)+ (Just (String method), Just _) -> case identifier of+ Just requestId -> withParams (Request requestId method)+ Nothing -> Invalid Nothing (invalidRequest "A request id is a string or an integer, never null")+ (Just _, _) -> Invalid identifier (invalidRequest "method must be a string")+ (Nothing, _)+ | member "result" fields || member "error" fields -> Response+ | otherwise -> Invalid identifier (invalidRequest "No method")+ where+ identifier = JK.lookup "id" fields >>= parseMaybe parseJSON+ withParams build = case JK.lookup "params" fields of+ Nothing -> build empty+ Just (Object params) -> build params+ Just _ -> Invalid identifier (invalidParams "params must be an object")++-- | A JSON-RPC error.+data ErrorObject = ErrorObject+ { code :: Int+ , message :: Text+ , errorData :: Maybe Value+ }+ deriving stock (Eq, Show)++instance ToJSON ErrorObject where+ toJSON ErrorObject {code, message, errorData} =+ object (["code" .= code, "message" .= message] <> catMaybes [("data" .=) <$> errorData])++-- | A result response, as one line without its end.+encodeResult :: RequestId -> Value -> ByteString+encodeResult requestId result =+ toStrict (encode (object ["jsonrpc" .= ("2.0" :: Text), "id" .= requestId, "result" .= result]))++-- | An error response, as one line without its end. The identifier is+-- left out when it could not be read.+encodeError :: Maybe RequestId -> ErrorObject -> ByteString+encodeError requestId err =+ toStrict . encode . object $+ ["jsonrpc" .= ("2.0" :: Text), "error" .= err] <> catMaybes [("id" .=) <$> requestId]++-- | The errors JSON-RPC defines, each with its code and a message: the+-- input is not JSON (-32700), is not a request (-32600), names a method+-- that does not exist (-32601), has parameters that do not fit (-32602),+-- or the server failed (-32603).+parseError, invalidRequest, methodNotFound, invalidParams, internalError :: Text -> ErrorObject+parseError message = ErrorObject {code = -32700, message, errorData = Nothing}+invalidRequest message = ErrorObject {code = -32600, message, errorData = Nothing}+methodNotFound message = ErrorObject {code = -32601, message, errorData = Nothing}+invalidParams message = ErrorObject {code = -32602, message, errorData = Nothing}+internalError message = ErrorObject {code = -32603, message, errorData = Nothing}++-- | The version a request asked for is not served: lists those that are.+unsupportedProtocolVersion :: [Text] -> Text -> ErrorObject+unsupportedProtocolVersion supported requested =+ ErrorObject+ { code = -32022+ , message = "Unsupported protocol version"+ , errorData = Just (object ["supported" .= supported, "requested" .= requested])+ }
+ src/Effectful/MCP/Server.hs view
@@ -0,0 +1,306 @@+-- |+-- Module : Effectful.MCP.Server+-- Description : An MCP server of tools, over stdio+-- License : BSD-3-Clause+--+-- A server of the Model Context Protocol which offers tools, for clients+-- of two eras, as revision 2026-07-28 allows a server to be.+--+-- * Revision 2026-07-28 is stateless: every request carries its protocol+-- version and the capabilities of the client in its @_meta@, and is+-- served on its own. The server answers @server/discover@, @tools/list@+-- and @tools/call@; a request in another version gets an+-- @UnsupportedProtocolVersionError@.+--+-- * Earlier revisions (2025-11-25 and before) start with @initialize@.+-- That request selects their semantics for the connection: from then+-- on, requests without the @_meta@ of the new revision are served as+-- those revisions describe (@tools/list@, @tools/call@, @ping@).+--+-- Both are served at once on one connection: what a request carries tells+-- which it is.+--+-- Requests are served concurrently, each in a thread of its own, as+-- Effectful forks threads: a tool that changes a local @State@ does so in+-- its own copy. @notifications/cancelled@ stops a request, which then gets+-- no answer.+module Effectful.MCP.Server+ ( -- * Configuration+ ServerConfig (..)+ , serverConfig+ , Implementation (..)+ , implementation+ , protocolVersion+ , legacyVersions++ -- * Serving+ , serveStdio+ , serve+ , handleRequest+ , handleLegacyRequest+ ) where++import Control.Monad (forM_, void)+import Data.Aeson (FromJSON (parseJSON), Key, Object, ToJSON (..), Value (..),+ object, (.=))+import Data.Aeson.KeyMap qualified as JK (empty, lookup, member)+import Data.Aeson.Types (parseMaybe)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS (init)+import Data.ByteString.Char8 (hGetLine, hPutStrLn, isSuffixOf)+import Data.ByteString.Char8 qualified as BS8 (all)+import Data.List (find)+import Data.Map.Strict (adjust, delete, elems, insert)+import Data.Map.Strict qualified as M (empty, lookup, member)+import Data.Maybe (catMaybes, listToMaybe)+import Data.Text (Text, pack)+import Effectful (Eff, IOE, MonadIO (liftIO), type (:>))+import Effectful.Concurrent (Concurrent, threadDelay)+import Effectful.Concurrent.Async (Async, async, cancel, race, waitCatch)+import Effectful.Concurrent.MVar (newMVar, withMVar)+import Effectful.Concurrent.STM (atomically, modifyTVar', newTVarIO, readTVar,+ readTVarIO, writeTVar)+import Effectful.Exception (trySync)+import Effectful.MCP.JsonRpc (ErrorObject,+ Incoming (Invalid, Notification, Request, Response),+ decodeIncoming, encodeError, encodeResult,+ internalError, invalidParams, methodNotFound,+ unsupportedProtocolVersion)+import Effectful.MCP.Tool (Tool (..), errorResult, toolDefinition,+ toolResultValue)+import Streamly.Data.Fold (drainMapM)+import Streamly.Data.Stream (fold, unfoldrM)+import Streamly.Data.Stream qualified as S (filter)+import System.IO (hFlush, hSetBinaryMode, isEOF, stdin, stdout)++-- | The stateless revision of the protocol this server speaks.+protocolVersion :: Text+protocolVersion = "2026-07-28"++-- | The earlier revisions this server speaks to a client that starts with+-- @initialize@, the latest first. For a server that only offers tools,+-- they differ by fields that older clients leave aside.+legacyVersions :: [Text]+legacyVersions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]++-- | The name and version of a server, as it reports them.+data Implementation = Implementation+ { name :: Text+ , version :: Text+ , title :: Maybe Text+ }+ deriving stock (Eq, Show)++-- | A name and a version, without title. Field names such as @name@ are+-- shared with t'Tool', which makes record syntax ambiguous without+-- @DuplicateRecordFields@.+implementation :: Text -> Text -> Implementation+implementation name version = Implementation {name, version, title = Nothing}++instance ToJSON Implementation where+ toJSON Implementation {name, version, title} =+ object (["name" .= name, "version" .= version] <> catMaybes [("title" .=) <$> title])++-- | What a server is: who it says it is, what it offers and how it+-- behaves. Start from 'serverConfig'.+data ServerConfig es = ServerConfig+ { info :: Implementation+ , instructions :: Maybe Text+ -- ^ Guidance for the model on how to use the server.+ , tools :: [Tool es]+ -- ^ Listed in this order.+ , cacheTtlMs :: Int+ -- ^ How long a client may keep the discovery and the list of tools, in+ -- milliseconds.+ , shutdownGrace :: Int+ -- ^ Once the input ends, how long the requests still running may take to+ -- finish, in microseconds, before they are stopped.+ }++-- | A server with no instructions, a cache of five minutes and two seconds+-- to finish at shutdown.+serverConfig :: Implementation -> [Tool es] -> ServerConfig es+serverConfig info tools =+ ServerConfig {info, instructions = Nothing, tools, cacheTtlMs = 300_000, shutdownGrace = 2_000_000}++-- | Serve on the standard input and output: one message per line. Ends+-- when the input ends.+serveStdio :: (IOE :> es, Concurrent :> es) => ServerConfig es -> Eff es ()+serveStdio config = do+ liftIO $ do+ hSetBinaryMode stdin True+ hSetBinaryMode stdout True+ serve config readLine writeLine+ where+ readLine =+ liftIO $+ isEOF >>= \case+ True -> pure Nothing+ False -> Just . stripReturn <$> hGetLine stdin+ stripReturn line = if isSuffixOf "\r" line then BS.init line else line+ writeLine line = liftIO (hPutStrLn stdout line >> hFlush stdout)++-- | A request being served: registered before it starts, so that its+-- answer can tell whether it was cancelled meanwhile.+newtype Running es = Running (Maybe (Async ()))++-- | Serve messages read one line at a time, until the input ends.+-- 'Nothing' ends the input. Answers are written whole, one at a time.+serve+ :: Concurrent :> es+ => ServerConfig es+ -> Eff es (Maybe ByteString)+ -> (ByteString -> Eff es ())+ -> Eff es ()+serve config readLine writeLine = do+ lock <- newMVar ()+ running <- newTVarIO M.empty+ -- Whether a client has selected the earlier revisions with initialize.+ legacy <- newTVarIO False+ let send line = withMVar lock (const (writeLine line))+ fold (drainMapM (dispatch legacy running send)) $+ S.filter (not . BS8.all (`elem` (" \t" :: String))) (unfoldrM (const (fmap (,()) <$> readLine)) ())+ shutDown running+ where+ dispatch legacy running send line = case decodeIncoming line of+ Request requestId method params -> do+ -- The era is settled before the request starts, so that what+ -- follows an initialize is read as it should be.+ era <- atomically $ do+ if method == "initialize" then writeTVar legacy True else pure ()+ selected <- readTVar legacy+ pure (if selected && not (carriesModernMeta params) then handleLegacyRequest else handleRequest)+ start running send requestId (era config method params)+ Notification "notifications/cancelled" params ->+ forM_ (JK.lookup "requestId" params >>= parseMaybe parseJSON) (stop running)+ Notification _ _ -> pure ()+ Response -> pure ()+ Invalid requestId err -> send (encodeError requestId err)++ start running send requestId answerRequest = do+ atomically (modifyTVar' running (insert requestId (Running Nothing)))+ worker <- async $ do+ outcome <- trySync answerRequest+ let answer = case outcome of+ Right (Right result) -> encodeResult requestId result+ Right (Left err) -> encodeError (Just requestId) err+ Left exception -> encodeError (Just requestId) (internalError (pack (show exception)))+ stillWanted <- atomically $ do+ current <- readTVar running+ writeTVar running (delete requestId current)+ pure (M.member requestId current)+ if stillWanted then send answer else pure ()+ -- Record the thread, unless the request is already over.+ atomically $ modifyTVar' running (adjust (const (Running (Just worker))) requestId)++ stop running requestId = do+ entry <- atomically $ do+ current <- readTVar running+ writeTVar running (delete requestId current)+ pure (M.lookup requestId current)+ forM_ entry $ \(Running worker) -> forM_ worker cancel++ -- Let the requests still running finish, within the grace period,+ -- then stop the others.+ shutDown running = do+ workers <- runningWorkers <$> readTVarIO running+ void (race (threadDelay config.shutdownGrace) (mapM_ waitCatch workers))+ readTVarIO running >>= mapM_ cancel . runningWorkers++ runningWorkers current = [worker | Running (Just worker) <- elems current]++-- | Whether a request carries the protocol version of the stateless+-- revision, which makes it one of that revision whatever came before.+carriesModernMeta :: Object -> Bool+carriesModernMeta params = case JK.lookup "_meta" params of+ Just (Object meta) -> JK.member "io.modelcontextprotocol/protocolVersion" meta+ _ -> False++-- | Answer one request of the earlier revisions: a result, or a protocol+-- error. @initialize@ answers the version asked when it is one of+-- 'legacyVersions', and the latest of them otherwise, which the client+-- takes or leaves.+handleLegacyRequest :: ServerConfig es -> Text -> Object -> Eff es (Either ErrorObject Value)+handleLegacyRequest config method params = case method of+ "initialize" ->+ pure . Right . object $+ [ "protocolVersion" .= negotiated+ , "capabilities" .= object ["tools" .= object ["listChanged" .= False]]+ , "serverInfo" .= config.info+ ]+ <> catMaybes [("instructions" .=) <$> config.instructions]+ "ping" -> pure (Right (object []))+ "tools/list"+ | JK.member "cursor" params -> pure (Left (invalidParams "Unknown cursor: the list has one page"))+ | otherwise -> pure (Right (object ["tools" .= map toolDefinition config.tools]))+ "tools/call" -> callToolWith object config params+ _ -> pure (Left (methodNotFound ("Method not found: " <> method)))+ where+ requested = stringField "protocolVersion" params+ negotiated = if requested `elem` legacyVersions then requested else maybe protocolVersion id (listToMaybe legacyVersions)++-- | Answer one request of the stateless revision: a result, or a protocol+-- error. An @initialize@, which belongs to the earlier revisions, is+-- answered as 'handleLegacyRequest' does.+handleRequest :: ServerConfig es -> Text -> Object -> Eff es (Either ErrorObject Value)+handleRequest config method params+ | method == "initialize" = handleLegacyRequest config method params+ | otherwise = case checkMeta params of+ Left err -> pure (Left err)+ Right () -> case method of+ "server/discover" ->+ pure . Right . complete config $+ cacheable config+ <> [ "supportedVersions" .= [protocolVersion]+ , "capabilities" .= object ["tools" .= object []]+ ]+ <> catMaybes [("instructions" .=) <$> config.instructions]+ "tools/list"+ | JK.member "cursor" params -> pure (Left (invalidParams "Unknown cursor: the list has one page"))+ | otherwise -> pure . Right . complete config $ ("tools" .= map toolDefinition config.tools) : cacheable config+ "tools/call" -> callToolWith (complete config) config params+ _ -> pure (Left (methodNotFound ("Method not found: " <> method)))++-- | Call a tool, and wrap the fields of its result as a revision wants.+callToolWith :: ([(Key, Value)] -> Value) -> ServerConfig es -> Object -> Eff es (Either ErrorObject Value)+callToolWith wrap config params = case JK.lookup "name" params of+ Just (String toolName) -> case find (\candidate -> candidate.name == toolName) config.tools of+ Nothing -> pure (Left (invalidParams ("Unknown tool: " <> toolName)))+ Just found -> case JK.lookup "arguments" params of+ Nothing -> run found (Object JK.empty)+ Just arguments@(Object _) -> run found arguments+ Just _ -> pure (Left (invalidParams "arguments must be an object"))+ _ -> pure (Left (invalidParams "name must be a string"))+ where+ run found arguments = do+ outcome <- trySync (found.call arguments)+ let result = either (\exception -> errorResult ("Internal error: " <> pack (show exception))) id outcome+ pure (Right (wrap (toolResultValue result)))++-- | Check the fields every request must carry, and the version.+checkMeta :: Object -> Either ErrorObject ()+checkMeta params = case JK.lookup "_meta" params of+ Just (Object meta) -> case (JK.lookup "io.modelcontextprotocol/protocolVersion" meta, JK.lookup "io.modelcontextprotocol/clientCapabilities" meta) of+ (Just (String requested), Just (Object _))+ | requested == protocolVersion -> Right ()+ | otherwise -> Left (unsupportedProtocolVersion [protocolVersion] requested)+ (Just (String _), _) -> Left (invalidParams "Missing _meta.io.modelcontextprotocol/clientCapabilities")+ _ -> Left (invalidParams "Missing _meta.io.modelcontextprotocol/protocolVersion")+ _ -> Left (invalidParams "Missing _meta: in revision 2026-07-28 every request carries its protocol version; the earlier revisions start with initialize")++complete :: ServerConfig es -> [(Key, Value)] -> Value+complete config fields =+ object $+ [ "resultType" .= ("complete" :: Text)+ , "_meta" .= object ["io.modelcontextprotocol/serverInfo" .= config.info]+ ]+ <> fields++cacheable :: ServerConfig es -> [(Key, Value)]+cacheable config = ["ttlMs" .= config.cacheTtlMs, "cacheScope" .= ("public" :: Text)]++stringField :: Key -> Object -> Text+stringField key fields = case JK.lookup key fields of+ Just (String text) -> text+ _ -> ""+
+ src/Effectful/MCP/Tool.hs view
@@ -0,0 +1,156 @@+-- |+-- Module : Effectful.MCP.Tool+-- Description : Tools that an MCP server offers, and what they return+-- License : BSD-3-Clause+module Effectful.MCP.Tool+ ( -- * Tools+ Tool (..)+ , tool+ , ToolAnnotations (..)+ , noAnnotations+ , withArguments++ -- * Results+ , ToolResult (..)+ , Content (..)+ , textResult+ , imageResult+ , structuredResult+ , errorResult++ -- * Encoding+ , toolDefinition+ , toolResultValue+ ) where++import Data.Aeson (FromJSON, Key, ToJSON (..), Value (..), object, (.=))+import Data.Aeson qualified as J (encode)+import Data.Aeson.Types (parseEither, parseJSON)+import Data.ByteString (ByteString)+import Data.ByteString.Base64 qualified as B64 (encode)+import Data.ByteString.Lazy (toStrict)+import Data.Maybe (catMaybes)+import Data.Text (Text, pack)+import Data.Text.Encoding (decodeUtf8)+import Effectful (Eff)++-- | A tool: what the client lists, and what runs when it is called.+data Tool es = Tool+ { name :: Text+ -- ^ Letters, digits, @_@, @-@ and @.@, at most 128 of them.+ , title :: Maybe Text+ -- ^ For display.+ , description :: Text+ , inputSchema :: Value+ -- ^ A JSON Schema (2020-12 unless it says otherwise) of the arguments,+ -- with @"type": "object"@.+ , outputSchema :: Maybe Value+ -- ^ A JSON Schema of the structured content, if the tool returns some.+ , annotations :: ToolAnnotations+ , call :: Value -> Eff es ToolResult+ -- ^ Receives the arguments, an object.+ }++-- | A tool with no title, no output schema and no annotation.+tool :: Text -> Text -> Value -> (Value -> Eff es ToolResult) -> Tool es+tool name description inputSchema call =+ Tool {name, title = Nothing, description, inputSchema, outputSchema = Nothing, annotations = noAnnotations, call}++-- | Hints about what a tool does. Clients treat them as untrusted unless+-- they trust the server.+data ToolAnnotations = ToolAnnotations+ { readOnlyHint :: Maybe Bool+ -- ^ The tool changes nothing.+ , destructiveHint :: Maybe Bool+ -- ^ The tool may destroy something, rather than only add.+ , idempotentHint :: Maybe Bool+ -- ^ Calling it again with the same arguments has no further effect.+ , openWorldHint :: Maybe Bool+ -- ^ The tool reaches outside entities.+ }+ deriving stock (Eq, Show)++-- | No hint at all.+noAnnotations :: ToolAnnotations+noAnnotations = ToolAnnotations Nothing Nothing Nothing Nothing++-- | Decode the arguments before running the tool. Arguments that do not+-- decode give an error result that tells the model what is wrong, so that+-- it can call again.+withArguments :: FromJSON a => (a -> Eff es ToolResult) -> Value -> Eff es ToolResult+withArguments run arguments = case parseEither parseJSON arguments of+ Right decoded -> run decoded+ Left err -> pure (errorResult ("Invalid arguments: " <> pack err))++-- | What a call returns.+data ToolResult = ToolResult+ { content :: [Content]+ , structuredContent :: Maybe Value+ , isError :: Bool+ -- ^ The tool failed; the content says why, for the model to correct.+ }+ deriving stock (Eq, Show)++-- | Content of a result.+data Content+ = TextContent Text+ | -- | An image: its media type, such as @image\/jpeg@, and its bytes.+ -- They are sent in base64.+ ImageContent Text ByteString+ deriving stock (Eq, Show)++-- | A text.+textResult :: Text -> ToolResult+textResult text = ToolResult {content = [TextContent text], structuredContent = Nothing, isError = False}++-- | An image, from its media type and its bytes.+imageResult :: Text -> ByteString -> ToolResult+imageResult mimeType bytes = ToolResult {content = [ImageContent mimeType bytes], structuredContent = Nothing, isError = False}++-- | A structured result, also given as JSON text for clients that only+-- read text, as the specification recommends.+structuredResult :: ToJSON a => a -> ToolResult+structuredResult value =+ ToolResult+ { content = [TextContent (decodeUtf8 (toStrict (J.encode value)))]+ , structuredContent = Just (toJSON value)+ , isError = False+ }++-- | A failure the model can act on.+errorResult :: Text -> ToolResult+errorResult text = ToolResult {content = [TextContent text], structuredContent = Nothing, isError = True}++-- | The definition of a tool, as @tools/list@ gives it.+toolDefinition :: Tool es -> Value+toolDefinition Tool {name, title, description, inputSchema, outputSchema, annotations} =+ object $+ ["name" .= name, "description" .= description, "inputSchema" .= inputSchema]+ <> catMaybes+ [ ("title" .=) <$> title+ , ("outputSchema" .=) <$> outputSchema+ , ("annotations" .=) <$> annotationsValue annotations+ ]++annotationsValue :: ToolAnnotations -> Maybe Value+annotationsValue ToolAnnotations {readOnlyHint, destructiveHint, idempotentHint, openWorldHint} =+ case catMaybes+ [ ("readOnlyHint" .=) <$> readOnlyHint+ , ("destructiveHint" .=) <$> destructiveHint+ , ("idempotentHint" .=) <$> idempotentHint+ , ("openWorldHint" .=) <$> openWorldHint+ ] of+ [] -> Nothing+ hints -> Just (object hints)++-- | The fields of a @tools/call@ result, without @resultType@ and @_meta@.+toolResultValue :: ToolResult -> [(Key, Value)]+toolResultValue ToolResult {content, structuredContent, isError} =+ ["content" .= map contentValue content]+ <> catMaybes [("structuredContent" .=) <$> structuredContent]+ <> ["isError" .= True | isError]+ where+ contentValue = \case+ TextContent text -> object ["type" .= ("text" :: Text), "text" .= text]+ ImageContent mimeType bytes ->+ object ["type" .= ("image" :: Text), "data" .= decodeUtf8 (B64.encode bytes), "mimeType" .= mimeType]
+ test/Main.hs view
@@ -0,0 +1,317 @@+-- | The server, fed and read through in-memory queues.+module Main (main) where++import Control.Concurrent.STM (TMVar, TVar, atomically, flushTQueue,+ newEmptyTMVarIO, newTQueueIO, newTVarIO,+ putTMVar, readTMVar, readTQueue, readTVarIO,+ tryReadTMVar, writeTQueue, writeTVar)+import Data.Aeson (FromJSON (..), Key, ToJSON (toJSON), Value (..),+ decodeStrict, encode, object, withObject, (.:), (.=))+import Data.Aeson.KeyMap (keys)+import Data.Aeson.KeyMap qualified as JK (lookup)+import Data.ByteString (ByteString)+import Data.ByteString.Lazy (toStrict)+import Data.Text (Text)+import Effectful (IOE, MonadIO (liftIO), runEff)+import Effectful.Concurrent (Concurrent, runConcurrent)+import Effectful.Concurrent.Async (wait, withAsync)+import Effectful.Exception (finally)+import Effectful.MCP.Server (Implementation (Implementation, name, title, version),+ ServerConfig (shutdownGrace), serve, serverConfig)+import Effectful.MCP.Tool (Tool (annotations), ToolAnnotations (readOnlyHint),+ imageResult, noAnnotations, structuredResult,+ textResult, tool, toolResultValue, withArguments)+import Test.Tasty (TestTree, defaultMain, localOption, mkTimeout, testGroup)+import Test.Tasty.HUnit (Assertion, assertFailure, testCase, (@?=))++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+ localOption (mkTimeout 10_000_000) $+ testGroup+ "effectful-mcp"+ [ testGroup+ "methods"+ [ testCase "server/discover" $ do+ result <- expectResult =<< exchange (request 1 "server/discover" [])+ field "resultType" result @?= Just (String "complete")+ field "supportedVersions" result @?= Just (toJSON ["2026-07-28" :: Text])+ field "capabilities" result @?= Just (object ["tools" .= object []])+ field "ttlMs" result @?= Just (Number 300000)+ field "cacheScope" result @?= Just (String "public")+ (field "_meta" result >>= field "io.modelcontextprotocol/serverInfo") @?= Just (object ["name" .= ("test-server" :: Text), "version" .= ("1.0" :: Text)])+ , testCase "tools/list gives the tools in order" $ do+ result <- expectResult =<< exchange (request 1 "tools/list" [])+ case field "tools" result of+ Just (Array tools) -> do+ map (field "name") (foldr (:) [] tools) @?= map (Just . String) ["echo", "add", "fail", "wait"]+ (field "annotations" =<< headMaybe tools) @?= Just (object ["readOnlyHint" .= True])+ other -> assertFailure ("no tools: " <> show other)+ field "ttlMs" result @?= Just (Number 300000)+ , testCase "tools/call returns text" $ do+ result <- expectResult =<< exchange (call 1 "echo" (object ["text" .= ("hello" :: Text)]))+ field "content" result @?= Just (toJSON [object ["type" .= ("text" :: Text), "text" .= ("hello" :: Text)]])+ field "isError" result @?= Nothing+ , testCase "tools/call returns structured content, also as text" $ do+ result <- expectResult =<< exchange (call 1 "add" (object ["a" .= (2 :: Int), "b" .= (3 :: Int)]))+ field "structuredContent" result @?= Just (object ["sum" .= (5 :: Int)])+ field "content" result @?= Just (toJSON [object ["type" .= ("text" :: Text), "text" .= ("{\"sum\":5}" :: Text)]])+ , testCase "arguments that do not decode give an error result" $ do+ result <- expectResult =<< exchange (call 1 "add" (object ["a" .= ("two" :: Text)]))+ field "isError" result @?= Just (Bool True)+ , testCase "a tool that throws gives an error result" $ do+ result <- expectResult =<< exchange (call 1 "fail" (object []))+ field "isError" result @?= Just (Bool True)+ , testCase "an image result carries its media type and its bytes in base64" $+ lookup "content" (toolResultValue (imageResult "image/png" "\137PNG"))+ @?= Just (toJSON [object ["type" .= ("image" :: Text), "data" .= ("iVBORw==" :: Text), "mimeType" .= ("image/png" :: Text)]])+ ]+ , testGroup+ "protocol errors"+ [ testCase "unknown tool" $ exchange (call 1 "nope" (object [])) >>= expectError (-32602)+ , testCase "missing _meta" $+ exchange (line (object ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int), "method" .= ("tools/list" :: Text)])) >>= expectError (-32602)+ , testCase "unsupported version" $ do+ response <- exchange (requestIn "2025-11-25" 1 "tools/list" [])+ expectError (-32022) response+ (field "error" response >>= field "data") @?= Just (object ["supported" .= ["2026-07-28" :: Text], "requested" .= ("2025-11-25" :: Text)])+ , testCase "a request of an earlier revision before any initialize" $+ exchange (legacy 1 "tools/call" ["name" .= ("echo" :: Text), "arguments" .= object ["text" .= ("hello" :: Text)]]) >>= expectError (-32602)+ , testCase "unknown method" $ exchange (request 1 "prompts/list" []) >>= expectError (-32601)+ , testCase "malformed JSON, without id" $ do+ response <- exchange "{not json"+ expectError (-32700) response+ field "id" response @?= Nothing+ , testCase "batch" $ exchange "[]" >>= expectError (-32600)+ ]+ , testGroup+ "earlier revisions"+ [ testCase "initialize answers the version asked, the capabilities and the server" $ do+ result <- expectResult =<< exchange (initialize 1 "2025-06-18")+ result+ @?= object+ [ "protocolVersion" .= ("2025-06-18" :: Text)+ , "capabilities" .= object ["tools" .= object ["listChanged" .= False]]+ , "serverInfo" .= object ["name" .= ("test-server" :: Text), "version" .= ("1.0" :: Text)]+ ]+ , testCase "initialize answers its latest earlier revision to a version it does not know" $ do+ answers <- mapM (\asked -> (field "protocolVersion" =<<) . field "result" <$> exchange (initialize 1 asked)) ["2025-11-25", "2024-11-05", "1900-01-01", "2026-07-28"]+ answers @?= map (Just . String) ["2025-11-25", "2024-11-05", "2025-11-25", "2025-11-25"]+ , testCase "after initialize, the tools are listed and called as those revisions do" $ do+ responses <- session $ \push pull -> do+ push (initialize 1 "2025-11-25")+ _ <- pull+ push (line (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/initialized" :: Text)]))+ push (legacy 2 "tools/list" [])+ listed <- pull+ push (legacy 3 "tools/call" ["name" .= ("add" :: Text), "arguments" .= object ["a" .= (2 :: Int), "b" .= (3 :: Int)]])+ called <- pull+ push (legacy 4 "ping" [])+ pinged <- pull+ pure [listed, called, pinged]+ case responses of+ [listed, called, pinged] -> do+ result <- expectResult listed+ case result of+ Object fields -> do+ keys fields @?= ["tools"]+ fmap (\case Array tools -> map (field "name") (foldr (:) [] tools); _ -> []) (field "tools" result)+ @?= Just (map (Just . String) ["echo", "add", "fail", "wait"])+ other -> assertFailure ("not an object: " <> show other)+ sum' <- expectResult called+ sum'+ @?= object+ [ "content" .= [object ["type" .= ("text" :: Text), "text" .= ("{\"sum\":5}" :: Text)]]+ , "structuredContent" .= object ["sum" .= (5 :: Int)]+ ]+ field "result" pinged @?= Just (object [])+ other -> assertFailure ("expected three answers, got " <> show other)+ , testCase "after initialize, errors are those of the protocol" $ do+ responses <- session $ \push pull -> do+ push (initialize 1 "2025-11-25")+ _ <- pull+ push (legacy 2 "tools/call" ["name" .= ("nope" :: Text)])+ unknownTool <- pull+ push (legacy 3 "prompts/list" [])+ unknownMethod <- pull+ push (legacy 4 "tools/list" ["cursor" .= ("next" :: Text)])+ cursor <- pull+ pure [unknownTool, unknownMethod, cursor]+ map (\response -> field "error" response >>= field "code") responses @?= map (Just . Number) [-32602, -32601, -32602]+ , testCase "both eras are served on one connection" $ do+ responses <- session $ \push pull -> do+ push (initialize 1 "2025-11-25")+ _ <- pull+ push (request 2 "tools/list" [])+ modern <- pull+ push (legacy 3 "tools/list" [])+ earlier <- pull+ pure [modern, earlier]+ map (\response -> field "result" response >>= field "resultType") responses @?= [Just (String "complete"), Nothing]+ ]+ , testGroup+ "serving"+ [ testCase "a notification gets no answer" $ do+ responses <- session $ \push pull -> do+ push (line (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/initialized" :: Text)]))+ push (request 2 "tools/list" [])+ (: []) <$> pull+ map (field "id") responses @?= [Just (Number 2)]+ , testCase "a slow call does not hold up the others" $ do+ gate <- newEmptyTMVarIO+ responses <- sessionWith gate $ \push pull -> do+ push (call 1 "wait" (object []))+ push (call 2 "echo" (object ["text" .= ("fast" :: Text)]))+ first <- pull+ atomically (putTMVar gate ())+ second <- pull+ pure [first, second]+ map (field "id") responses @?= [Just (Number 2), Just (Number 1)]+ , testCase "a cancelled call stops and gets no answer" $ do+ gate <- newEmptyTMVarIO+ responses <- sessionWith gate $ \push pull -> do+ push (call 7 "wait" (object []))+ push (line (object ["jsonrpc" .= ("2.0" :: Text), "method" .= ("notifications/cancelled" :: Text), "params" .= object ["requestId" .= (7 :: Int)]]))+ push (call 8 "echo" (object ["text" .= ("after" :: Text)]))+ (: []) <$> pull+ map (field "id") responses @?= [Just (Number 8)]+ , testCase "calls still running when the input ends may finish" $ do+ gate <- newEmptyTMVarIO+ output <- newTQueueIO+ input <- newTQueueIO+ let config = (testConfig gate) {shutdownGrace = 5_000_000}+ runEff . runConcurrent $+ withAsync (serve config (liftIO (atomically (readTQueue input))) (liftIO . atomically . writeTQueue output)) $ \server -> do+ liftIO . atomically $ do+ writeTQueue input (Just (call 1 "wait" (object [])))+ writeTQueue input Nothing+ liftIO (atomically (putTMVar gate ()))+ wait server+ responses <- atomically (flushTQueue output)+ map (field "id" . decode) responses @?= [Just (Number 1)]+ , testCase "calls still running after the grace period are stopped" $ do+ gate <- newEmptyTMVarIO+ output <- newTQueueIO+ input <- newTQueueIO+ stopped <- newTVarIO False+ let config = (testConfigStopping gate stopped) {shutdownGrace = 50_000}+ runEff . runConcurrent $ do+ liftIO . atomically $ do+ writeTQueue input (Just (call 1 "wait" (object [])))+ writeTQueue input Nothing+ serve config (liftIO (atomically (readTQueue input))) (liftIO . atomically . writeTQueue output)+ atomically (flushTQueue output) >>= (@?= [])+ readTVarIO stopped >>= (@?= True)+ ]+ ]+ where+ headMaybe = foldr (\x _ -> Just x) Nothing++-- Tools++data AddArguments = AddArguments Int Int++instance FromJSON AddArguments where+ parseJSON = withObject "AddArguments" $ \fields -> AddArguments <$> fields .: "a" <*> fields .: "b"++newtype EchoArguments = EchoArguments Text++instance FromJSON EchoArguments where+ parseJSON = withObject "EchoArguments" $ \fields -> EchoArguments <$> fields .: "text"++testConfig :: TMVar () -> ServerConfig '[Concurrent, IOE]+testConfig gate = testConfigWith gate (pure ())++-- | 'testConfig', where the waiting tool records that it was stopped.+testConfigStopping :: TMVar () -> TVar Bool -> ServerConfig '[Concurrent, IOE]+testConfigStopping gate stopped = testConfigWith gate (atomically (writeTVar stopped True))++testConfigWith :: TMVar () -> IO () -> ServerConfig '[Concurrent, IOE]+testConfigWith gate onStop =+ serverConfig+ Implementation {name = "test-server", version = "1.0", title = Nothing}+ [ (tool "echo" "Echo the text" schema (withArguments (\(EchoArguments text) -> pure (textResult text))))+ { annotations = noAnnotations {readOnlyHint = Just True}+ }+ , tool "add" "Add two numbers" schema (withArguments (\(AddArguments a b) -> pure (structuredResult (object ["sum" .= (a + b)]))))+ , tool "fail" "Throw" schema (\_ -> error "boom")+ , tool "wait" "Wait for the gate" schema $ \_ ->+ (liftIO (atomically (readTMVar gate)) >> pure (textResult "done")) `finally` liftIO onStop'+ ]+ where+ schema = object ["type" .= ("object" :: Text)]+ -- Only a call that did not finish counts as stopped.+ onStop' = atomically (tryReadTMVar gate) >>= maybe onStop (const (pure ()))++-- Driving the server++-- | Send one message, and read the one answer.+exchange :: ByteString -> IO Value+exchange message =+ session (\push pull -> push message >> (: []) <$> pull) >>= \case+ [response] -> pure response+ other -> assertFailure ("expected one answer, got " <> show other)++session :: ((ByteString -> IO ()) -> IO Value -> IO [Value]) -> IO [Value]+session script = newEmptyTMVarIO >>= \gate -> sessionWith gate script++-- | Run the server while a script talks to it, then end the input.+sessionWith :: TMVar () -> ((ByteString -> IO ()) -> IO Value -> IO [Value]) -> IO [Value]+sessionWith gate script = do+ input <- newTQueueIO+ output <- newTQueueIO+ runEff . runConcurrent $+ withAsync (serve (testConfig gate) (liftIO (atomically (readTQueue input))) (liftIO . atomically . writeTQueue output)) $ \server -> do+ responses <- liftIO (script (atomically . writeTQueue input . Just) (decode <$> atomically (readTQueue output)))+ liftIO (atomically (writeTQueue input Nothing))+ wait server+ pure responses++decode :: ByteString -> Value+decode bytes = maybe (error ("not JSON: " <> show bytes)) id (decodeStrict bytes)++line :: Value -> ByteString+line = toStrict . encode++meta :: Text -> Value+meta version =+ object+ [ "io.modelcontextprotocol/protocolVersion" .= version+ , "io.modelcontextprotocol/clientCapabilities" .= object []+ , "io.modelcontextprotocol/clientInfo" .= object ["name" .= ("test" :: Text), "version" .= ("0" :: Text)]+ ]++request :: Int -> Text -> [(Key, Value)] -> ByteString+request = requestIn "2026-07-28"++-- | A request as the earlier revisions write it: without the version.+legacy :: Int -> Text -> [(Key, Value)] -> ByteString+legacy requestId method params =+ line (object ["jsonrpc" .= ("2.0" :: Text), "id" .= requestId, "method" .= method, "params" .= object params])++-- | The handshake of the earlier revisions, asking for a version.+initialize :: Int -> Text -> ByteString+initialize requestId asked =+ legacy requestId "initialize" ["protocolVersion" .= asked, "capabilities" .= object [], "clientInfo" .= object ["name" .= ("test-client" :: Text), "version" .= ("0" :: Text)]]++requestIn :: Text -> Int -> Text -> [(Key, Value)] -> ByteString+requestIn version requestId method params =+ line (object ["jsonrpc" .= ("2.0" :: Text), "id" .= requestId, "method" .= method, "params" .= object (("_meta" .= meta version) : params)])++call :: Int -> Text -> Value -> ByteString+call requestId name arguments = request requestId "tools/call" ["name" .= name, "arguments" .= arguments]++field :: Key -> Value -> Maybe Value+field key = \case+ Object fields -> JK.lookup key fields+ _ -> Nothing++expectResult :: Value -> IO Value+expectResult response = case field "result" response of+ Just result -> pure result+ Nothing -> assertFailure ("not a result: " <> show response)++expectError :: Int -> Value -> Assertion+expectError expected response = (field "error" response >>= field "code") @?= Just (Number (fromIntegral expected))