Mcp42.Server behaviour (mcp42 v0.1.0)

Copy Markdown

Behaviour every mcp42 host server implements.

defmodule MyApp.MCP do
  use Mcp42.Server, name: "myapp", version: "1.0.0"

  @impl true
  def tools, do: [...]

  @impl true
  def handle_tool("greet", %{"name" => name}, _ctx), do: {:ok, "hi #{name}"}
end

Summary

Types

Per-request context handed to handle_tool (transport-injected, e.g. session id).

A tool declaration (JSON shape from the MCP tools/list result): %{name: String.t(), description: String.t(), inputSchema: map()}

Tool results

Callbacks

Optional: overrides the serverInfo block in initialize responses. Defaults to the :name and :version given to use Mcp42.Server.

Types

ctx()

@type ctx() :: map()

Per-request context handed to handle_tool (transport-injected, e.g. session id).

tool()

@type tool() :: %{name: String.t(), description: String.t(), inputSchema: map()}

A tool declaration (JSON shape from the MCP tools/list result): %{name: String.t(), description: String.t(), inputSchema: map()}

tool_result()

@type tool_result() :: {:ok, String.t()} | {:ok, [map()]} | {:error, String.t()}

Tool results:

  • {:ok, text} — single text content, success
  • {:ok, content :: [map()]} — raw content items (already MCP-shaped)
  • {:error, message} — tool-level error (becomes isError: true result)

Callbacks

handle_tool(name, args, ctx)

@callback handle_tool(name :: String.t(), args :: map(), ctx :: ctx()) :: tool_result()

server_info()

(optional)
@callback server_info() :: %{required(String.t()) => String.t()}

Optional: overrides the serverInfo block in initialize responses. Defaults to the :name and :version given to use Mcp42.Server.

tools()

@callback tools() :: [tool()]