Ragex.MCP.Formatter (Ragex v0.17.1)

View Source

Centralized response formatting for MCP tool results.

Sits between Tools.call_tool/2 and the JSON serializer in Server.handle_tools_call/2. Every tool result passes through format/3 which applies compaction, token budgeting, and smart suggestions based on the formatting options.

Modes

  • :compact (default) -- truncates lists, strips verbose fields (docs, specs, long strings), and appends next-step suggestions.
  • :verbose -- passes the result through unchanged (current behavior).

Token Budget

When max_tokens is specified, the formatter estimates the JSON size of the result (~4 chars per token) and truncates to fit.

Smart Suggestions

In compact mode, the formatter appends _suggestions with actionable next-step hints based on the result shape and tool name.

Usage

The formatter is invoked automatically by Server.handle_tools_call/2. Tool handlers do not need to call it directly.

Options are extracted from tool arguments:

  • "verbose" (boolean, default false) -- if true, skip compaction
  • "max_tokens" (integer, optional) -- token budget for the response

Summary

Functions

Estimate the number of tokens a value will consume when JSON-encoded.

Extract formatting options from MCP tool arguments.

Format a tool result based on options.

Generate next-step suggestions based on the result shape and tool name.

Functions

estimate_tokens(value)

@spec estimate_tokens(term()) :: non_neg_integer()

Estimate the number of tokens a value will consume when JSON-encoded.

Uses ~4 characters per token as a rough heuristic.

extract_opts(arguments)

@spec extract_opts(map()) :: keyword()

Extract formatting options from MCP tool arguments.

Pulls verbose and max_tokens from the arguments map, returning a keyword list suitable for format/3.

format(result, tool_name, opts \\ [])

@spec format(term(), String.t(), keyword()) :: term()

Format a tool result based on options.

Parameters

  • result -- the raw result from Tools.call_tool/2 (the value inside {:ok, result})
  • tool_name -- string name of the tool that produced the result
  • opts -- formatting options:
    • :verbose -- boolean (default false)
    • :max_tokens -- integer token budget (optional)

Returns

The formatted result (same shape as input, but potentially compacted).

suggest_next(result, tool_name)

@spec suggest_next(map(), String.t()) :: [String.t()]

Generate next-step suggestions based on the result shape and tool name.

Returns a list of actionable hint strings.