Skip to content

2026 11 25 delivery inputs

kubed-io[bot] edited this page Nov 25, 2026 · 1 revision

The delivery inputs Implementation Plan

History. Written 2026-11-25 for #21 (quick-mcp#41), step 5 of material delivery, after #37. What it builds is in the living spec: delivery (DLV-1 to DLV-8, and DLV-16, new). Those rows were rewritten this round and stay (proposed) until the task that builds each one drops the tag. It also edits gateway GW-1, GW-2 and GW-3, app APP-2, APP-4 and APP-12, and facade FAC-1 and FAC-2, each in the task that changes the code under it.

For agentic workers: REQUIRED SUB-SKILL: Use skill://superpowers/subagent-driven-development/SKILL.md (recommended) or skill://superpowers/executing-plans/SKILL.md to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: A client says, by header or query parameter, whether it can read resources (X-MCP-Resources) and which kinds resources/list shows (X-MCP-Listed). A server can name its own spelling of every such header (header_prefix="Kb"). An invalid value of any input, the gateway prefix included, falls through to the next source with one warning that names it. A client that cannot read resources gets list_resources and read_resource.

Architecture:

  • One new public module, kubed/mcp/delivery.py, owns the inputs:
    • a table of them, and the Delivery config protocol;
    • a resolver that is an ordered list of levels per input;
    • a middleware that resolves once per request into a ContextVar.
  • gateway.prefix() reads that resolution. The warn-once in request.py is rewritten under it.
  • The plugin layer reads the resolution in two places:
    • its skills and files providers' _list_resources (DLV-8);
    • a new private provider, kubed/mcp/_tools.py, added at the first plugin, which serves the two tools (DLV-6).

Tech Stack: Python 3.11+, FastMCP >=4.2,<5, pytest, ruff.

Spec: docs/superpowers/specs/delivery.md. The rows are the contract. #21's notes are the brief, approved by Dr K, and this plan records the calls they leave to the builder.

The design this settles

The spec rows say what a client sees. These are the calls below them, and the plan's departures from the brief.

  1. One table of inputs. delivery._INPUTS holds Resource-Prefix, Resources and Listed, each with its query name, its Delivery attribute (None for the prefix), how a value is taken, the rule a warning quotes, and its built-in default. Each input's levels are built from the table, so #22 adds Via as one more row. Each input gets two header levels with a header_prefix and one without.

  2. A level is a function, and the walk is one loop.

    • A level is values -> (raw, source) | None, where values is request_values()'s result or None.
    • The walk tries each level in turn and stops at the first value it takes. An empty value is no value, except Listed's, which is none. An untaken value warns and moves on. With none taken, the built-in default answers: it is the walk's end, not a level.
  3. DLV-14's slot is a place, not a level. This differs from the brief. A level that always gives nothing is dead code, so there is none. #22 inserts DLV-14's level after the query and DLV-15's after the config. Task 1's stand-in test appends a level after the config and proves it answers there.

  4. The config is checked once, when QuickMCP is built.

    • getattr(config, "delivery", None) is read once.
    • Each attribute is checked by its input's own take. listed may be a collection, which is joined with ,.
    • An invalid attribute is warned at construction, naming config delivery.<attribute>, and gives no level. So a bad config warns once per process, not once per session.
    • via is read from #22.
  5. The session for warn-once:

    • on live HTTP, the request's mcp-session-id header;
    • off HTTP, get_context().session_id;
    • otherwise none.

    FastMCP builds a session object, and so an id, per HTTP request, so on HTTP only the header names a real session. The 2026-07-28 protocol sends none, so its key is server-wide.

  6. The warn-once key is (session, source, value), not (session, input, value). This departs from the call #16 accepted, by one word. A bad Kb-Listed and a bad X-MCP-Listed with the same value are two sources, so each warns once.

    • There are 4096 entries, LRU.
    • An entry is never dropped when its session ends, because FastMCP 4.2 gives no such signal to a middleware (Task 1, Step 1 confirms it). The bound alone keeps the set finite, and DLV-5 says "bounded".
  7. One warning shape, from one logger, kubed.mcp.delivery: "%s %r is ignored, and the next source answers: %s" with the source, the value cut to 64 characters, and the input's rule. The prefix warnings move from kubed.mcp.gateway, and their tests move too.

  8. The resolution is pinned beside the plugin pin, not in it.

    • _ResolveScope sits at middleware index 1, between _CallScope and _PinScope, so the build key's prefix is the pinned one.
    • A nested request with the same resolver shares the open resolution.
    • Off a request, _resolved() resolves afresh. It uses the resolver of the context's server when there is one (_RESOLVERS, keyed by FastMCP, as SERVING is), and the bare alias-only resolver otherwise. So a background task's worker on a Kb server still reads Kb-Resource-Prefix.
  9. gateway.prefix() is _resolved().prefix. _VALID moves to delivery._PREFIX, and gateway imports it, so delivery imports nothing of gateway. gateway.HEADER and gateway.QUERY go. They came with #28, which reached only 0.2.0rc1, and neither server imports gateway.

  10. A listed prompt or agent row is material.row exactly. _material builds a _FileResource(TextResource) whose to_mcp_resource() passes _meta=self.meta unless told otherwise. Its row is to_mcp_resource() of that resource, and _Files._list_resources returns the same resources, so the listing and the folder row are one wire form, with no fastmcp key.

  11. Under a prefix, the tools write only each list_resources row's uri. This narrows the brief's "both tools' results are prefixed".

    • Every other text in both results is the build's, prefixed already (GW-5), or the server's own. GW-10 keeps the server's own unrewritten, which a second prefixed() pass would break.
    • So read_resource answers exactly as resources/read does, with or without a prefix.
    • A row's uri is the one structured field a gateway would have prefixed and does not inside a tool result. It is written gateway.prefixed(uri, prefix), which touches served schemes alone, the ones read_resource takes back (GW-4).
  12. read_resource reads through ctx.read_resource(uri). That runs the server's middleware, as _PinScope's docstring relies on, so _TakeThePrefix, the %2F refusal and NameTheIndex apply. A miss is ToolError(message), where the message is the one a client gets from resources/read. For an MCPError that is its .message, so FolderNotFound's hint comes along, and .miss stays unused here.

  13. The pointer gets the URI as sent, since its sentence is for the model, which names addresses as it sent them. A pointer that raises or returns a non-string is logged at error on kubed.mcp.delivery and gives none.

  14. The annotations are kb's (mcp-kb's tool page, TOOL-6): readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False. The titles are "List resources" and "Read a resource".

  15. mcp.tool becomes QuickMCP's own method, with FastMCP's signature, as mcp.resource is.

    • The name is the name keyword, else a positional string, else the function's __name__.
    • For @mcp.tool() with neither, the returned decorator is wrapped to check the function it is given.
    • mcp.server.tool, mcp.server.add_tool and add_provider are the gap DLV-7 names.
  16. No ### Changed line for the prefix fall-through. The prefix's ### Added line is still in [Unreleased]: rc1 did not roll it, so 0.2.0's notes describe the final behaviour.

