ExAgent.MCP.Protocol (ExAgent v3.0.0)

View Source

Pure JSON-RPC 2.0 encoding and decoding for the Model Context Protocol. Use ExAgent.MCP.Client to discover and call tools.

Stability — Stable.

Summary

Functions

Decode one complete JSON-RPC line.

Encode a JSON-RPC notification (no id, no reply expected).

Encode a JSON-RPC request (with an id) as a newline-terminated binary.

Extract the text of an MCP tools/call result.

Types

decoded()

@type decoded() ::
  {:response, id :: term(), result :: map()}
  | {:error_response, id :: term(),
     error :: map() | :invalid_jsonrpc | :duplicate_json_key}
  | {:ping, integer() | String.t()}
  | {:unsupported_request, integer() | String.t()}
  | {:invalid_request, integer() | String.t() | nil}
  | {:notification, method :: String.t(), params :: map()}
  | :ignore

Functions

decode(line)

@spec decode(binary()) :: decoded()

Decode one complete JSON-RPC line.

  • a response with a result → {:response, id, result}
  • a response with an error object with integer code and string message → {:error_response, id, error}
  • a response with a malformed error or both members → {:error_response, id, :invalid_jsonrpc}
  • duplicate JSON keys in a response with a single valid ID → {:error_response, id, :duplicate_json_key}
  • a server ping request → {:ping, id}
  • another well-formed server request → {:unsupported_request, id}
  • a server request with non-object params or an invalid ID → {:invalid_request, id}. The ID is nil when it is unusable in MCP.
  • a JSON-RPC 2.0 notification with a string method and no id → {:notification, method, params}, with an object for params (default %{})
  • a message with method and either response member → :ignore
  • anything unparseable / unrelated → :ignore

encode_notification(method, params)

@spec encode_notification(String.t(), map()) :: iodata()

Encode a JSON-RPC notification (no id, no reply expected).

encode_request(id, method, params)

@spec encode_request(term(), String.t(), map()) :: iodata()

Encode a JSON-RPC request (with an id) as a newline-terminated binary.

result_to_text(result)

@spec result_to_text(map()) ::
  {:ok, String.t()} | {:tool_error, String.t()} | {:error, term()}

Extract the text of an MCP tools/call result.

Text blocks are concatenated. In this text projection, other blocks become explicit notices instead of raw payloads: images and audio name their MIME type and size, embedded text resources contribute their text, binary resources and resource links are named by URI. An empty content list with structuredContent returns that object as JSON. If it is the only content and is not an object, the result is {:error, :invalid_tool_result}. The optional boolean isError selects {:tool_error, text} or {:ok, text}. A missing or non-list content or a non-boolean isError returns {:error, :invalid_tool_result}.