MCP.Server.ToolContext (MCP Elixir SDK v1.0.1)

Copy Markdown View Source

Context passed to handle_call_tool/4 handlers during tool execution.

Provides an API for tool handlers to interact with the MCP server while the tool is running — sending notifications (logging, progress) and making server-to-client requests (sampling, elicitation).

Example

def handle_call_tool("my_tool", args, ctx, state) do
  ToolContext.log(ctx, "info", "Starting tool execution")
  ToolContext.send_progress(ctx, 0, 100)

  # Request LLM sampling from the client
  {:ok, result} = ToolContext.request_sampling(ctx, %{
    "messages" => [%{"role" => "user", "content" => %{"type" => "text", "text" => "Hello"}}],
    "maxTokens" => 100
  })

  ToolContext.send_progress(ctx, 100, 100)
  {:ok, [%{"type" => "text", "text" => "Done"}], state}
end

Summary

Functions

Sends a log notification to the client.

Sends a server-to-client JSON-RPC request and waits for the response.

Sends an elicitation/create request to the client.

Sends a sampling/createMessage request to the client.

Sends a JSON-RPC notification to the client during tool execution.

Sends a progress notification to the client.

Types

t()

@type t() :: %MCP.Server.ToolContext{
  meta: map() | nil,
  request_id: term(),
  server_pid: pid()
}

Functions

log(ctx, level, data, logger \\ nil)

@spec log(t(), String.t(), term(), String.t() | nil) :: :ok

Sends a log notification to the client.

Convenience wrapper around send_notification/3 for logging.

request(ctx, method, params, timeout \\ 60000)

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

Sends a server-to-client JSON-RPC request and waits for the response.

Used for sampling, elicitation, and other bidirectional operations during tool execution. The request is routed to the client on the same SSE stream, and the client responds via a new POST.

Returns {:ok, result} or {:error, reason}.

request_elicitation(ctx, params, timeout \\ 60000)

@spec request_elicitation(t(), map(), timeout()) :: {:ok, map()} | {:error, term()}

Sends an elicitation/create request to the client.

Returns {:ok, result} or {:error, reason}.

request_sampling(ctx, params, timeout \\ 60000)

@spec request_sampling(t(), map(), timeout()) :: {:ok, map()} | {:error, term()}

Sends a sampling/createMessage request to the client.

Returns {:ok, result} or {:error, reason}.

send_notification(ctx, method, params)

@spec send_notification(t(), String.t(), map()) :: :ok

Sends a JSON-RPC notification to the client during tool execution.

The notification is routed through the MCP server and delivered to the client on the same SSE stream as the tool call response.

send_progress(ctx, progress, total \\ nil)

@spec send_progress(t(), number(), number() | nil) :: :ok

Sends a progress notification to the client.

Uses the progressToken from _meta if available.