Global Constraints

  • fastmcp>=4.2,<5. Python 3.11 is the floor, and it gates every PR.
  • kubed/ has no __init__.py (PEP 420).
  • These public names are new:
    • kubed.mcp.Delivery (also kubed.mcp.delivery.Delivery);
    • kubed.mcp.delivery.BinaryPointer;
    • QuickMCP(..., header_prefix=None);
    • QuickMCP.binary_pointer.
  • gateway.prefix() and gateway.prefixed() keep their signatures. Everything else new is private (_).
  • docs/ is the wiki. Commit there on its branch issue-21, push it, then commit the docs pointer here. Never push the wiki's master.
  • Changelog: only [Unreleased], one short line per entry, all under ### Added. Tasks 2, 3 and 4 add their lines.
  • Every task must pass two checks from the repository root, after pip install -e .[test,tasks]:
    • pytest, which test.yml runs;
    • ruff check ., which lint.yml runs.
  • Tests go through a Client, over gateway_server.over_http wherever a header or query is sent, with no network, and pytestmark = pytest.mark.unit.
  • Parity: with no input sent, resources/list, tools/list and every read are what they are today. Dr K checks both servers' dumps in QA.

Review Focus

  1. Empty values. An n8n credential sends X-MCP-Resources: empty, or ?listed=.
    • A person expects the empty X-MCP-Resources to be no value, so the next source answers without a warning.
    • They expect an empty X-MCP-Listed to list none, and to win over the query.
    • Test in Task 1.
  2. Case and spaces. X-MCP-Resources: " OFF " and X-MCP-Listed: "Skills , PROMPTS" resolve as off and {skills, prompts}. Test in Task 1.
  3. No HTTP. On stdio, and in a background task's worker on a Kb server, a person expects:
    • stdio: the config's and the built-in defaults;
    • the worker: Kb-Resource-Prefix, read from the headers it kept.
    • Tests in Task 1 and Task 2.
  4. A folder URI, and kb+ui://, given to read_resource. A person expects:
    • for the folder, the same "read <folder>/_index.md" hint resources/read gives;
    • for kb+ui:// and UI://, the app refusal.
    • Test in Task 4.
  5. A binary_pointer that raises or returns a non-string. A person expects the generic sentence and an error in the log, never a failed read. Test in Task 4.

Task 1: The resolver, warn-once, and the prefix falling through (DLV-1 to DLV-5, GW-1, GW-3)

