package mcp-kit-ppx

All checked builds pass
  1. Overview
  2. Docs

doc/README.html

mcp-kit

mcp-kit is an OCaml library for building Model Context Protocol (MCP) servers. It gives you a typed server core, schema-checked tools, and adapters for stdio, Eio flows, and Streamable HTTP with Cohttp-Eio.

The core supports the current MCP 2026-07-28 request model and the 2025-11-25 initialization lifecycle used by established clients.

Run the example

From a checkout, with OCaml 5.1 or later and opam installed:

opam install . --deps-only --with-test
opam exec -- dune exec examples/typed_tool.exe

The example exposes an echo tool over line-delimited JSON-RPC on standard input and output. Send it an initialization request, then call the tool:

opam exec -- dune exec examples/typed_tool.exe <<'EOF_REQUESTS'
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"manual","version":"0"}}}
{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"message":"hello"}}}
EOF_REQUESTS

The complete source is examples/typed_tool.ml.

Define a typed tool

Describe the input and optional structured output with JSON Schema, then add the tool to a server:

let echo =
  let input_schema =
    Mcp_kit.Schema.object_
      ~properties:[("message", Mcp_kit.Schema.string ())]
      ~required:["message"]
      ()
  in
  Mcp_kit.Tool.make
    ~description:"Echo a message."
    ~input_schema
    ~output_schema:
      (Mcp_kit.Schema.object_
         ~properties:[("echoed", Mcp_kit.Schema.string ())]
         ~required:["echoed"]
         ())
    "echo"
    (fun args ->
      Result.map
        (fun message ->
          {
            Mcp_kit.Tool.content = [Mcp_kit.Tool.Text message];
            is_error = false;
            structured_content = Some (`Assoc [("echoed", `String message)]);
          })
        (Mcp_kit.Tool.Arg.string "message" args))

let server =
  Mcp_kit.Server.create ~name:"example" ~version:"1.0" ()
  |> fun server ->
  match Mcp_kit.Server.add_tool server echo with
  | Ok server -> server
  | Error (Duplicate_tool name) -> failwith ("duplicate tool: " ^ name)
  | Error _ -> failwith "unexpected declaration error"

A tool's input is validated before its handler runs. If you declare an output schema, each successful result must supply matching structuredContent. Invalid schemas are rejected when the tool is declared.

Choose a transport

Package

Use it when

Entry point

mcp-kit

You want the typed server model and implement the surrounding transport yourself.

Mcp_kit.Server

mcp-kit-stdio

Your client starts the server as a subprocess.

Mcp_kit_stdio.run_channels

mcp-kit-eio

You serve JSON-RPC through an Eio flow.

Mcp_kit_eio.run_flow

mcp-kit-cohttp-eio

You serve MCP over Streamable HTTP with Cohttp-Eio.

Mcp_kit_cohttp_eio.handler

The adapters create an MCP session for each connection or HTTP request as required by the protocol. A server value can serve concurrent clients; keep application state safe for the concurrency model of the adapter you choose.

What you can expose

Register the capabilities your server needs:

  • Tools with typed argument accessors, JSON Schema validation, text, image, audio, and embedded-resource content.
  • Resources and static resource templates, including resources/list and resources/read.
  • Prompts with arguments and application-supplied completion.
  • Interactive tools for MCP multi-round-trip requests.
  • Progress for work associated with a client progress token.
  • HTTP subscriptions for opt-in resource update streams when using the Cohttp-Eio adapter.

See the public interfaces in src/ and runnable examples in examples/ for the complete API.

PPX tool declarations

Install mcp-kit-ppx, ppx_deriving_jsonschema, and ppx_deriving_yojson. Enable the three PPXs and link both deriver runtimes:

(libraries mcp-kit ppx_deriving_jsonschema.runtime ppx_deriving_yojson.runtime)
(preprocess (pps ppx_deriving_jsonschema ppx_deriving_yojson mcp-kit-ppx))

