AshAi.McpResource.Contents behaviour (ash_ai v1.5.6)

Copy Markdown View Source

Builds the contents of an mcp_resource's resources/read result from what its action returned.

Without the contents option, an action that returns :string is sent as text, and one that returns :binary as a base64 blob, each with the resource's mime_type. Set contents when that isn't enough: a MIME type that differs per read, such as a photo's, or several items for one URI. It takes a module implementing this behaviour (or {module, opts}), or a function taking the action's result and an AshAi.McpResource.Contents.Context:

mcp_resources do
  mcp_resource :photo, "photos://{id}", MyApp.Photos.Photo, :get do
    title "Photo"
    contents &MyAppWeb.McpViews.photo/2
  end
end

def photo(%Photo{} = photo, _context) do
  AshAi.McpResource.Contents.blob(MyApp.Storage.read!(photo.key),
    mime_type: photo.mime_type
  )
end

With contents, the action may return any type. Return one item built with text/2 or blob/2, or a list of them. An item's uri defaults to the URI that was read, and its mime_type to the resource's mime_type, if it has one.

The callback isn't called when the action returns nil or fails with Ash.Error.Query.NotFound: both are sent as resource not found. If it raises, or returns anything else, the error is logged and the client gets a read error.

Summary

Callbacks

Returns the contents for one read: an item or a list of items.

Functions

A binary item. Pass the raw bytes; they are base64-encoded for you.

A text item. text must be valid UTF-8.

Types

Callbacks

contents(result, opts, context)

@callback contents(
  result :: term(),
  opts :: Keyword.t(),
  context :: AshAi.McpResource.Contents.Context.t()
) ::
  item() | [item()]

Returns the contents for one read: an item or a list of items.

Functions

blob(data, opts \\ [])

A binary item. Pass the raw bytes; they are base64-encoded for you.

Takes the same options as text/2.

text(text, opts \\ [])

A text item. text must be valid UTF-8.

Options

  • :mime_type - defaults to the resource's mime_type
  • :uri - defaults to the URI that was read
  • :meta - a map sent as the item's _meta