Files:

  • Create: kubed/mcp/delivery.py
  • Modify: kubed/mcp/request.py:
    • add _session and _warn_once;
    • remove _first_time, _told and _TOLD_MAX.
  • Modify: kubed/mcp/gateway.py:
    • prefix() reads the resolution;
    • prefixed() uses delivery._PREFIX;
    • remove HEADER, QUERY, _VALID, the _first_time import, and log if nothing else uses it.
  • Modify: kubed/mcp/app.py:
    • build self._resolver;
    • register it in _RESOLVERS;
    • insert _ResolveScope at index 1;
    • renumber the two comments after it.
  • Modify: kubed/mcp/__init__.py (export Delivery) and tests/test_facade.py (OWN["kubed.mcp"] gains "Delivery").
  • Modify: tests/gateway_server.py. over_http gains headers: dict[str, str] | None = None and params: dict[str, str] | None = None, merged with header and query. Query values are URL-encoded, except query, which is kept as sent, as today.
  • Modify: tests/test_gateway.py:
    • logger kubed.mcp.delivery;
    • test_an_invalid_prefix_is_none_and_warned_once_per_connection becomes test_an_invalid_prefix_falls_through_warned_once_per_session, and its last block now expects "xx+".
  • Create: tests/test_delivery_inputs.py
  • Modify these specs:
    • docs/superpowers/specs/delivery.md: drop (proposed) from DLV-1 to DLV-5.
    • docs/superpowers/specs/gateway.md:
      • GW-1's second sentence becomes: "The other inputs, and how every input resolves, the prefix included, are delivery's (DLV-2, DLV-3)."
      • GW-3's last sentence becomes: "An invalid one is ignored as DLV-5 says, and the next source answers: an invalid header falls to the query parameter, then to no prefix."
    • docs/superpowers/specs/facade.md:
      • FAC-1: "QuickMCP and Serving are the app's, Delivery is delivery's (DLV-4)";
      • FAC-2's kubed.mcp row gains Delivery after Serving.

Interfaces:

  • Produces, in kubed/mcp/request.py:

    • _WARNED_MAX = 4096. _warned is an OrderedDict[tuple[str | None, str, str], None].
    • _session() -> str | None: design call 5. A RuntimeError from either lookup means none.
    • _warn_once(source: str, value: str) -> bool: True the first time (_session(), source, value) is seen, and False after. A hit moves it to the end, and past _WARNED_MAX the oldest entry goes.
  • Produces, in kubed/mcp/delivery.py, with __all__ = ["Delivery"]:

    • class Delivery(Protocol): read-only properties resources: str | None, listed: str | Collection[str] | None and via: str | None (DLV-4).

    • _PREFIX = re.compile(r"[A-Za-z][A-Za-z0-9+.-]{0,62}\+"), moved from gateway._VALID.

    • Found = tuple[str, str], which is (raw value, source). Level = Callable[[tuple[Values, Values] | None], Found | None].

    • @dataclass(frozen=True) class _Input, with these fields:

      • name: str;
      • query: str;
      • attr: str | None;
      • take: Callable[[str], object], which raises ValueError for a value the input does not take;
      • rule: str;
      • default: object;
      • blank: bool, True when an empty value is a value;
      • plus: bool, True when a query space reads as +.
    • _INPUTS: Mapping[str, _Input] (a MappingProxyType), keyed by name. Each row's take strips the value and compares it in lowercase:

      name query attr take gives default blank plus
      Resource-Prefix prefix None the value, when _PREFIX matches it in full None False True
      Resources resources resources "on" or "off", by DLV-2's spellings "on" False False
      Listed listed listed frozenset of the known kinds named; frozenset() for "" or none; ValueError when no known kind is left frozenset({"skills"}) True False

      The rules, quoted by warnings:

      • the prefix: "a prefix is a letter, then letters, digits, +, - or ., ending in +, at most 64 characters";
      • Resources: "it is on, true, 1, yes, or off, false, 0, no, none";
      • Listed: "it is a comma-separated set of skills, prompts and agents, or empty or none for none".
    • @dataclass(frozen=True) class _Resolved: resources: str, listed: frozenset[str] and prefix: str | None.

    • _header(name: str) -> Level: reads headers[name.lower()][0], with source f"header {name}".

    • _query(entry: _Input) -> Level: reads params[entry.query][0], with source f"query parameter {entry.query}". When entry.plus, a space becomes +.

    • class _Resolver:

      • __init__(self, header_prefix: str | None = None, delivery: object | None = None), which builds self.levels: dict[str, list[Level]]. Each input gets _header(f"X-MCP-{name}"), then _query, then its config level when design call 4 gives one. Task 2 adds the prefixed header.
      • resolve(self, values: tuple[Values, Values] | None) -> _Resolved: one walk per input (design call 2), warning through _warn_once and log.warning (design call 7).
    • _RESOLVED: ContextVar[tuple[_Resolver, _Resolved] | None]. _RESOLVERS is a WeakKeyDictionary[FastMCP, _Resolver], and _BARE = _Resolver().

    • class _ResolveScope(Middleware), built as __init__(self, resolver: _Resolver). Its on_request shares an open resolution of the same resolver, or sets (resolver, resolver.resolve(request_values())) and resets it afterwards.

    • _resolved() -> _Resolved: design call 8.

  • Produces, in kubed/mcp/app.py:

    • self._resolver = _Resolver(None, getattr(config, "delivery", None));
    • _RESOLVERS[self.server] = self._resolver;
    • self.server.middleware.insert(1, _ResolveScope(self._resolver)), before the _PinScope insert. _PinScope goes in at 2 and _TakeThePrefix at 3.
  • Step 1: Read the installed FastMCP's session id. Confirm three things:

    • Context.session_id on HTTP is per HTTP request unless the mcp-session-id header names one;
    • on stdio it is stable for the connection;
    • nothing a middleware can hook fires when a session ends.

    If any of these is otherwise, follow FastMCP's real behaviour in _session and in design call 6, and say so in the commit.

  • Step 2: Write the failing tests in tests/test_delivery_inputs.py.