Declare input and output types with [@@deriving yojson, jsonschema], then give the handler an explicit OCaml function type. The PPX derives the MCP input schema, decodes arguments, derives the output schema, and serializes a successful value. mcp.description defaults to the binding name.

open Ppx_deriving_jsonschema_runtime.Primitives.Yojson

type echo_input = { message : string } [@@deriving yojson, jsonschema]
type echo_output = { echoed : string } [@@deriving yojson, jsonschema]

let%mcp.tool (echo [@mcp.title "Echo"] [@mcp.description "Return the supplied message."]) :
    echo_input -> (echo_output, string) result =
 fun input -> Ok { echoed = input.message }

With one named input type, the MCP argument object is decoded directly as that type. With several arguments, simple unlabeled lambda parameter names become required MCP fields. Scalar values, lists, arrays, options, and OCaml references are supported; a reference is serialized as its current contained value. The return value must be ('output, string) result, where 'output is a named type deriving both codecs.

For example, a multi-argument handler can expose a numeric calculation without writing JSON parsing or Mcp_kit.Tool.result records:

type fma_output = float * bool [@@deriving yojson, jsonschema]

let%mcp.tool (fma_check [@mcp.title "FMA check"]) :
    int -> int -> int -> int -> (fma_output, string) result =
 fun a b c expected ->
  let value = (float_of_int a *. float_of_int b) +. float_of_int c in
  Ok (value, value = float_of_int expected)

The typed declaration is available for classic tools. Progress and interactive tools continue to use their context-first JSON handlers and explicit schema metadata.

The established mcp.input_type and mcp.output_type attributes remain available for existing JSON handlers. Use mcp.schema and mcp.output_schema for hand-written schemas. Explicit schema attributes cannot be combined with a typed handler annotation.

Use let%mcp.tool.progress when the handler receives a progress reporter before its arguments. Use let%mcp.tool.interactive for a context-first handler; it requires [@mcp.input_response_keys expression] and also accepts mcp.verify_request_state, mcp.input_response_kinds, mcp.required_client_capabilities, mcp.form_response_schemas, mcp.form_state_codec, mcp.url_state_codec, and mcp.verify_url_completion. These option payloads are OCaml expressions passed to the typed core.

The PPX playground guide shows every declaration form and can expand a snippet through the same PPX used by Dune.

MCP versions and HTTP serving

Modern MCP clients may use server/discover and send the protocol version and client capabilities in request metadata. Clients using the earlier lifecycle can send initialize followed by notifications/initialized. mcp-kit supports both paths where their features overlap.

The Cohttp-Eio adapter validates the routing headers required by Streamable HTTP and bounds request bodies. Deploy a public server behind infrastructure that provides TLS termination, authentication, rate limiting, and DDoS protection. Those deployment controls belong at the gateway or reverse proxy, not in the MCP server library.

JSON Schema

Schemas use JSON Schema Draft 2020-12 and are compiled locally. The pinned validator supports local references and the standard schema vocabulary used by the project. It never retrieves schemas over the network: declarations that require an external reference fail during setup.

Input schemas must describe JSON objects. Output schemas may describe an object or use a Boolean schema. The schema compiler limits nesting and node counts so a malformed declaration cannot consume unbounded resources.

Protocol conformance

The repository runs the official MCP compliance scenarios against the server and records the result in docs/conformance.md. The latest required run has 37 passes, 0 failures, and 0 inconclusive scenarios; the pending manifest is empty.

That evidence covers the server capabilities advertised by this library. It does not make mcp-kit an MCP client implementation or replace deployment security controls.

Development

Run the required checks before contributing:

opam exec -- dune build @install
opam exec -- dune runtest
opam exec -- dune build @doc
opam exec -- dune build @fmt

CONTRIBUTING.md lists the full contributor checks. The project's implementation history and planned work live in ROADMAP.md.