ExMCP.Server.Tools (ex_mcp v0.10.0)

View Source

DSL for defining MCP tools in server handlers.

This module provides a declarative way to define tools with automatic schema generation and validation. It supports both simple and advanced APIs.

Simple API

For common cases, use the simple API with automatic schema generation:

defmodule MyServer do
  use ExMCP.Server.Handler
  use ExMCP.Server.Tools

  tool "echo", "Echo back the input" do
    param :message, :string, required: true

    handle fn %{message: message}, _state ->
      {:ok, text: message}
    end
  end
end

Advanced API

For full control over schemas and metadata:

tool "calculate" do
  description "Perform mathematical calculations"

  input_schema %{
    type: "object",
    properties: %{
      expression: %{type: "string", pattern: "^[0-9+\-*/().\s]+$"}
    }
  }

  annotations %{
    readOnlyHint: true
  }

  handle fn %{expression: expr}, state ->
    result = evaluate_expression(expr)
    {:ok, %{
      content: [{type: "text", text: "Result: #{result}"}],
      structuredContent: %{result: result, expression: expr}
    }, state}
  end
end

Summary

Functions

Set annotations for a tool.

Set the description for a tool.

Define the handler function for a tool.

Set the input schema for a tool.

Set the output schema for a tool.

Define a parameter for a tool.

Set the title for a tool (2025-06-18 feature).

Define a tool using the DSL.

Functions

annotations(anns)

(macro)

Set annotations for a tool.

description(desc)

(macro)

Set the description for a tool.

handle(func)

(macro)

Define the handler function for a tool.

The handler receives the arguments and state, and should return {:ok, response} or {:ok, response, new_state}.

input_schema(schema)

(macro)

Set the input schema for a tool.

output_schema(schema)

(macro)

Set the output schema for a tool.

param(name, type, opts \\ [])

(macro)

Define a parameter for a tool.

This macro is used within a tool definition to specify parameters.

Examples

param :name, :string, required: true
param :age, :integer, default: 0
param :tags, {:array, :string}

title(title_text)

(macro)

Set the title for a tool (2025-06-18 feature).

tool(name, description \\ nil, list)

(macro)

Define a tool using the DSL.

Examples

tool "echo", "Echo back the input" do
  param :message, :string, required: true
  handle fn %{message: message}, _state ->
    {:ok, text: message}
  end
end