def server(delivery=None, header_prefix=None) -> QuickMCP:
    # QuickMCP("t", config=SimpleNamespace(delivery=delivery)), plus a tool seen() returning
    # {"resources": r.resources, "listed": sorted(r.listed), "prefix": r.prefix} of _resolved(),
    # and a resource state://resolved returning the same JSON
def config(resources=None, listed=None): return SimpleNamespace(resources=resources, listed=listed, via=None)

@pytest.mark.parametrize("raw", ["on", "true", "1", "yes", "ON", " Yes "])
@pytest.mark.parametrize("raw_off", ["off", "false", "0", "no", "none", " NONE "])
async def test_every_resources_spelling_resolves(...)   # by header and by query: on / off

@pytest.mark.parametrize(("raw", "listed"), [
    ("skills,prompts", ["prompts", "skills"]), (" Skills , PROMPTS ", ["prompts", "skills"]),  # Review Focus 2
    ("", []), ("none", []), (" None ", []), ("prompts,bogus", ["prompts"]),
])
async def test_listed_values(raw, listed)               # by header and by query

async def test_an_empty_resources_value_is_no_value(caplog):   # Review Focus 1
    # headers {"X-MCP-Resources": ""}, params {"resources": "off"} -> "off", and no warning
async def test_an_empty_listed_header_lists_none_and_wins():  # Review Focus 1
    # headers {"X-MCP-Listed": ""}, params {"listed": "prompts"} -> []

async def test_header_beats_query_beats_config_beats_built_in():
    # for Resources and Listed, one source more each time:
    # built-in ("on", ["skills"]); config ("off", ["agents"]); query wins; header wins

@pytest.mark.parametrize("bad", ["header", "query"])
async def test_an_invalid_value_falls_to_the_next_source(bad, caplog):
    # bad "maybe" / "bogus" at `bad`; the next source's value answers; one warning

def test_an_invalid_config_value_warns_once_at_build(caplog):
    # server(config(resources="maybe", listed=["bogus"])) logs two warnings at construction,
    # "config delivery.resources 'maybe' is ignored, and the next source answers: ..." and
    # "config delivery.listed 'bogus' ..."; seen() then gives ("on", ["skills"]), with no more warnings

@pytest.mark.parametrize("listed", ["", [], (), "none"])
async def test_a_config_may_list_none(listed):          # mcp-kb's K3
    # server(config(listed=listed)): seen()["listed"] == []

@pytest.mark.parametrize(("where", "source"), [
    ({"params": {"prefix": "kb"}}, "query parameter prefix"),
    ({"headers": {"X-MCP-Resource-Prefix": "kb"}}, "header X-MCP-Resource-Prefix"),
    ({"headers": {"X-MCP-Listed": "bogus"}}, "header X-MCP-Listed"),
    ({"params": {"resources": "maybe"}}, "query parameter resources"),
])
async def test_a_warning_names_its_true_source(where, source, caplog):
    (record,) = warnings(caplog)  # logger kubed.mcp.delivery
    assert record.getMessage().startswith(f"{source} ")

async def test_warned_once_per_session_and_again_in_a_second(caplog):
    # over_http(mode="legacy", headers {"X-MCP-Resources": "maybe"}): two calls, 1 warning;
    # a second connection, 2
async def test_warned_once_per_value_without_a_session(caplog):
    # default mode: two calls, 1 warning; a second client with the same value, still 1;
    # a new value "perhaps", 2
async def test_the_warnings_remembered_are_bounded(monkeypatch, caplog):
    # monkeypatch request._WARNED_MAX to 2; values a, b, c, then a again: 4 warnings

async def test_an_inserted_level_answers_between_config_and_built_in():  # #22's DLV-15 slot
    # mcp._resolver.levels["Listed"].append(lambda values: ("prompts", "stand-in"))
    # config listed None: ["prompts"]; config listed "agents": ["agents"]; header "skills": ["skills"]

async def test_on_stdio_the_defaults_answer():  # Review Focus 3
    # Client(server(config(resources="off")).server): seen() == {"resources": "off", "listed": ["skills"], "prefix": None}

async def test_a_nested_request_shares_the_resolution():  # DLV-3, design call 8
    # a tool reads state://resolved through ctx.read_resource; under headers
    # {"X-MCP-Listed": "agents", "X-MCP-Resource-Prefix": "kb+"} it equals the tool's own seen()

In tests/test_gateway.py, the renamed test's last block now expects await seen(client) == "xx+" for header kb with query xx+, and its warning to name header X-MCP-Resource-Prefix.

  • Step 3: Run them to see them fail

    Run: pytest tests/test_delivery_inputs.py tests/test_gateway.py -v Expected: FAIL. kubed.mcp.delivery cannot be imported, and the gateway test still gets None.

  • Step 4: Implement the Interfaces above.

  • Step 5: Run pytest and ruff check .. Expected: all pass, with tests/test_gateway_addresses.py and tests/test_gateway_text.py unchanged.

  • Step 6: Spec (the Files list above). There is no changelog line: the inputs do nothing a client sees until Tasks 3 and 4, and design call 16 covers the prefix.

  • Step 7: Commit (the wiki first, then here): feat(delivery): resolve the delivery inputs and the prefix by levels, falling through


Task 2: The server's own header prefix (DLV-16, APP-2, GW-2)

