mcp-server
Library for building Model Context Protocol (MCP) servers
https://github.com/drshade/haskell-mcp-server
| Version on this page: | 0.1.0.21 |
| LTS Haskell 24.53: | 0.1.0.21 |
| Stackage Nightly 2026-08-04: | 0.2.0.1 |
| Latest on Hackage: | 0.2.0.1 |
mcp-server-0.1.0.21@sha256:518f56e52ead0dc8288f6a00087edfb72e23d553fb00e68ec6478baf03b94274,6234Module documentation for 0.1.0.21
mcp-server
A fully-featured Haskell library for building Model Context Protocol (MCP) servers.
Features
- Complete MCP Implementation: Negotiates MCP protocol revisions
2024-11-05through2025-11-25(the shared wire format for tool/resource/prompt operations) - Type-Safe API: Leverage Haskell’s type system for robust MCP servers
- Multiple Abstractions: Both low-level fine-grained control and high-level derived interfaces
- Template Haskell Support: Automatic handler derivation from data types
- Multiple Transports: STDIO and HTTP Streaming transport (MCP Streamable HTTP)
Supported MCP Features
- ✅ Prompts: User-controlled prompt templates with arguments
- ✅ Resources: Application-controlled readable resources
- ✅ Tools: Model-controlled callable functions
- ✅ Initialization Flow: Complete protocol lifecycle with version negotiation
- ✅ Error Handling: Comprehensive error types and JSON-RPC error responses
Quick Start
Add the library mcp-server to your cabal file:
build-depends:
mcp-server
Create a simple module, such as this example below:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
import MCP.Server
import MCP.Server.Derive
-- Define your data types
data MyPrompt = Recipe { idea :: Text } | Shopping { items :: Text }
data MyResource = Menu | Specials
data MyTool = Search { query :: Text } | Order { item :: Text }
-- Implement handlers. Every handler receives the per-request 'ClientContext'
-- (the caller's bearer token and principal on the HTTP transport) first.
handlePrompt :: ClientContext -> MyPrompt -> IO Content
handlePrompt _ (Recipe idea) = pure $ ContentText $ "Recipe for " <> idea
handlePrompt _ (Shopping items) = pure $ ContentText $ "Shopping list: " <> items
handleResource :: ClientContext -> URI -> MyResource -> IO ResourceContent
handleResource _ uri Menu = pure $ ResourceText uri "text/plain" "Today's menu..."
handleResource _ uri Specials = pure $ ResourceText uri "text/plain" "Daily specials..."
handleTool :: ClientContext -> MyTool -> IO Content
handleTool _ (Search query) = pure $ ContentText $ "Search results for " <> query
handleTool _ (Order item) = pure $ ContentText $ "Ordered " <> item
-- Derive handlers automatically
main :: IO ()
main = runMcpServerStdio serverInfo handlers
where
serverInfo = McpServerInfo
{ serverName = "My MCP Server"
, serverVersion = "1.0.0"
, serverInstructions = "A sample MCP server"
}
handlers = McpServerHandlers
{ prompts = Just $(derivePromptHandler ''MyPrompt 'handlePrompt)
, resources = Just $(deriveResourceHandler ''MyResource 'handleResource)
, tools = Just $(deriveToolHandler ''MyTool 'handleTool)
}
Advanced Template Haskell Features
Automatic Naming Conventions
Constructor names are automatically converted to snake_case for MCP names:
data MyTool = GetValue | SetValue | SearchItems
-- Becomes: "get_value", "set_value", "search_items"
Automatic Type Conversion
The derivation system automatically converts Text arguments to appropriate Haskell types:
data MyTool = Calculate { number :: Int, factor :: Double, enabled :: Bool }
-- Text "42" -> Int 42
-- Text "3.14" -> Double 3.14
-- Text "true" -> Bool True
Supported conversions: Int, Integer, Double, Float, Bool, and Text (no conversion).
Nested Parameter Types
You can nest parameter types with automatic unwrapping:
-- Parameter record types
data GetValueParams = GetValueParams { _gvpKey :: Text }
data SetValueParams = SetValueParams { _svpKey :: Text, _svpValue :: Text }
-- Main tool type
data SimpleTool
= GetValue GetValueParams
| SetValue SetValueParams
deriving (Show, Eq)
The Template Haskell derivation recursively unwraps single-parameter constructors until it reaches a record type, then extracts all fields for the MCP schema.
Resource URI Generation
Resources automatically get resource:// URIs based on constructor names:
data MyResource = Menu | Specials
-- Generates: "resource://menu", "resource://specials"
Unsupported Patterns
We do not support positional (unnamed) parameters:
-- ❌ This won't work - no field names
data SimpleTool
= GetValue Int
| SetValue Int Text
All parameter types must ultimately resolve to records with named fields to generate proper MCP schemas.
Custom Descriptions
You can provide custom descriptions for constructors and fields using the *WithDescription variants:
-- Define descriptions for constructors and fields
descriptions :: [(String, String)]
descriptions =
[ ("Recipe", "Generate a recipe for a specific dish") -- Constructor description
, ("Search", "Search our menu database") -- Constructor description
, ("idea", "The dish you want a recipe for") -- Field description
, ("query", "Search terms to find menu items") -- Field description
]
-- Use in derivation
handlers = McpServerHandlers
{ prompts = Just $(derivePromptHandlerWithDescription ''MyPrompt 'handlePrompt descriptions)
, tools = Just $(deriveToolHandlerWithDescription ''MyTool 'handleTool descriptions)
, resources = Just $(deriveResourceHandlerWithDescription ''MyResource 'handleResource descriptions)
}
Manual Handler Implementation
For fine-grained control, implement handlers manually:
import MCP.Server
-- Manual handler implementation. Every handler receives the per-request
-- 'ClientContext' as its first argument.
promptListHandler :: ClientContext -> IO [PromptDefinition]
promptGetHandler :: ClientContext -> PromptName -> [(ArgumentName, ArgumentValue)] -> IO (Either Error Content)
-- ... implement your custom logic
main :: IO ()
main = runMcpServerStdio serverInfo handlers
where
handlers = McpServerHandlers
{ prompts = Just (promptListHandler, promptGetHandler)
, resources = Nothing -- Not supported
, tools = Nothing -- Not supported
}
HTTP Transport (NEW!)
The library supports the MCP Streamable HTTP transport. Compile your
executable with ghc-options: -threaded — Warp requires the threaded runtime:
import MCP.Server.Transport.Http
-- Simple HTTP server (localhost:3000/mcp)
main = runMcpServerHttp serverInfo handlers
-- Custom configuration
main = runMcpServerHttpWithConfig customConfig serverInfo handlers
where
customConfig = HttpConfig
{ httpPort = 8080
, httpHost = "0.0.0.0"
, httpEndpoint = "/api/mcp"
, httpVerbose = True -- Enable detailed logging
, httpAuthorize = Nothing -- No authentication (see below)
}
Bearer-token authentication (optional): supply an httpAuthorize callback
to validate the Authorization: Bearer token each request presents. Return
Just principal to authorize (the principal — any JSON Value, e.g. a role —
reaches your handlers as clientPrincipal in the ClientContext), or
Nothing to reject the request with 401. Token policy lives entirely in your
application; the library only threads the identity through:
customConfig = defaultHttpConfig
{ httpAuthorize = Just $ \mtoken -> case mtoken of
Just "secret-admin-token" -> pure $ Just (String "admin")
Just "secret-user-token" -> pure $ Just (String "user")
_ -> pure Nothing
}
Features:
- CORS enabled for web clients
- GET
/mcpfor server discovery - POST
/mcpfor JSON-RPC messages - Protocol-version negotiation across supported revisions (
2024-11-05–2025-11-25) - Optional pluggable bearer-token authentication via
httpAuthorize
Examples
The library includes several examples:
examples/Simple/: Basic key-value store using Template Haskell derivation (STDIO)examples/Complete/: Full-featured example with prompts, resources, and tools (STDIO)examples/HttpSimple/: HTTP version of the simple key-value store
Docker Usage
I like to build and publish my MCP servers to Docker - which means that it’s much easier to configure assistants such as Claude Desktop to run them.
# Build the image
docker build -t haskell-mcp-server .
# Run different examples
docker run -i --entrypoint="/usr/local/bin/simple-example" haskell-mcp-server
And then configure Claude by editing claude_desktop_config.json:
{
"mcpServers": {
"simple-example": {
"command": "docker",
"args": [
"run",
"-i",
"--entrypoint=/usr/local/bin/simple-example",
"haskell-mcp-server"
]
}
}
}
Documentation
Contributing
Contributions are welcome! Please see the issue tracker for open issues and feature requests.
Disclaimer - AI Assistance
I am not sure whether there is any stigma associated with this but Claude helped me write a lot of this library. I started with a very specific specification of what I wanted to achieve and worked shoulder-to-shoulder with Claude to implement and refactor the library until I was happy with it. A few of the features such as the Derive functions are a little out of my comfort zone to have manually written, so I appreciated having an expert guide me here - however I do suspect that this implementation may be sub-par and I do intend to refactor and rewrite large pieces of this through regular maintenance.
License
BSD-3-Clause
Changes
Revision history for mcp-server
0.1.0.21 - ???
- BREAKING: every handler (prompt/resource/tool; list and get/read/call)
now receives a
ClientContextas its first argument, so a server can behave differently depending on who is calling. On stdio the context is anonymous; on HTTP it carries the request’s bearer token and the principal returned by the authorization callback. - BREAKING:
HttpConfiggains anhttpAuthorizefield — an optional callback that validates the presentedAuthorization: Bearertoken and returns an application-defined principal (Nothingrejects with 401). As it now holds a function,HttpConfigno longer derivesShow/Eq. - HTTP transport: accept requests without an
MCP-Protocol-Versionheader (the spec says to assume2025-03-26), exemptinitializefrom the header check (it negotiates its version in the body), and keep rejecting a present but unsupported header with 400. Previously every request without the header was rejected, locking out pre-2025-06-18clients. initializenow advertises only the capabilities that actually have handlers, so strict clients no longer drop the server when e.g.prompts/listanswers “not supported”.- CORS: preflight
OPTIONSrequests are exempt from authorization (browsers send no credentials on preflight) andAuthorizationis included inAccess-Control-Allow-Headers. http-simple-exampleis now built with-threaded, which Warp requires; previously every request crashed with aTimerManagererror.
0.1.0.20 - ???
- Fix protocol version negotiation: echo back any compatible revision the client
proposes (
2024-11-05,2025-03-26,2025-06-18,2025-11-25) instead of always responding with the server’s own version. Fixes clients (e.g. Claude Code) that disconnect when they receive a different version than requested. - Apply the same negotiation to the HTTP transport’s
MCP-Protocol-Versionheader check, which previously rejected anything other than2025-06-18. - Default/fallback advertised version bumped to
2025-11-25.
0.1.0.19 - ???
- Improve handler code generated by TemplateHaskell functions in
MCP.Server.Derive:- Don’t repeat
Map.fromListfor each argument in map lookup - Properly handle argument parse errors (Return
InvalidParamserror instead of crashing mcp server witherror)
- Don’t repeat
0.1.0.18 - 2026-02-09
- Switch default-language to GHC2021 to support broader range of GHC versions (9.6 - 9.12)
0.1.0.17 – 2026-01-28
- Implement protocol version negotiation according to spec
- Remove unused dependencies, fix GHC warnings
- Add tested-with and haskell-ci generated GitHub Actions config
0.1.0.16 – 2026-01-19
- Bump template-haskell dependency upper bound
0.1.0.15 – 2025-08-13
- Update to MCP spec 2025-06-18
0.1.0.14 – 2025-06-26
- Bump version bounds before adding to Stackage
- Remove support for JSON-RPC batching
0.1.0.13 – 2025-06-17
- Better handling of UTF-8 in logs
0.1.0.12 – 2025-06-17
- Fix unicode handling
- Refactor transports to remove unneeded functions
- Add unicode handling tests
0.1.0.11 – 2025-06-17
- Refactor transports and add HTTP streaming support
- Add
MCP.Server.Handlersmodule - Add
MCP.Server.Transport.HttpandMCP.Server.Transport.Stdiomodules
0.1.0.10 – 2025-06-13
- Fix resources handling
0.1.0.9 – 2025-06-13
- Bump versions of dependencies
- Port tests to hspec
0.1.0.8 – 2025-06-12
- Support for nestable data types
0.1.0.7 – 2025-06-09
- Documentation updates
0.1.0.6 – 2025-06-09
- Remove pagination support
0.1.0.5 – 2025-06-09
- Add descriptions to constructors and fields
0.1.0.4 – 2025-06-09
- Clean up build configuration
0.1.0.3 – 2025-06-09
- Refactor example modules
- Fix JSON to Haskell type conversion
0.1.0.0 – 2025-06-05
- First version. Released on an unsuspecting world.