Repository navigation
2026 11 27 an async plugin view
History. Written 2026-11-27 for #86 (quick-mcp#92, part of epic #83). What it changes is in the living spec: plugins PLUG-53, which Task 3 rewrites. PLUG-51 and PLUG-55 are unchanged. The mcp-kb half of #86 is kubed-io/mcp-kb#116, which does not depend on this.
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: mcp.plugin_view takes a coroutine function as well as a plain one. _pin awaits it, so
a view can wait on I/O without holding the event loop for every other request, /health
included.
Architecture: One private coroutine, Plugins._call_view, is the only place a view is called.
Both callers use it: _pin, for the request, and _quiet_pin, for the handshake's skill count
(#81). It calls fn() and awaits the result when it is awaitable. The memo and the state are still
taken after the view returns and before any await, so the _pin invariant holds. A synchronous
view is still called on the loop, never in a worker thread.
Tech Stack: Python 3.11+, FastMCP 4.2.x (fastmcp>=4.2,<5), anyio, pytest, ruff.
Spec: No separate design file. #86 is a Bug, and its notes are the debug agent's report, decided with Dr K on #86 (11:12 UTC: "Both."), so the report stands for the spec. This plan is the record. The contract is the PLUG-53 text Task 3 writes.
-
Why.
Plugins._pincalls the server's view synchronously. On mcp-kb the view's live re-read waited 1.5–1.8 s on a WebDAV PROPFIND, on the loop, every 21–413 s. Dr K's Pyroscope shows about 40–70 ms of CPU and no_makeframes, so the stall was waiting, not rebuilding. Every request in flight stalled with it, and the 1 s probes failed. -
The signature.
QuickMCP.plugin_viewandPlugins.set_viewtakeCallable[[], View | Awaitable[View]].plugin_viewis typed with a private TypeVar bound to that, so a decorated function keeps its own type. Adding a type a parameter accepts breaks no caller.Viewis unchanged. -
One call site.
Plugins._call_view() -> Viewcallsfn(), and ifinspect.isawaitable(result)it awaits it. So a coroutine function, anasync def __call__and afunctools.partialof one all work. With no view set it returns_EVERY, as today.-
_pinisview = await self._call_view(), thenawait self._pin_view(view). -
_quiet_pincalls it inside its existingtry, so a failing async view leaves the count out, as a failing sync view does. -
_pin_viewdoes not change: it takesself._memoandself._statewith no await between them and the view's return. A set the view serves, even after its own await, is the one the request reads (PLUG-53).
-
-
A view replaced while an async view awaits.
set_viewreplaces the memo, so no build of the old view is kept. An async view's await opens a window whereplugin_viewcan land from another task. If_pinkept the old view's result, that build would be stored in the new view's memo, under a key the new view may reuse. So_call_viewchecks after the await: ifself._viewis no longer thefnit called, it calls the new view in its place. The check runs only after an await, so a sync view's path is exactly today's. (This is the plan's own call, oneischeck. Dr K can drop it on review.) -
What does not move.
- A view that raises, sync or async, fails the request as PLUG-53 says since #90:
-32603"Internal server error", the original logged once, and anMCPErrorpassed through whole. - A view may serve (PLUG-51), and nothing else.
- Nested requests share the slot, and the view runs once per request.
-
A sync view stays on the loop. It is never sent to a worker thread, because a context
variable it sets (mcp-kb's
_PINNED) would be lost when the thread returns. PLUG-53 states the rule instead: a sync view must not block, and I/O goes in an async view. - The docstrings of
plugin_viewandset_viewsay the same.plugin_view's still says "fails the request with its error", which #90 overtook. It is fixed here.
- A view that raises, sync or async, fails the request as PLUG-53 says since #90:
-
Release. Minor, additive, within the epic's minor. One
### Addedline. No downstream deadline: mcp-kb#116 fixes its side with a background pass. Later servers should use the async form.
- No public name is added, renamed or removed.
plugin_view's parameter widens, and that is all. -
kubed/has no__init__.py. Do not add one. - Tests are pytest with no network.
tests/test_plugin_views.pyandtests/test_skill_cap.pyalready havepytestmark = pytest.mark.unit. - Checks, as CI runs them:
pytest(test.yml, Python 3.11 and 3.14 on a pull request, afterpip install .[test,tasks]) andruff check .(lint.yml). Run both on 3.11 if you can, since that is the floor. - The wiki (
docs/) is its own repository. Commit there on the wiki branchissue-86, push it, then commit thedocspointer here. Never push the wiki'smaster. - CHANGELOG: edit only
[Unreleased], with one short line and no version heading. - This repository is public: no names, emails or hostnames in a file or a commit message.
-
A
serve()after the async view's own await. That request reads the new set, and the memo it stores into is the new one. Pinned in Task 1 bytest_a_set_the_view_serves_is_what_its_request_reads[async]. Its wrapper awaits before calling the view's body, which serves. -
plugin_viewlanding while an async view awaits. The new view answers, and no build of the old view is stored. Pinned by Task 1'stest_a_view_set_while_an_async_view_awaits_answers_in_its_place. -
The handshake's skill count with an async view (
_quiet_pin, the second call site). The count is filled, and a raising async view leaves it out without failing the handshake. Pinned by Task 1'stest_an_async_view_is_countedand the async row oftest_a_failing_pin_leaves_the_count_out. -
An async view's failure on every era and over HTTP, logged once with its traceback. Pinned by
the two async rows Task 1 adds to
FAILING_VIEWS, which every existing failed-pin test already parametrises over. -
A context variable an async view sets. It is set in the task that awaited the pin, with no
thread or task between them, and in a request it behaves exactly as a sync view's does. Pinned
by Task 1's
test_a_context_variable_the_view_sets_is_kept_as_a_sync_views_is.
Files:
- Modify:
kubed/mcp/plugins.py:-
Plugins.__init__, theself._viewannotation (~L1771); -
Plugins.set_view(~L1873); -
Plugins._pin(~L1961–1968), and a newPlugins._call_viewbeside it; -
Plugins._quiet_pin(~L1995); - the imports (
inspect, andAwaitablefromcollections.abc).
-
- Modify:
kubed/mcp/app.py:QuickMCP.plugin_view(~L493–505), and a private TypeVar. - Test:
tests/test_plugin_views.py,tests/test_skill_cap.py
Interfaces:
-
Consumes:
served,DEMO,ENTRY,listed(tests/plugin_server.py);request(tests/skill_server.py);View(key, admits);Plugins.pinned() -> _Pin, with_Pin.view: View,_Pin.state.generation: int,_Pin.build.admitted: tuple[Plugin, ...];Plugins._memo.builds, anOrderedDictkeyed(generation, view key, prefix). In test_skill_cap:capped,seen_by,over_http,MODES,SkillCount. -
Produces:
Plugins.set_view(self, fn: Callable[[], View | Awaitable[View]]) -> None-
async Plugins._call_view(self) -> View, the only place a view is called -
QuickMCP.plugin_view(self, fn: _ViewFn) -> _ViewFn, where_ViewFn = TypeVar("_ViewFn", bound=Callable[[], View | Awaitable[View]])is private toapp.py - test helpers in
tests/test_plugin_views.py:awaited(fn)andKINDS, which Task 2 does not need
-
Step 1: Run the full suite first
Run: pytest
Expected: all pass. This is the branch's first run. Record any failure that exists before this
change, and do not fix it here.
- Step 2: Add the helpers to
tests/test_plugin_views.py
def awaited(fn):
"""``fn`` as a coroutine function that yields to the loop once, then answers."""
async def view():
await anyio.sleep(0)
return fn()
return view
KINDS = {"sync": lambda fn: fn, "async": awaited}Then give scopes(tmp_path, kind: str = "sync") and counting(mcp, kind: str = "sync") a kind
parameter. Each passes its view through KINDS[kind] before mcp.plugin_view. The defaults keep
every other caller as it is.
- Step 3: Parametrise the honoured-view tests over
KINDS
Add @pytest.mark.parametrize("kind", KINDS) and pass kind through, with no assertion changed:
-
test_each_scope_is_served_its_plugins:scopes(tmp_path, kind). The key and admits are honoured. -
test_the_view_runs_once_per_request:counting(mcp, kind). -
test_a_set_the_view_serves_is_what_its_request_reads:mcp.plugin_view(KINDS[kind](revalidate)). Underasync, the serve comes after an await (Review Focus 1). -
test_a_view_that_raises_an_mcp_error_sends_it_whole:mcp.plugin_view(KINDS[kind](refuses)). -
Step 4: Add the async failures to
FAILING_VIEWS
FAILING_VIEWS = {
"raises": lambda: 1 / 0,
"unhashable": lambda: View([], lambda plugin: True),
}
FAILING_VIEWS |= {f"{name}, async": awaited(fn) for name, fn in FAILING_VIEWS.items()}FAILURES is built from it, so test_a_failure_to_pin_fails_the_request, ..._over_http and
test_the_original_error_is_logged_once_with_its_traceback cover the async view on both eras and
over HTTP, with no other change (Review Focus 4).
- Step 5: Write the context-variable test
SEEN: ContextVar[str | None] = ContextVar("SEEN", default=None)
def marks() -> View:
SEEN.set("pinned")
return View(None, lambda plugin: True)
async def test_a_context_variable_the_view_sets_is_kept_as_a_sync_views_is():
# Review Focus 5
seen = {}
for kind, wrap in KINDS.items():
SEEN.set(None)
mcp = served((DEMO, None))
mcp.plugin_view(wrap(marks))
@mcp.tool
async def read_back(ctx: Context) -> str:
await ctx.read_resource(ENTRY)
return str(SEEN.get())
async with Client(mcp.server) as client:
seen[kind] = (await client.call_tool("read_back", {})).data
await mcp._plugins.pinned() # off a request, pinned in this very task
assert SEEN.get() == "pinned", kind # awaited here: no thread, no task between
assert seen["async"] == seen["sync"] # in a request, as a sync view'sImport ContextVar from contextvars.
- Step 6: Write the replaced-view test
async def test_a_view_set_while_an_async_view_awaits_answers_in_its_place():
# Review Focus 2
mcp = served((DEMO, None))
entered, release, pins = anyio.Event(), anyio.Event(), []
async def old() -> View:
entered.set()
await release.wait()
return View("old", lambda plugin: True)
async def pin() -> None:
pins.append(await mcp._plugins.pinned())
mcp.plugin_view(old)
async with anyio.create_task_group() as tg:
tg.start_soon(pin)
await entered.wait()
mcp.plugin_view(lambda: View("new", lambda plugin: False))
release.set()
assert pins[0].view.key == "new"
assert pins[0].build.admitted == ()
assert [key[1] for key in mcp._plugins._memo.builds] == ["new"]- Step 7: Write the skill-count tests in
tests/test_skill_cap.py
Beside _view_raises:
async def _view_raises_async() -> View:
await anyio.sleep(0)
raise RuntimeError("view down")Add (_view_raises_async, None) to the parameters of test_a_failing_pin_leaves_the_count_out.
The assertions stay as they are. Then add:
@pytest.mark.parametrize("mode", MODES)
async def test_an_async_view_is_counted(tmp_path, mode): # Review Focus 3
mcp = capped(tmp_path, ("a", 101))
async def every() -> View:
await anyio.sleep(0)
return View(None, lambda plugin: True)
mcp.plugin_view(every)
got = seen_by(mcp)
async with over_http(mcp, mode=mode):
pass
assert got[0].skills == SkillCount(100, 1)Import anyio if the module does not already.
- Step 8: Run the new tests and confirm they fail
Run: pytest tests/test_plugin_views.py tests/test_skill_cap.py -v
Expected: the async rows FAIL, and so do test_a_view_set_while_... and
test_an_async_view_is_counted. Today _pin_view gets a coroutine, view.key raises
AttributeError, and Python warns that the coroutine was never awaited. The four failed-pin
, async rows may already pass, because the request fails either way. The context-variable test
fails on its async pass. Every sync row PASSES.
- Step 9: Implement
Plugins._call_viewand use it in_pinand_quiet_pin
async def _call_view(self) -> View:
while True:
fn = self._view
if fn is None:
return _EVERY
view = fn()
if not inspect.isawaitable(view):
return view # a sync view: today's path exactly
view = await view
if self._view is fn:
return view
# plugin_view landed while it awaited: the new view answers (its memo is new)This body is in the plan because the re-call is the design (point 4). The docstring says: the one place a view is called; an awaitable result is awaited in the caller's task, never in a thread; a view replaced during that await is called in its place.
-
_pin:view = await self._call_view(), thenreturn await self._pin_view(view). Keep its docstring, and add that an async view's set is read after it returns, like a sync one's. -
_quiet_pin: replaceview = self._view() if self._view else _EVERYwithview = await self._call_view(). Leave the rest of thetryas it is. -
self._view: Callable[[], View | Awaitable[View]] | None = None. -
set_view(self, fn: Callable[[], View | Awaitable[View]]). Docstring: "Makesfnthe view, called once per request and awaited when it returns an awaitable (PLUG-53)." -
Step 10: Retype and reword
QuickMCP.plugin_viewinapp.py
Add _ViewFn = TypeVar("_ViewFn", bound=Callable[[], "View | Awaitable[View]"]) at module level,
and import Awaitable from collections.abc. The signature is plugin_view(self, fn: _ViewFn) -> _ViewFn. The docstring keeps its first paragraph's request and admits sentences, then says:
-
fnmay be a coroutine function; its result is awaited inside the request, and a set it serves withserve(), after any await, is the one that request reads; -
a synchronous
fnruns on the event loop and must not block: I/O goes in an async view; -
a
fn()that raises fails the request with-32603"Internal server error", and one that raises anMCPErrorfails it with that error. This replaces "fails the request with its error". -
Step 11: Run the tests and the checks
Run: pytest tests/test_plugin_views.py tests/test_skill_cap.py tests/test_rewriters.py -v
Expected: all PASS, with no "coroutine ... was never awaited" warning.
test_a_build_begun_before_a_change_is_never_stored and
test_a_serve_during_a_build_is_never_stored pass unedited.
Run: pytest, then ruff check .
Expected: all pass, and ruff reports no errors.
- Step 12: Commit
git add kubed/mcp/plugins.py kubed/mcp/app.py tests/test_plugin_views.py tests/test_skill_cap.py
git commit -m "feat(plugins): a plugin view may be async, awaited in its request"Files:
- Test:
tests/test_plugin_views.py
Interfaces:
-
Consumes: Task 1's async view.
asgi_server(fastmcp.utilities.tests, already imported),running.transport(headers=...),running.http_client()andrunning.app.url_path_for(name), as intests/test_app.py::test_a_custom_route_answers_over_http;request_values,request. -
Produces: no names.
-
Step 1: Write the regression test
async def test_a_slow_async_view_stalls_no_other_request(): # #86
mcp = served((DEMO, None))
armed, waiting, took = [False], anyio.Event(), {}
async def revalidates() -> View:
found = request_values()
slow = found and (found[1].get("x-slow") or [None])[0]
if armed[0] and slow:
waiting.set()
await anyio.to_thread.run_sync(time.sleep, 1) # a PROPFIND's wait
return View(None, lambda plugin: True)
mcp.plugin_view(revalidates)
@mcp.custom_route("/health", methods=["GET"], name="health")
async def health(request: Request) -> JSONResponse:
return JSONResponse({"status": "ok"})
async def timed(name, call) -> None:
# From the slow request's start: a stall that blocks the loop also keeps this
# task from starting its call, so a call's own duration would not show it.
took[name] = (await call(), time.monotonic() - began)
async with asgi_server(mcp.server) as running, running.http_client() as http:
path = str(running.app.url_path_for("health"))
async with (
Client(running.transport(headers={"x-slow": "1"})) as slow,
Client(running.transport()) as fast,
):
armed[0] = True # after both handshakes, so neither waits
began = time.monotonic()
async with anyio.create_task_group() as tg:
tg.start_soon(timed, "slow", lambda: request(slow, "skills/list"))
await waiting.wait() # the slow view is waiting now
tg.start_soon(timed, "health", lambda: http.get(path))
tg.start_soon(timed, "tools", fast.list_tools)
tg.start_soon(timed, "skills", lambda: request(fast, "skills/list"))
assert took["health"][0].status_code == 200
assert took["health"][1] < 0.6 # a plain ASGI route, as a probe
assert took["tools"][1] < 0.6 # a concurrent tools/list
assert took["skills"][1] < 0.6 # and a request that pins a view of its own
assert took["slow"][1] >= 1 # the slow view was awaited, not skippedImport time, and Request and JSONResponse from starlette.requests and
starlette.responses.
- Step 2: Prove the test sees a stall
Temporarily replace await anyio.to_thread.run_sync(time.sleep, 1) with time.sleep(1), which
blocks the loop as mcp-kb's PROPFIND did.
Run: pytest tests/test_plugin_views.py::test_a_slow_async_view_stalls_no_other_request -v
Expected: FAIL on a < 0.6 assertion (health first), with each fast call near 1 s from
began. If it passes, the test cannot see the server's loop, and the setup must change until it
can. Then restore the to_thread line.
- Step 3: Run it as written
Run: pytest tests/test_plugin_views.py::test_a_slow_async_view_stalls_no_other_request -v
Expected: PASS, in a little over 1 s.
Run: pytest, then ruff check .
Expected: all pass, and ruff reports no errors.
- Step 4: Commit
git add tests/test_plugin_views.py
git commit -m "test(plugins): a slow async view stalls neither a route nor another request"Files:
- Modify:
docs/superpowers/specs/plugins.md: PLUG-53 (L406–416), in the wiki submodule - Modify:
CHANGELOG.md:[Unreleased]
Interfaces:
-
Consumes: Tasks 1 and 2's behaviour.
-
Produces: no names.
-
Step 1: Add PLUG-53's sentences
After "A request with no HTTP request, on stdio, calls fn() the same way, and request_values()
answers there as FAC-9 says.", add exactly:
"fn may be a coroutine function, or any callable whose result is awaitable: the result is awaited
inside the request, in the task of the read that pins it, never in a worker thread, so a context
variable fn() sets is seen there after the pin. A synchronous fn runs on the event loop and must
not block: I/O goes in an async view. If mcp.plugin_view sets another view while an async fn()
awaits, the new view is called in its place."
In the existing sentence "A set fn() serves (PLUG-51) is the one the request reads: the set is
read after fn() returns.", change "after fn() returns" to "after fn() returns, or its result
is awaited". Leave the rest of PLUG-53 and PLUG-51 as they are.
- Step 2: Add the changelog line
Under ## [Unreleased] → ### Added, after the skills-cap line, add exactly:
- A plugin view may be async, so it can wait on I/O without holding the event loop.
- Step 3: Check
Run: git -C docs diff and git diff CHANGELOG.md
Expected: only PLUG-53 changes in the spec. [Unreleased] → ### Added gains one line, and no
version heading was added.
- Step 4: Commit the wiki, then the pointer and the changelog
git -C docs switch issue-86 2>/dev/null || git -C docs switch -c issue-86
git -C docs add superpowers/specs/plugins.md
git -C docs commit -m "PLUG-53: a plugin view may be async, and a sync one must not block"
git -C docs push -u origin issue-86
git add docs CHANGELOG.md
git commit -m "docs: PLUG-53 and the changelog for an async plugin view"These pages describe what is on main; the spec says what is built and what is only proposed.
kubed-mcp · MIT