NexusMCP.Server.Resource (NexusMCP v0.3.0)

Copy Markdown View Source

Provides defresource and defresource_template macros for declaring MCP resources alongside their read handlers.

Resources are application-controlled context surfaced to MCP clients via resources/list, resources/templates/list, and resources/read (MCP spec 2025-11-25).

Static resources

defresource "config://app",
  name: "app_config",
  description: "Application configuration",
  mime_type: "application/json" do
  {:ok, Jason.encode!(MyApp.config())}
end

Templated resources

defresource_template "file:///{path}",
  name: "project_files",
  description: "Files in the project directory",
  mime_type: "text/plain" do
  {:ok, File.read!(params["path"])}
end

URI template syntax supports two RFC 6570 operators:

  • {var} — matches a single path segment (no /)
  • {+var} — matches one or more segments (reserved expansion)

Inside the do block, params (URI captures) and session are bound.

Return shape

The handler returns one of:

  • {:ok, binary} — wrapped as text if mime_type is textual (text/* or application/json), otherwise base64-encoded as blob
  • {:ok, %{text: string}} or {:ok, %{blob: base64}} — passed through
  • {:error, reason} — surfaces as JSON-RPC -32002 resource-not-found

Summary

Functions

Compile an RFC 6570 URI template (subset: {var} and {+var}) to a regex source string plus the list of variable names.

Defines a static resource and its read handler.

Defines a templated resource and its read handler.

Try to match a URI against a list of compiled templates.

Strips the internal __regex__ / __vars__ fields from a template definition before serializing it over the wire.

Functions

compile_template(uri_template)

Compile an RFC 6570 URI template (subset: {var} and {+var}) to a regex source string plus the list of variable names.

Examples

iex> NexusMCP.Server.Resource.compile_template("file:///{path}")
{"^file:///(?<path>[^/]+)$", ["path"]}

iex> NexusMCP.Server.Resource.compile_template("file:///{+path}")
{"^file:///(?<path>.+)$", ["path"]}

defresource(uri, opts, do_block \\ [])

(macro)

Defines a static resource and its read handler.

defresource_template(uri_template, opts, do_block \\ [])

(macro)

Defines a templated resource and its read handler.

match_template(uri, templates)

Try to match a URI against a list of compiled templates.

Returns {:ok, template, params} on the first match, or :error.

public_template(template)

Strips the internal __regex__ / __vars__ fields from a template definition before serializing it over the wire.