From 58b9f96484583a16950e317e225c3dda3e1c0b88 Mon Sep 17 00:00:00 2001 From: Ayla Croft Date: Sat, 5 Dec 2026 19:10:16 -0500 Subject: [PATCH] Check a catalog when a supervision tree starts The HTTP transport checks only that its catalog exports capabilities/0, because Plug may run its initialisation at the host's compile time. A catalog BeamMCP.Server.new/1 refuses was then answered 500 on every request, while UPGRADING's 1.0.2 row said both transports refuse it at startup. BeamMCP.Catalog.child_spec/1 makes {BeamMCP.Catalog, catalog: M} a child that calls validate/2 once and keeps no process. A catalog it refuses fails the tree's start with {:invalid_catalog, catalog, reason}, before the children after it. The README and the transport's docs show it before the server, and UPGRADING corrects the 1.0.2 row. Signed-off-by: Ayla Croft --- CHANGELOG.md | 9 ++ README.md | 17 ++++ UPGRADING.md | 9 +- docs/public-api.txt | 1 + lib/beam_mcp/catalog.ex | 58 ++++++++++- lib/beam_mcp/transport/http.ex | 7 ++ test/beam_mcp/catalog_at_boot_test.exs | 135 +++++++++++++++++++++++++ 7 files changed, 234 insertions(+), 2 deletions(-) create mode 100644 test/beam_mcp/catalog_at_boot_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index 117f1d4..370fac3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,15 @@ All notable changes to this project are documented here. The format follows Each row says what holds and how far, and cites the test behind it, which the threat-model census holds to the tree. The assurance case and `docs/provenance.md` point to the section. + +- **`{BeamMCP.Catalog, catalog: MyApp.Catalog}` checks a catalog when a supervision tree + starts.** `BeamMCP.Catalog.child_spec/1` calls `BeamMCP.Catalog.validate/2` once and keeps no + process. A catalog it refuses fails the tree's start with `{:invalid_catalog, catalog, + reason}`. The HTTP transport checks only that the catalog exports `capabilities/0` (its + initialisation may run at the host's compile time), so until now an HTTP host learnt of a + refused catalog from a `500` on every request. `UPGRADING.md` corrects its `1.0.2` row, which + said both transports refuse such a catalog at startup. + - **The connectome surface keeps the declared graph it built.** `BeamMCP.Connectome.Surface.read/2` and `call/2` keep the declared graph, its bytes and its hash after a build, and answer later reads from it until what it was built from changes: the diff --git a/README.md b/README.md index baf8bb7..f232bc7 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,23 @@ defmodule MyApp.Router do end ``` +**The catalog is checked at startup only if you ask.** The Plug's initialisation checks that +the catalog module exports `capabilities/0` and does not call it, because under `forward` (and +any `Plug.Builder` pipeline) it runs at your compile time. A catalog `BeamMCP.Server.new/1` +refuses, such as a tool whose `pattern` ECMA-262 does not read or two tools with one name, is +then answered `500` on every request. To refuse it when your application starts instead, put +the check before the server in your supervision tree: + +```elixir +children = [ + {BeamMCP.Catalog, catalog: MyApp.Catalog}, + {Bandit, plug: {BeamMCP.Transport.HTTP, catalog: MyApp.Catalog, ...}, port: 4000} +] +``` + +It keeps no process. A catalog it refuses stops the start, with the reason. Pass it the same +`pattern_dialect:` you pass the transport. + **`authorize` and `allowed_origins` are required and have no defaults.** Omit either and the Plug raises when it is initialised: at start, not on the first request. diff --git a/UPGRADING.md b/UPGRADING.md index 90d0130..a41b557 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -30,11 +30,18 @@ under `1.1.0`. | a client that sends more than 16,384 values (each value one, each key one more) to a method other than `tools/call`, or to a tool the catalog does not list; or a `tools/call` carrying more values than its tool's `inputSchema` admits | `-32600` before the body is decoded, with the request's id, where it got the method's answer, `-32601`, or the tool's schema refusal | nothing for an honest client of a host whose tools declare what they take; a host whose tool takes more than its schema says widens the schema (`maxItems`, `maxProperties`) | | a host that runs a server module above the core serving tools its `:catalog` option does not list | a call to such a tool may carry 16,384 values | list the tool in the catalog the transport is given | | an HTTP client that sends a POST with no `Content-Type` | `415` / `-32600` before the body is read, where `1.0.2` served it. The TypeScript and Python SDKs, the Inspector and the conformance suite all send `application/json` | send `Content-Type: application/json`; or, for a client you cannot change, pass `allow_missing_content_type: true` to `BeamMCP.Transport.HTTP` | -| a host whose tool schema has a `pattern` that ECMA-262 does not read (an atomic group, a possessive quantifier, `\Q`, inline options such as `(?i)`, `\A`, `\z`, `\h`, `\x{...}`, a POSIX class, a verb, a recursion, `\X`) | `BeamMCP.Server.new/1` refuses the catalog, naming the construct and the character it stands at: the stdio transport does not start, and the HTTP transport answers every request `500` / `-32603` and logs the reason. A few patterns ECMA-262 reads are refused the same way, where the runtime would read them otherwise (a back-reference into a repeated group or a lookbehind, an unbounded lookbehind, a count above 65,535) | write it as ECMA-262 reads it, which is how a client's validator reads it; or pass `pattern_dialect: :pcre` to `BeamMCP.Server.new/1` (a transport hands it on) to read every pattern as `1.0.2` did | +| a host whose tool schema has a `pattern` that ECMA-262 does not read (an atomic group, a possessive quantifier, `\Q`, inline options such as `(?i)`, `\A`, `\z`, `\h`, `\x{...}`, a POSIX class, a verb, a recursion, `\X`) | `BeamMCP.Server.new/1` refuses the catalog, naming the construct and the character it stands at: the stdio transport does not start, and the HTTP transport answers every request `500` / `-32603` and logs the reason (a host that starts `{BeamMCP.Catalog, catalog: ...}` before it does not come up). A few patterns ECMA-262 reads are refused the same way, where the runtime would read them otherwise (a back-reference into a repeated group or a lookbehind, an unbounded lookbehind, a count above 65,535) | write it as ECMA-262 reads it, which is how a client's validator reads it; or pass `pattern_dialect: :pcre` to `BeamMCP.Server.new/1` (a transport hands it on) to read every pattern as `1.0.2` did | | a client whose string holds the no-break space, U+2028, U+FEFF or another space ECMA-262 counts, against a pattern such as `^\S+$`; or a carriage return, U+2028 or U+2029 against a `.` | refused, as the client's own validator refuses it, where `1.0.2` admitted it | nothing for an honest client; a host that needs the old reading passes `pattern_dialect: :pcre` | | a host that calls `BeamMCP.Schema.validate/2` or `BeamMCP.Catalog.validate/1` itself | both read a pattern as ECMA-262 reads it | call `validate/3` or `validate/2` with `pattern_dialect: :pcre` for the old reading | | a stdio host with a filter or audit proxy in front that reads lines | nothing by default; `legacy_framing: false` is new | pass `legacy_framing: false` to `BeamMCP.Transport.Stdio.run/1`, and the filter sees every request served. The default turns to `false` at 2.0; a host whose client sends `Content-Length` frames passes `true` before then | +A correction to the `1.0.2` table below: its row for a catalog with a tool name that is not an +atom, or two tools with one name, says `BeamMCP.Server.new/1` and both transports refuse it at +startup. The stdio transport does; the HTTP transport did not, and does not: it answers every +request `500` / `-32603`. From `1.1.0` an HTTP host gets the refusal at startup by putting +`{BeamMCP.Catalog, catalog: MyApp.Catalog}` before the server in its supervision tree +(`BeamMCP.Catalog.child_spec/1`). + ## From `1.0.1` to `1.0.2`: a patch whose fixes change some answers No line of `docs/public-api.txt` changes, and the pin stays `~> 1.0`. `1.0.2` is a security diff --git a/docs/public-api.txt b/docs/public-api.txt index faab207..0e3d3ab 100644 --- a/docs/public-api.txt +++ b/docs/public-api.txt @@ -12,6 +12,7 @@ BeamMCP.Catalog callback capabilities/0 BeamMCP.Catalog callback get_prompt/2 BeamMCP.Catalog callback read_resource/1 +BeamMCP.Catalog function child_spec/1 since=Unreleased BeamMCP.Catalog function fetch/2 BeamMCP.Catalog function fetch_prompt/2 BeamMCP.Catalog function prompts/1 diff --git a/lib/beam_mcp/catalog.ex b/lib/beam_mcp/catalog.ex index 742b8c0..61970f0 100644 --- a/lib/beam_mcp/catalog.ex +++ b/lib/beam_mcp/catalog.ex @@ -610,7 +610,8 @@ defmodule BeamMCP.Catalog do default initialisation is the host's **compile** time and a catalog reading config or ETS there would fail for a correct host. That transport checks the export and leaves the shape to `BeamMCP.Server.new/1`. (The transport's `init` callback is not linked here: it is a hidden - callback, and a doc reference to it is a broken link rather than a useful one.) + callback, and a doc reference to it is a broken link rather than a useful one.) An HTTP host + that wants the check at startup puts `child_spec/1` in its supervision tree. """ @spec validate(module()) :: :ok | {:error, String.t()} def validate(catalog), do: validate(catalog, []) @@ -636,6 +637,61 @@ defmodule BeamMCP.Catalog do def validate(other, _opts), do: {:error, "expected a module, got: #{inspect(other)}"} + @doc """ + A child for the host's supervision tree that checks a catalog when the tree starts. + + children = [ + {BeamMCP.Catalog, catalog: MyApp.Catalog}, + {Bandit, plug: {BeamMCP.Transport.HTTP, catalog: MyApp.Catalog, ...}, port: 4000} + ] + + It calls `validate/2` once, as the supervisor starts its children, and keeps no process. A + catalog `validate/2` accepts starts nothing (`:ignore`). One it refuses fails the + supervisor's start, so the host does not come up, with + `{:invalid_catalog, catalog, reason}` in the start error and `reason` the sentence + `validate/2` gives. + + `BeamMCP.Server.new/1`, and with it the stdio transport, refuses such a catalog when it + starts. The HTTP transport checks only that the module exports `capabilities/0`, because + Plug may initialise it at the host's compile time (see `validate/1`). Its requests then + answer `500` / `-32603`. This child is how an HTTP host refuses the catalog at startup + instead. Place it before the transport, and after any child whose state `capabilities/0` + reads. + + Options: `:catalog`, the module (required), and `:pattern_dialect`, as `validate/2` takes it. + Pass the dialect the transport is given. Any other option raises `ArgumentError`, as a + missing catalog or an unknown dialect does, when the child spec is built. + """ + @spec child_spec(keyword()) :: Supervisor.child_spec() + def child_spec(opts) when is_list(opts) do + {catalog, rest} = Keyword.pop(opts, :catalog) + + case Keyword.keys(rest) -- [:pattern_dialect] do + [] -> :ok + unknown -> raise ArgumentError, "unknown option(s) for BeamMCP.Catalog: #{inspect(unknown)}" + end + + unless is_atom(catalog) and not is_nil(catalog) and catalog not in [true, false] do + raise ArgumentError, "BeamMCP.Catalog requires :catalog, a module; got: #{inspect(catalog)}" + end + + _ = BeamMCP.Schema.dialect!(rest) + + %{ + id: {__MODULE__, catalog}, + start: {__MODULE__, :check_at_start, [catalog, rest]}, + restart: :temporary + } + end + + @doc false + def check_at_start(catalog, opts) do + case validate(catalog, opts) do + :ok -> :ignore + {:error, reason} -> {:error, {:invalid_catalog, catalog, reason}} + end + end + defp validate_shape(catalog, dialect) do case catalog.capabilities() do %{} = caps -> diff --git a/lib/beam_mcp/transport/http.ex b/lib/beam_mcp/transport/http.ex index 67b4797..807fa1e 100644 --- a/lib/beam_mcp/transport/http.ex +++ b/lib/beam_mcp/transport/http.ex @@ -204,6 +204,13 @@ if Code.ensure_loaded?(Plug) do The specification says a locally-running server **SHOULD** bind to localhost rather than all interfaces. That is the host's `Bandit` option above; this module cannot enforce it. + + This module's initialisation checks that the catalog exports + `c:BeamMCP.Catalog.capabilities/0` and does not call it: Plug may run it at the host's + compile time. A catalog `BeamMCP.Server.new/1` refuses is answered `500` / `-32603` on + every request. To refuse it at startup, put + `{BeamMCP.Catalog, catalog: MyApp.Catalog}` before this server in the supervision tree + (`BeamMCP.Catalog.child_spec/1`). """ @behaviour Plug diff --git a/test/beam_mcp/catalog_at_boot_test.exs b/test/beam_mcp/catalog_at_boot_test.exs new file mode 100644 index 0000000..1170131 --- /dev/null +++ b/test/beam_mcp/catalog_at_boot_test.exs @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: 2026 Sudo Apt Holdings LLC +# SPDX-License-Identifier: Apache-2.0 + +defmodule BeamMCP.CatalogAtBootTest do + # `{BeamMCP.Catalog, catalog: M}` in a supervision tree: the startup check an HTTP host + # otherwise lacks (its transport checks only the export, and a catalog the server refuses is + # answered 500 on every request). + use ExUnit.Case, async: true + + alias BeamMCP.Transport.HTTP + + def tool!(name, pattern) do + %BeamMCP.ToolSpec{ + name: name, + command_class: :observe, + mode: :read_only, + description: "Looks up.", + input_schema: %{ + "type" => "object", + "properties" => %{"id" => %{"type" => "string", "pattern" => pattern}} + } + } + end + + defmodule Good do + @behaviour BeamMCP.Catalog + def capabilities, + do: %{ + tools: [BeamMCP.CatalogAtBootTest.tool!(:lookup, "^[a-z]+$")], + resources: [], + prompts: [] + } + end + + # A pattern the default reading refuses (an atomic group) and :pcre reads. + defmodule Atomic do + @behaviour BeamMCP.Catalog + def capabilities, + do: %{ + tools: [BeamMCP.CatalogAtBootTest.tool!(:lookup, "^(?>[a-z]+)$")], + resources: [], + prompts: [] + } + end + + # Two tools with one name: the 1.0.2 row of UPGRADING.md. + defmodule Twice do + @behaviour BeamMCP.Catalog + def capabilities do + t = BeamMCP.CatalogAtBootTest.tool!(:lookup, "^[a-z]+$") + %{tools: [t, t], resources: [], prompts: []} + end + end + + # A child after the check, to show whether the tree got past it. + defmodule After do + def child_spec(test), do: %{id: __MODULE__, start: {__MODULE__, :start_link, [test]}} + + def start_link(test) do + send(test, :after_started) + :ignore + end + end + + defp start_tree(children) do + Process.flag(:trap_exit, true) + Supervisor.start_link(children, strategy: :one_for_one) + end + + test "a catalog validate/2 accepts starts nothing, and the tree goes on" do + assert {:ok, sup} = start_tree([{BeamMCP.Catalog, catalog: Good}, {After, self()}]) + assert_received :after_started + + # A temporary child that answers :ignore is not kept: the tree holds nothing of the check. + assert [{After, :undefined, :worker, _}] = Supervisor.which_children(sup) + + Supervisor.stop(sup) + end + + test "a catalog validate/2 refuses fails the tree's start, with the reason, before the next child" do + for {catalog, said} <- [ + {Atomic, "an atomic group"}, + {Twice, "lookup"} + ] do + assert {:error, {:shutdown, {:failed_to_start_child, {BeamMCP.Catalog, ^catalog}, error}}} = + start_tree([{BeamMCP.Catalog, catalog: catalog}, {After, self()}]) + + assert {:invalid_catalog, ^catalog, reason} = error + assert {:error, ^reason} = BeamMCP.Catalog.validate(catalog) + assert reason =~ said + refute_received :after_started + end + end + + test "the check reads patterns in the dialect it is given" do + assert {:ok, sup} = + start_tree([{BeamMCP.Catalog, catalog: Atomic, pattern_dialect: :pcre}]) + + Supervisor.stop(sup) + end + + test "the child spec refuses what it cannot check, when it is built" do + for opts <- [ + [], + [catalog: nil], + [catalog: true], + [catalog: "Good"], + [catalog: Good, pattern_dialect: :perl], + [catalog: Good, dispatch: &Function.identity/1] + ] do + assert_raise ArgumentError, fn -> BeamMCP.Catalog.child_spec(opts) end + end + + assert %{id: {BeamMCP.Catalog, Good}, restart: :temporary} = + BeamMCP.Catalog.child_spec(catalog: Good) + end + + test "an HTTP host with the check does not come up on a catalog the transport would answer 500" do + # The transport alone starts on this catalog: its init checks only the export. + http = [ + catalog: Atomic, + dispatch: fn _, args, _ -> {:ok, args} end, + authorize: fn _ -> :ok end, + allowed_origins: :any + ] + + assert %{} = HTTP.init(http) + + assert {:error, {:shutdown, {:failed_to_start_child, {BeamMCP.Catalog, Atomic}, _}}} = + start_tree([ + {BeamMCP.Catalog, catalog: Atomic}, + {Bandit, plug: {HTTP, http}, port: 0, ip: {127, 0, 0, 1}} + ]) + end +end