Files:

  • Modify: kubed/mcp/delivery.py (_header_prefix; _Resolver.__init__ puts the prefixed header first)
  • Modify: kubed/mcp/app.py (QuickMCP.__init__ takes header_prefix, and its docstring names it)
  • Create: tests/test_header_prefix.py
  • Modify these specs:
    • docs/superpowers/specs/delivery.md: drop (proposed) from DLV-16.
    • docs/superpowers/specs/app.md, APP-2: it becomes "QuickMCP(name, *, config=None, header_prefix=None, **fastmcp_options) builds one FastMCP server, named name, with fastmcp_options passed through unchanged. header_prefix names the server's own headers (DLV-16)." The rest of the row is unchanged.
    • docs/superpowers/specs/gateway.md:
      • GW-1: "are delivery's (DLV-2, DLV-3, DLV-16)".
      • GW-2's first sentence: "A request may name its prefix as the header X-MCP-Resource-Prefix, the server's own <Prefix>-Resource-Prefix (DLV-16), or the query parameter prefix, resolved in DLV-3's order."
      • GW-2: "With neither" becomes "With none".
  • Modify: CHANGELOG.md

Interfaces:

  • Consumes: _Resolver, _header and _INPUTS from Task 1.

  • Produces, in kubed/mcp/delivery.py:

    • _HEADER_TOKEN = re.compile(r"[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*").
    • _header_prefix(value: str | None) -> str | None. It returns None for None and the value as given when it is valid. It raises ValueError in two cases:
      • when _HEADER_TOKEN does not match the value in full: f"header_prefix {value!r} is not a header-name token: letters and digits, with - only between them (Kb, Sf, My-Co)";
      • when value.lower() == "x-mcp": f"header_prefix {value!r} is the shared X-MCP alias: name the server's own".
    • _Resolver.__init__, given a prefix, makes each input's levels start with _header(f"{header_prefix}-{name}") and then _header(f"X-MCP-{name}"). The warning names the prefixed header as given (header Kb-Listed).
  • Produces, in kubed/mcp/app.py:

    • QuickMCP.__init__(self, name: str, *, config: object | None = None, header_prefix: str | None = None, **fastmcp_options: Any).
    • It calls _header_prefix(header_prefix) first, before anything is built, and passes the result to _Resolver.
  • Step 1: Write the failing tests in tests/test_header_prefix.py. Reuse Task 1's server() and seen(), moved into a helper module or imported from test_delivery_inputs.

INPUTS = [  # (header name, query, two valid values, the resolved key)
    ("Resource-Prefix", "prefix", "kb+", "xx+", "prefix"),
    ("Resources", "resources", "off", "on", "resources"),
    ("Listed", "listed", "prompts", "agents", "listed"),
]

@pytest.mark.parametrize(INPUTS)
async def test_the_servers_name_beats_the_alias_beats_the_query(...):
    # server(header_prefix="Kb"): {f"Kb-{n}": a, f"X-MCP-{n}": b} -> a; {f"X-MCP-{n}": a} + query b -> a

async def test_kb_resource_prefix_serves_kb_plus(tmp_path):
    # kit(tmp_path) rebuilt with QuickMCP("t", header_prefix="Kb"); headers {"Kb-Resource-Prefix": "kb+"}
    read = await client.read_resource("kb+skill://lib/guide/SKILL.md")
    assert "kb+skill://lib/guide/references/a.md" in read[0].text

async def test_a_bad_server_header_falls_to_the_alias_with_one_warning(caplog):
    # {"Kb-Listed": "bogus", "X-MCP-Listed": "prompts"}: ["prompts"]; one warning starting "header Kb-Listed 'bogus'"

async def test_without_a_header_prefix_kb_headers_are_ignored():
    # server(): {"Kb-Listed": "prompts", "Kb-Resource-Prefix": "kb+"} -> ["skills"], None

async def test_header_names_match_in_any_case():
    # server(header_prefix="KB"): {"kb-listed": "prompts"} -> ["prompts"]

def test_a_background_task_reads_the_servers_header():  # Review Focus 3
    # mcp = server(header_prefix="Kb"); inside `async with Context(fastmcp=mcp.server)` with
    # _background_task_headers {"Kb-Resource-Prefix": "kb+"}: gateway.prefix() == "kb+"

@pytest.mark.parametrize("bad", ["", " ", "-Kb", "Kb-", "Kb--Co", "K b", "Kb_", "Kb:", "X-MCP", "x-mcp"])
def test_an_invalid_header_prefix_is_refused(bad):
    with pytest.raises(ValueError, match="header_prefix"):
        QuickMCP("t", header_prefix=bad)

@pytest.mark.parametrize("good", ["Kb", "Sf", "My-Co", "kb", "X1"])
def test_a_valid_header_prefix_is_taken(good): QuickMCP("t", header_prefix=good)
  • Step 2: Run them to see them fail

    Run: pytest tests/test_header_prefix.py -v Expected: FAIL. QuickMCP passes header_prefix to FastMCP, which refuses it.

  • Step 3: Implement the Interfaces above.

  • Step 4: Run pytest and ruff check .. Expected: all pass.

  • Step 5: Spec and changelog (the Files list above). Under ### Added: "QuickMCP(…, header_prefix=\"Kb\") reads every X-MCP-* header as Kb-* too, the server's own name winning."

  • Step 6: Commit: feat(delivery): read every input under the server's own header prefix


