Repository navigation
2026 11 25 delivery inputs
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
Deliveryconfig protocol; - a resolver that is an ordered list of levels per input;
- a middleware that resolves once per request into a
ContextVar.
- a table of them, and the
-
gateway.prefix()reads that resolution. The warn-once inrequest.pyis 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).
- its skills and files providers'
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 spec rows say what a client sees. These are the calls below them, and the plan's departures from the brief.
-
One table of inputs.
delivery._INPUTSholdsResource-Prefix,ResourcesandListed, each with its query name, itsDeliveryattribute (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 addsViaas one more row. Each input gets two header levels with aheader_prefixand one without. -
A level is a function, and the walk is one loop.
- A level is
values -> (raw, source) | None, wherevaluesisrequest_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.
- A level is
-
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.
-
The config is checked once, when
QuickMCPis built.-
getattr(config, "delivery", None)is read once. - Each attribute is checked by its input's own take.
listedmay 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. -
viais read from #22.
-
-
The session for warn-once:
- on live HTTP, the request's
mcp-session-idheader; - 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.
- on live HTTP, the request's
-
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-Listedand a badX-MCP-Listedwith 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".
-
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 fromkubed.mcp.gateway, and their tests move too. -
The resolution is pinned beside the plugin pin, not in it.
-
_ResolveScopesits at middleware index 1, between_CallScopeand_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 byFastMCP, asSERVINGis), and the bare alias-only resolver otherwise. So a background task's worker on aKbserver still readsKb-Resource-Prefix.
-
-
gateway.prefix()is_resolved().prefix._VALIDmoves todelivery._PREFIX, andgatewayimports it, sodeliveryimports nothing ofgateway.gateway.HEADERandgateway.QUERYgo. They came with #28, which reached only 0.2.0rc1, and neither server importsgateway. -
A listed prompt or agent row is
material.rowexactly._materialbuilds a_FileResource(TextResource)whoseto_mcp_resource()passes_meta=self.metaunless told otherwise. Its row isto_mcp_resource()of that resource, and_Files._list_resourcesreturns the same resources, so the listing and the folder row are one wire form, with nofastmcpkey. -
Under a prefix, the tools write only each
list_resourcesrow'suri. 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_resourceanswers exactly asresources/readdoes, with or without a prefix. - A row's
uriis the one structured field a gateway would have prefixed and does not inside a tool result. It is writtengateway.prefixed(uri, prefix), which touches served schemes alone, the onesread_resourcetakes back (GW-4).
- 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
-
read_resourcereads throughctx.read_resource(uri). That runs the server's middleware, as_PinScope's docstring relies on, so_TakeThePrefix, the%2Frefusal andNameTheIndexapply. A miss isToolError(message), where the message is the one a client gets fromresources/read. For anMCPErrorthat is its.message, soFolderNotFound's hint comes along, and.missstays unused here. -
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.deliveryand gives none. -
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". -
mcp.toolbecomesQuickMCP's own method, with FastMCP's signature, asmcp.resourceis.- The name is the
namekeyword, 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_toolandadd_providerare the gap DLV-7 names.
- The name is the
-
No
### Changedline for the prefix fall-through. The prefix's### Addedline is still in[Unreleased]: rc1 did not roll it, so 0.2.0's notes describe the final behaviour.
-
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(alsokubed.mcp.delivery.Delivery); -
kubed.mcp.delivery.BinaryPointer; -
QuickMCP(..., header_prefix=None); -
QuickMCP.binary_pointer.
-
-
gateway.prefix()andgateway.prefixed()keep their signatures. Everything else new is private (_). -
docs/is the wiki. Commit there on its branchissue-21, push it, then commit thedocspointer here. Never push the wiki'smaster. - 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, whichtest.ymlruns; -
ruff check ., whichlint.ymlruns.
-
- Tests go through a
Client, overgateway_server.over_httpwherever a header or query is sent, with no network, andpytestmark = pytest.mark.unit. - Parity: with no input sent,
resources/list,tools/listand every read are what they are today. Dr K checks both servers' dumps in QA.
-
Empty values. An n8n credential sends
X-MCP-Resources:empty, or?listed=.- A person expects the empty
X-MCP-Resourcesto be no value, so the next source answers without a warning. - They expect an empty
X-MCP-Listedto list none, and to win over the query. - Test in Task 1.
- A person expects the empty
-
Case and spaces.
X-MCP-Resources: " OFF "andX-MCP-Listed: "Skills , PROMPTS"resolve asoffand {skills, prompts}. Test in Task 1. -
No HTTP. On stdio, and in a background task's worker on a
Kbserver, 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.
-
A folder URI, and
kb+ui://, given toread_resource. A person expects:- for the folder, the same "read
<folder>/_index.md" hintresources/readgives; - for
kb+ui://andUI://, the app refusal. - Test in Task 4.
- for the folder, the same "read
-
A
binary_pointerthat 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.
Files:
- Create:
kubed/mcp/delivery.py - Modify:
kubed/mcp/request.py:- add
_sessionand_warn_once; - remove
_first_time,_toldand_TOLD_MAX.
- add
- Modify:
kubed/mcp/gateway.py:-
prefix()reads the resolution; -
prefixed()usesdelivery._PREFIX; - remove
HEADER,QUERY,_VALID, the_first_timeimport, andlogif nothing else uses it.
-
- Modify:
kubed/mcp/app.py:- build
self._resolver; - register it in
_RESOLVERS; - insert
_ResolveScopeat index 1; - renumber the two comments after it.
- build
- Modify:
kubed/mcp/__init__.py(exportDelivery) andtests/test_facade.py(OWN["kubed.mcp"]gains"Delivery"). - Modify:
tests/gateway_server.py.over_httpgainsheaders: dict[str, str] | None = Noneandparams: dict[str, str] | None = None, merged withheaderandquery. Query values are URL-encoded, exceptquery, 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_connectionbecomestest_an_invalid_prefix_falls_through_warned_once_per_session, and its last block now expects"xx+".
- logger
- 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:
-
Interfaces:
-
Produces, in
kubed/mcp/request.py:-
_WARNED_MAX = 4096._warnedis anOrderedDict[tuple[str | None, str, str], None]. -
_session() -> str | None: design call 5. ARuntimeErrorfrom 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_MAXthe oldest entry goes.
-
-
Produces, in
kubed/mcp/delivery.py, with__all__ = ["Delivery"]:-
class Delivery(Protocol): read-only propertiesresources: str | None,listed: str | Collection[str] | Noneandvia: str | None(DLV-4). -
_PREFIX = re.compile(r"[A-Za-z][A-Za-z0-9+.-]{0,62}\+"), moved fromgateway._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 raisesValueErrorfor 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](aMappingProxyType), keyed byname. Each row'stakestrips the value and compares it in lowercase:name query attr take gives default blank plus Resource-PrefixprefixNone the value, when _PREFIXmatches it in fullNone False True Resourcesresourcesresources"on"or"off", by DLV-2's spellings"on"False False Listedlistedlistedfrozensetof the known kinds named;frozenset()for""ornone;ValueErrorwhen no known kind is leftfrozenset({"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".
- the prefix:
-
@dataclass(frozen=True) class _Resolved:resources: str,listed: frozenset[str]andprefix: str | None. -
_header(name: str) -> Level: readsheaders[name.lower()][0], with sourcef"header {name}". -
_query(entry: _Input) -> Level: readsparams[entry.query][0], with sourcef"query parameter {entry.query}". Whenentry.plus, a space becomes+. -
class _Resolver:-
__init__(self, header_prefix: str | None = None, delivery: object | None = None), which buildsself.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_onceandlog.warning(design call 7).
-
-
_RESOLVED: ContextVar[tuple[_Resolver, _Resolved] | None]._RESOLVERSis aWeakKeyDictionary[FastMCP, _Resolver], and_BARE = _Resolver(). -
class _ResolveScope(Middleware), built as__init__(self, resolver: _Resolver). Itson_requestshares 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_PinScopeinsert._PinScopegoes in at 2 and_TakeThePrefixat 3.
-
-
Step 1: Read the installed FastMCP's session id. Confirm three things:
-
Context.session_idon HTTP is per HTTP request unless themcp-session-idheader 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
_sessionand 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 -vExpected: FAIL.kubed.mcp.deliverycannot be imported, and the gateway test still gets None. -
Step 4: Implement the Interfaces above.
-
Step 5: Run
pytestandruff check .. Expected: all pass, withtests/test_gateway_addresses.pyandtests/test_gateway_text.pyunchanged. -
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
Files:
- Modify:
kubed/mcp/delivery.py(_header_prefix;_Resolver.__init__puts the prefixed header first) - Modify:
kubed/mcp/app.py(QuickMCP.__init__takesheader_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, namedname, withfastmcp_optionspassed through unchanged.header_prefixnames 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 parameterprefix, resolved in DLV-3's order." - GW-2: "With neither" becomes "With none".
-
- Modify:
CHANGELOG.md
Interfaces:
-
Consumes:
_Resolver,_headerand_INPUTSfrom 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 raisesValueErrorin two cases:- when
_HEADER_TOKENdoes 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".
- when
-
_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'sserver()andseen(), moved into a helper module or imported fromtest_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 -vExpected: FAIL.QuickMCPpassesheader_prefixto FastMCP, which refuses it. -
Step 3: Implement the Interfaces above.
-
Step 4: Run
pytestandruff check .. Expected: all pass. -
Step 5: Spec and changelog (the Files list above). Under
### Added: "QuickMCP(…, header_prefix=\"Kb\")reads everyX-MCP-*header asKb-*too, the server's own name winning." -
Step 6: Commit:
feat(delivery): read every input under the server's own header prefix
Files:
- Modify:
kubed/mcp/plugins.py:- add
_FileResource; -
_materialbuilds one, and its row isto_mcp_resource()with no argument; -
_Skills._list_resourcesand_Files._list_resourcesread_resolved().listed.
- add
- Create:
tests/test_listed.py - Modify:
docs/superpowers/specs/delivery.md(drop (proposed) from DLV-8) andCHANGELOG.md
Interfaces:
-
Consumes:
delivery._resolved()from Task 1. -
Produces, in
kubed/mcp/plugins.py:-
class _FileResource(TextResource), overridingto_mcp_resource(self, **overrides)to callsuper()with{"_meta": self.meta, **overrides}._Material.resourceis one. -
_Skills._list_resources(self) -> list[Resource]:[]when"skills"is not in_resolved().listed, elsesuper()'s. -
_Files._list_resources(self) -> list[Resource]:material.resourcefor each material of the pinned build'sfiles, in order, whose URI scheme (promptsoragents) is in_resolved().listed.
-
-
Step 1: Read how the installed FastMCP's
resources/listhandler turns a listedResourceinto its row. If it does not callto_mcp_resource(), so_FileResourcecannot make the listed row equalmaterial.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 resourcestate://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 -vExpected: FAIL. Nothing changes withX-MCP-Listed.test_the_default_listing_is_unchangedandtest_the_other_lists_do_not_changepass already. -
Step 4: Implement the Interfaces above.
-
Step 5: Run
pytestandruff check .. Expected: all pass, withtests/test_prompt_and_agent_resources.pyunchanged. Its whole-_metarow 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 agentsresources/listshows, and a config'sdeliverysets the default." -
Step 7: Commit:
feat(delivery): X-MCP-Listed chooses the kinds resources/list shows
Files:
- Create:
kubed/mcp/_tools.py - Modify:
kubed/mcp/delivery.py: addBinaryPointer, and add it to__all__. - Modify:
kubed/mcp/plugins.py:-
Plugins._tools,_pointerandset_binary_pointer; -
check_own_tooland_own_tool; -
_check_firstrefuses an own tool; -
_providersadds_ResourceTools.
-
- Modify:
kubed/mcp/app.py:-
QuickMCP.toolbecomes 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.toolfrom the first list, and add aftermcp.resource's clause: "mcp.toolhas FastMCP's signature and passes what it is given through tomcp.server.tool, except that it refuseslist_resourcesandread_resourceonce the server has a plugin (DLV-7)." - APP-12 gains: "
mcp.binary_pointer(fn)says where a binary's link is listed (DLV-6)."
- APP-4: drop
-
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, andskills._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_functionand design call 14'sToolAnnotations. 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: oneTextContent,json.dumps({"resources": rows}).rowsholds each listed resource's wire form, built asresources/listbuilds it, less_UIURIs, with eachuriwrittenprefixed(uri, prefix)(design call 11). The resources come fromget_context().fastmcp, through the server's middleware asresources/listis. -
async def _read(self, uri: str) -> ToolResult, in order:- it refuses a
_UImatch withToolError(f"{uri} is an app for a host to draw, not to read."); - it reads
await get_context().read_resource(uri); - a miss becomes
ToolError(design call 12); - otherwise its contents become
_contents(uri, contents, pointer).
- it refuses a
-
_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 orapplication/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 inTOOL_NAMES, read fromlocal_provider._componentsas_own_reservedreads them, with its warning when that attribute is missing. -
_check_firstraisesPluginError(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)raisesValueError(f"{name}: list_resources and read_resource are the plugins' in a server that has one")whenself._toolsis set andnameis inTOOL_NAMES. -
Plugins.set_binary_pointer(fn: BinaryPointer)replacesself._pointer. -
_providersaddsself._tools = _ResourceTools(lambda: self._pointer)withadd_provider, beside_Files.
-
- In
kubed/mcp/app.py:-
@_signed_as(FastMCP.tool) def tool(self, name_or_fn: Any = None, *args: Any, **kwargs: Any) -> Anyfollows design call 15. A decorator still returns what FastMCP's returns (APP-4). -
def binary_pointer(self, fn: BinaryPointer) -> BinaryPointer, a decorator that returnsfn, with its docstring from DLV-6.
-
- In
-
Step 1: Read the installed FastMCP. Find four things:
- which
Providerhooktools/calluses to find a tool (_get_tool, or a listing), so a tool hidden from_list_toolsstays callable; - whether a call checks that the tool is listed;
- what
Context.read_resourcereturns (its contents'contentandmime_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.
- which
-
Step 2: Write the failing tests in
tests/test_resource_tools.py. The server iscopy(tmp_path)with askills/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 theCallToolResult.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 -vExpected: FAIL. There is no such tool, and an ownread_resourceis not refused.test_an_inner_read_after_serve_answers_from_the_outer_setpasses already, because it pins #18's behaviour. -
Step 4: Implement the Interfaces above.
-
Step 5: Run
pytestandruff check .. Expected: all pass, withtests/test_app.pyunchanged. -
Step 6: Spec, changelog and History (the Files list above).
- Under
### Added: "X-MCP-Resources: off(or?resources=off) lists read-onlylist_resourcesandread_resourcetools for clients that cannot read resources." - Under
### Added: "mcp.binary_pointer(fn)tellsread_resourcewhere a binary's link is listed." - Check that
[Unreleased]holds Task 2's and Task 3's lines and these two, one line each.
- Under
-
Step 7: Commit:
feat(delivery): list_resources and read_resource for clients that cannot read resources
Dr K's QA, not CI:
- both servers' default dumps are unchanged;
- kb's gateway's
Kb-Resource-Prefixserveskb+through kubed-mcp, withheader_prefix="Kb"(K3, mcp-kb#89).
0.2.0rc2 is cut after this merges.
These pages describe what is on main; the spec says what is built and what is only proposed.
kubed-mcp · MIT