Task 3: X-MCP-Listed chooses what resources/list shows (DLV-8)

Files:

  • Modify: kubed/mcp/plugins.py:
    • add _FileResource;
    • _material builds one, and its row is to_mcp_resource() with no argument;
    • _Skills._list_resources and _Files._list_resources read _resolved().listed.
  • Create: tests/test_listed.py
  • Modify: docs/superpowers/specs/delivery.md (drop (proposed) from DLV-8) and CHANGELOG.md

Interfaces:

  • Consumes: delivery._resolved() from Task 1.

  • Produces, in kubed/mcp/plugins.py:

    • class _FileResource(TextResource), overriding to_mcp_resource(self, **overrides) to call super() with {"_meta": self.meta, **overrides}. _Material.resource is one.
    • _Skills._list_resources(self) -> list[Resource]: [] when "skills" is not in _resolved().listed, else super()'s.
    • _Files._list_resources(self) -> list[Resource]: material.resource for each material of the pinned build's files, in order, whose URI scheme (prompts or agents) is in _resolved().listed.
  • Step 1: Read how the installed FastMCP's resources/list handler turns a listed Resource into its row. If it does not call to_mcp_resource(), so _FileResource cannot make the listed row equal material.row, stop and report on the PR. Do not override the handler.

  • Step 2: Write the failing tests in tests/test_listed.py. Use the demo plugin (copy(tmp_path)), which has commands and agents, plus a server's own resource state://own.

async def test_the_default_listing_is_unchanged(tmp_path):
    # no input: the skill:// rows are the SKILL.md rows alone, as listed_by gives today; state://own is listed;
    # no prompts:// or agents:// row
async def test_listed_prompts_adds_one_row_per_prompt(tmp_path):
    # headers {"X-MCP-Listed": "skills,prompts"}
    rows = [r.model_dump(by_alias=True, exclude_none=True, mode="json") for r in await client.list_resources()]
    prompt_rows = [r for r in rows if r["uri"].startswith("prompts://")]
    build = (await mcp._plugins.pinned()).build
    assert prompt_rows == [dict(m.row) for u, m in build.files.items() if u.startswith("prompts://")]
    assert all("fastmcp" not in r["_meta"] for r in prompt_rows)
    assert len(prompt_rows) == len(await client.list_prompts())   # the plugin's prompts alone
async def test_listed_agents_adds_one_row_per_agent(tmp_path):   # likewise for agents://
async def test_an_empty_listed_shows_only_the_servers_own(tmp_path):
    # {"X-MCP-Listed": ""}: rows == [state://own]; and a catalogue served with skills.serve on
    # the same server (skill_server.make_skill) still lists its SKILL.md
async def test_unknown_kinds_are_dropped(tmp_path):   # "prompts,bogus": prompts rows, no skill:// rows
async def test_folders_and_indexes_are_never_listed(tmp_path):
    # "skills,prompts,agents": no row ends _index.md / _index.json, and none is a folder of build.folders
async def test_the_other_lists_do_not_change(tmp_path):
    # prompts/list, skills/list and agents/list under "" equal those under no input
async def test_a_folder_row_is_unchanged(tmp_path):
    # read_directory(client, uri="prompts://t") rows for files still equal build.files[...].row (the override kept PLUG-68's row)
async def test_a_config_that_lists_none(tmp_path):    # mcp-kb's K3
    # QuickMCP("t", config=SimpleNamespace(delivery=config(listed=""))): only state://own
  • Step 3: Run them to see them fail

    Run: pytest tests/test_listed.py -v Expected: FAIL. Nothing changes with X-MCP-Listed. test_the_default_listing_is_unchanged and test_the_other_lists_do_not_change pass already.

  • Step 4: Implement the Interfaces above.

  • Step 5: Run pytest and ruff check .. Expected: all pass, with tests/test_prompt_and_agent_resources.py unchanged. Its whole-_meta row tests guard _FileResource.

  • Step 6: Spec and changelog (the Files list above). Under ### Added: "X-MCP-Listed (or ?listed=) chooses which of skills, prompts and agents resources/list shows, and a config's delivery sets the default."

  • Step 7: Commit: feat(delivery): X-MCP-Listed chooses the kinds resources/list shows


Task 4: The resource tools, binary_pointer, and the name check (DLV-6, DLV-7)

Files:

  • Create: kubed/mcp/_tools.py
  • Modify: kubed/mcp/delivery.py: add BinaryPointer, and add it to __all__.
  • Modify: kubed/mcp/plugins.py:
    • Plugins._tools, _pointer and set_binary_pointer;
    • check_own_tool and _own_tool;
    • _check_first refuses an own tool;
    • _providers adds _ResourceTools.
  • Modify: kubed/mcp/app.py:
    • QuickMCP.tool becomes a method;
    • add QuickMCP.binary_pointer;
    • remove self.tool = self.server.tool.
  • Create: tests/test_resource_tools.py
  • Modify these specs:
    • docs/superpowers/specs/delivery.md: drop (proposed) from DLV-6 and DLV-7.
    • docs/superpowers/specs/app.md:
      • APP-4: drop mcp.tool from the first list, and add after mcp.resource's clause: "mcp.tool has FastMCP's signature and passes what it is given through to mcp.server.tool, except that it refuses list_resources and read_resource once the server has a plugin (DLV-7)."
      • APP-12 gains: "mcp.binary_pointer(fn) says where a binary's link is listed (DLV-6)."
    • docs/superpowers/plans/2026-11-24-material-delivery-design.md: the History gains "Step 5 is built (quick-mcp#41): DLV-1 to DLV-8 and DLV-16."
  • Modify: CHANGELOG.md

Interfaces:

  • Consumes: _resolved() (Task 1), gateway.prefixed, _media.media_type, and skills._wire.

  • Produces:

    • In kubed/mcp/delivery.py: BinaryPointer = Callable[[str], str | None].
    • In kubed/mcp/_tools.py:
      • TOOL_NAMES = ("list_resources", "read_resource").

      • _UI = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*\+)?ui://", re.IGNORECASE), matched at the start.

      • _IMAGES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"}).

      • NOT_TEXT = "Not returned: binary content is not text."

      • class _ResourceTools(Provider), built as __init__(self, pointer: Callable[[], BinaryPointer | None]), with these methods:

        • _list_tools(self) -> list[Tool]: both tools when _resolved().resources == "off", else [];
        • _get_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None: either tool by name, always;
        • get_tasks(self) -> list: [].

        Its tools are built once with Tool.from_function and design call 14's ToolAnnotations. The descriptions are "List every resource this server has, as resources/list does for this request." and "Read one resource by its URI, as resources/read does."

      • async def _list(self) -> ToolResult: one TextContent, json.dumps({"resources": rows}). rows holds each listed resource's wire form, built as resources/list builds it, less _UI URIs, with each uri written prefixed(uri, prefix) (design call 11). The resources come from get_context().fastmcp, through the server's middleware as resources/list is.

      • async def _read(self, uri: str) -> ToolResult, in order:

        1. it refuses a _UI match with ToolError(f"{uri} is an app for a host to draw, not to read.");
        2. it reads await get_context().read_resource(uri);
        3. a miss becomes ToolError (design call 12);
        4. otherwise its contents become _contents(uri, contents, pointer).
      • _contents(uri: str, contents: Iterable[Any], pointer: BinaryPointer | None) -> list[TextContent | ImageContent]: DLV-6's mapping. The media type is the declared one, or _media.media_type(uri path) when it declares none or application/octet-stream. The description JSON's keys are in DLV-6's order.

      • _pointed(pointer: BinaryPointer | None, uri: str) -> str | None: design call 13.

    • In kubed/mcp/plugins.py:
      • _own_tool(server: FastMCP) -> str | None: the first of the server's own tools named in TOOL_NAMES, read from local_provider._components as _own_reserved reads them, with its warning when that attribute is missing.
      • _check_first raises PluginError(f"the server has its own tool {name}, and list_resources and read_resource are the plugins' (DLV-7)").
      • Plugins.check_own_tool(name: str | None) raises ValueError(f"{name}: list_resources and read_resource are the plugins' in a server that has one") when self._tools is set and name is in TOOL_NAMES.
      • Plugins.set_binary_pointer(fn: BinaryPointer) replaces self._pointer.
      • _providers adds self._tools = _ResourceTools(lambda: self._pointer) with add_provider, beside _Files.
    • In kubed/mcp/app.py:
      • @_signed_as(FastMCP.tool) def tool(self, name_or_fn: Any = None, *args: Any, **kwargs: Any) -> Any follows design call 15. A decorator still returns what FastMCP's returns (APP-4).
      • def binary_pointer(self, fn: BinaryPointer) -> BinaryPointer, a decorator that returns fn, with its docstring from DLV-6.
  • Step 1: Read the installed FastMCP. Find four things:

    • which Provider hook tools/call uses to find a tool (_get_tool, or a listing), so a tool hidden from _list_tools stays callable;
    • whether a call checks that the tool is listed;
    • what Context.read_resource returns (its contents' content and mime_type);
    • which call lists resources through the middleware, and how it builds a row.

    If a hidden tool cannot be called, stop and report on the PR.

  • Step 2: Write the failing tests in tests/test_resource_tools.py. The server is copy(tmp_path) with a skills/demo-guide/logo.png, plus these own resources:

    • ui://app/x;
    • state://own (text);
    • files://x.png (PNG bytes, image/png);
    • files://y.webp (WebP bytes, no type);
    • files://n.txt (b"hello", text/plain);
    • files://i.svg (SVG bytes, image/svg+xml);
    • files://l1.txt ("café".encode("latin-1"), text/plain);
    • files://x.bin (b"\x00\x01", application/octet-stream);
    • a template state://{id}.

    call(client, name, **args) returns the CallToolResult. OFF = {"X-MCP-Resources": "off"}.

async def test_off_lists_the_two_read_only_tools(tmp_path):
    # tools/list names include both; each tool's annotations:
    assert (a.readOnlyHint, a.destructiveHint, a.idempotentHint, a.openWorldHint) == (True, False, True, False)
async def test_on_hides_them_and_they_stay_callable(tmp_path):
    # no input: neither in tools/list; call_tool("list_resources") answers
async def test_list_resources_is_resources_list_less_ui(tmp_path):
    # under OFF + {"X-MCP-Listed": "skills,prompts"}:
    rows = json.loads(result.content[0].text)["resources"]
    expected = [r.model_dump(by_alias=True, exclude_none=True, mode="json") for r in await client.list_resources()]
    assert rows == [r for r in expected if not r["uri"].startswith("ui://")]
    # no row for state://{id}
async def test_read_resource_reads_text_as_resources_read(tmp_path):
    # ENTRY and state://own: TextContent text == client.read_resource(...)[0].text
@pytest.mark.parametrize(("uri", "media"), [("files://x.png", "image/png"), ("files://y.webp", "image/webp"),
                                            ("skill://t/demo-guide/logo.png", "image/png")])
async def test_images_are_image_content(tmp_path, uri, media):
    # ImageContent, mimeType == media, base64.b64decode(data) == the bytes
@pytest.mark.parametrize(("uri", "text"), [("files://n.txt", "hello"), ("files://i.svg", SVG)])
async def test_text_blobs_are_text(tmp_path, uri, text)
@pytest.mark.parametrize("uri", ["files://x.bin", "files://l1.txt"])
async def test_other_binary_is_a_description(tmp_path, uri):
    assert json.loads(content.text) == {"uri": uri, "mime_type": MEDIA[uri], "bytes": len(DATA[uri]),
                                        "binary": True, "read": "Not returned: binary content is not text."}
async def test_the_pointer_follows_the_sentence(tmp_path):
    # @mcp.binary_pointer returning f"Its link is listed at files://index for {uri}."
    assert read == "Not returned: binary content is not text. Its link is listed at files://index for files://x.bin."
@pytest.mark.parametrize("pointer", [lambda uri: None, lambda uri: 1 / 0, lambda uri: 3])
async def test_a_pointer_that_gives_nothing_leaves_the_sentence(tmp_path, pointer, caplog):  # Review Focus 5
    # read == NOT_TEXT; an error record on kubed.mcp.delivery for the raise and the 3, none for None
@pytest.mark.parametrize("uri", ["skill://t/nope/SKILL.md", "skill://t/demo-guide/references", "skill://t/demo-guide%2FSKILL.md"])
async def test_a_miss_is_a_tool_error_with_the_reads_message(tmp_path, uri):  # Review Focus 4
    # with pytest.raises(McpError) as read: client.read_resource(uri)
    # the tool's result isError, and its text == read.value.error.message
@pytest.mark.parametrize("uri", ["ui://app/x", "UI://app/x", "kb+ui://app/x"])
async def test_ui_is_refused(tmp_path, uri):  # Review Focus 4
    # isError, text == f"{uri} is an app for a host to draw, not to read."
async def test_under_a_prefix_rows_are_prefixed_and_reads_take_it(tmp_path):
    # kit(tmp_path) over_http(header="kb+", headers=OFF):
    # "kb+skill://lib/guide/SKILL.md" in [r["uri"] for r in rows]; a row's description is the build's
    # read_resource("kb+skill://lib/guide/SKILL.md").text == client.read_resource(same)[0].text,
    # and holds "kb+skill://lib/guide/references/a.md"
async def test_an_inner_read_after_serve_answers_from_the_outer_set(tmp_path):  # item 1, _PINS
    # an own tool swap(): reads ENTRY via ctx.read_resource, calls mcp.serve(mcp.plugin_set()),
    # reads ENTRY again: both texts equal; a later client read of ENTRY misses
def test_an_own_tool_refuses_the_first_plugin(tmp_path):    # DLV-7, both first doors
    # @mcp.tool def read_resource(): ... ; add_plugin raises PluginError naming read_resource;
    # likewise list_resources through mcp.serve(staging); nothing is served
@pytest.mark.parametrize("form", ["bare", "called", "positional", "keyword"])
def test_mcp_tool_refuses_the_names_once_a_plugin_is_served(tmp_path, form):
    # @mcp.tool / @mcp.tool() / @mcp.tool("read_resource") / mcp.tool(fn, name="list_resources"): ValueError
    # and @mcp.tool def other() still registers and returns what FastMCP's returns
  • Step 3: Run them to see them fail

    Run: pytest tests/test_resource_tools.py -v Expected: FAIL. There is no such tool, and an own read_resource is not refused. test_an_inner_read_after_serve_answers_from_the_outer_set passes already, because it pins #18's behaviour.

  • Step 4: Implement the Interfaces above.

  • Step 5: Run pytest and ruff check .. Expected: all pass, with tests/test_app.py unchanged.

  • Step 6: Spec, changelog and History (the Files list above).

    • Under ### Added: "X-MCP-Resources: off (or ?resources=off) lists read-only list_resources and read_resource tools for clients that cannot read resources."
    • Under ### Added: "mcp.binary_pointer(fn) tells read_resource where a binary's link is listed."
    • Check that [Unreleased] holds Task 2's and Task 3's lines and these two, one line each.
  • Step 7: Commit: feat(delivery): list_resources and read_resource for clients that cannot read resources


After the tasks

Dr K's QA, not CI:

  • both servers' default dumps are unchanged;
  • kb's gateway's Kb-Resource-Prefix serves kb+ through kubed-mcp, with header_prefix="Kb" (K3, mcp-kb#89).

0.2.0rc2 is cut after this merges.

Clone this wiki locally