Skip to content

fix: defer local API app imports during MCP startup - #1740

Closed
mvanhorn wants to merge 1 commit into
basicmachines-co:mainfrom
mvanhorn:fix/1731-mcp-lazy-api-import
Closed

mvanhorn wants to merge 1 commit into
basicmachines-co:mainfrom
mvanhorn:fix/1731-mcp-lazy-api-import

Conversation

@mvanhorn

Copy link
Copy Markdown

Why

MCP startup loads the local API and its routers even when all tool calls will go to cloud. That unnecessary work delays readiness and can contribute to connection timeouts when several clients start servers together. Importing basic_memory.api.container first initializes the basic_memory.api package, which eagerly imported the FastAPI app. This pulled the app and its routers into the MCP startup import chain.

What changed

The package now loads and caches the FastAPI instance when its app export is requested. It also preserves that export when the app submodule is imported first, so callers receive the instance in either import order. New subprocess tests cover container and MCP startup imports in local and cloud modes, plus explicit app imports and repeated access.

Verification

  • Ran just test locally; it hit its time limit before finishing.
  • The python_tests check found no applicable tests and ran none.
  • The just test run showed passing tests but timed out before completing, so it does not establish a full-suite pass.

Closes #1731

AI was used for assistance.

The package now loads and caches the FastAPI instance when its app
export is requested. It also preserves that export when the app
submodule is imported first, so callers receive the instance in either
import order. New subprocess tests cover container and MCP startup
imports in local and cloud modes, plus explicit app imports and repeated
access.

Fixes basicmachines-co#1731

Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T06:44:37.620950Z 6c695ac PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6c695acd88

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

from basic_memory.api.container import ApiContainer
assert importlib.import_module('basic_memory.api.app').app is app
""")
result = subprocess.run(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Collect coverage from the fresh interpreter tests

The only assertions that execute the new __getattr__ body run in this child interpreter; the normal test process has already imported basic_memory.api.app from tests/mcp/conftest.py:13, so it exercises only _ApiModule.__setattr__. This repository locks pytest-cov 7.1, while [tool.coverage.run] does not enable subprocess patching, so this child's data is not merged and src/basic_memory/api/__init__.py:14-22 remains uncovered. Collect/combine subprocess coverage (or exercise this path in-process) so the new code preserves the required 100% coverage.

AGENTS.md reference: AGENTS.md:L306-L306

Useful? React with 👍 / 👎.

@phernandez

Copy link
Copy Markdown
Member

Thanks @mvanhorn. The diagnosis in #1731 is spot on, and the startup-import tests are a nice extension of the existing bm --help check.

We're going to decline this one, though. We'd rather not take on module-level __getattr__ plus a module __class__ swap to defer this import. Python 3.15's explicit lazy imports (PEP 810) solve it at the import statement, so we plan to fix #1731 that way once we support 3.15. I'll leave #1731 open to track it.

Thanks again for digging into this and measuring it so carefully.

@phernandez phernandez closed this Oct 11, 2026
groksrc added a commit that referenced this pull request Oct 29, 2026
…1966)

This PR makes the OpenClaw plugin work on OpenClaw 2026.10 and later. On
those hosts, conversation capture never ran (#1880), the plugin's memory
search never ran, and OpenClaw's memory features read only workspace
files. All fixes were tested together against a live OpenClaw 2026.10.9
gateway.

This PR now also contains the work from #1968, which is closed so that
one branch carries everything.

## Commits

| Commit | What it fixes |
|---|---|
| `e49f7255` | **Capture (#1880).** OpenClaw 2026.10 rejected the
context engine on every turn, so nothing was captured. |
| `16a30828` | `context-engine/types.ts` was missing from the npm
`files` list. |
| `1e29bb0d` | Heartbeat polls and `NO_REPLY` turns were captured as
conversation. |
| `2f554e17` | **Memory provider.** The plugin's
`memory_search`/`memory_get` never ran, and OpenClaw's memory features
fell back to its file index. Search scores displayed as "118%". |
| `60c153d8` | `openclaw memory status` printed "Health: ready" and then
never exited. |
| `a32aa118` | `write_note`/`edit_note` told agents to cite `file_path`,
but the result text did not include it. |
| `61a1d305` | `edit_note` hid every server error behind "It may not
exist", and offered no way to add to a section. |
| `ccccfbbe` | A first start overran OpenClaw's 5 s service limit and
could wedge the gateway; a missing workspace directory broke a fresh
install; search previews cut off long notes; `build_context` repeated
observations and printed `null` for unresolved links; every other tool
hid server errors. |

## 1. Capture (#1880)

OpenClaw 2026.10 runs a context engine for durable turns only if the
engine meets two requirements. It must declare
`info.transcriptSemantics` (`currentTurnFence:
"before-current-turn-entry-v1"`, `turnAdvancementIdempotency:
"atomic-idempotent-v1"`). It must also implement `commitTurn()`, an
atomic write keyed by `advancementKey` that is safe to repeat. Our
engine did neither. OpenClaw logged `Context engine
"openclaw-basic-memory" degraded to "legacy" ... current-turn transcript
fencing is not declared` and captured nothing.

- **Declarations.** The engine declares both values. The fence holds
because `assemble()` passes the host's messages through unchanged and
the engine stores no transcript.
- **`commitTurn()`.** It captures the turn keyed by `advancementKey`.
- Each entry carries a hidden `<!-- openclaw-turn:<sha256 prefix> -->`
marker.
- A key already present in today's or yesterday's conversation note
returns `duplicate`.
- Captures run one at a time, so a duplicate check and its append cannot
interleave.
  - Errors propagate, so OpenClaw keeps the turn queued and retries it.
- **Fallback.** `afterTurn()` stays for older hosts. OpenClaw skips
`afterTurn()` for turns it sends to `commitTurn()`.
- **Housekeeping turns.** Both paths skip heartbeat turns
(`isHeartbeat`) and replies that are exactly `NO_REPLY`.
- **Build.** The plugin builds against `openclaw ^2026.10.6`. 2026.10
removed the bare `openclaw/plugin-sdk` export, so `ContextEngine` types
now come from `OpenClawPluginApi.registerContextEngine`.

## 2. Memory provider

The plugin registered `memory_search` and `memory_get` as plain tools.
OpenClaw's bundled Memory Core plugin registers the same names even when
another plugin owns the memory slot, so OpenClaw rejected ours (`plugin
tool name conflict`). The plugin also never called
`registerMemoryCapability`, OpenClaw's "exclusive memory-plugin API".

`memory/basic-memory-capability.ts` now registers a capability:

- **`providerRuntime`** with `search`, `get`, `health` and `close` over
the shared BM client. Gateway `memory.search` v2, `memory.get`,
`memory.status` and doctor now read Basic Memory.
  - Fused scores (0–1.3) are capped at 1 for the host's 0–1 `minScore`.
  - A missing note returns `not_found`; any other failure propagates.
- Every BM call is wrapped in `context.assertCurrent()`, so a revoked
caller is refused.
- A reader opened outside the plugin service, as in a one-shot CLI
command, stops its own `bm mcp` connection on `close()`.
- **`recallToolNames`**: `search_notes`, `read_note` and
`build_context`, for Active Memory.
- **`providerFlushPlanResolver`**: the pre-compaction flush saves
through `write_note`/`edit_note` instead of a workspace file.
- **`promptBuilder`**: a short system-prompt section that points agents
at `search_notes`. Otherwise OpenClaw fills this field from Memory Core,
which points agents at its file-only `memory_search`.

The dead `tools/memory-provider.ts` is removed, and its tools are
dropped from `openclaw.plugin.json`.

**Design decision.** Memory Core's `memory_search` cannot be routed to
Basic Memory: it always opens Memory Core's own index (`backend:
"builtin"`). This PR keeps Memory Core loaded and steers agents to
`search_notes` through the prompt section and the `search_notes`
description. The alternatives were to disable Memory Core, which also
loses its file memory and its background memory-consolidation feature
("dreaming"), or to re-add the combined search under a new tool name.

## 3. Smaller fixes

- **Scores.** Search results show `(score 1.18)` instead of "118%" in
`search_notes`, `/recall` and the CLI. Basic Memory's fused scores reach
1.3 by design (`search_reader.py:349`).
- **File paths.** `write_note` and `edit_note` results now include a
`File:` line, matching their descriptions.
- **`edit_note` errors.** Failures show the server's reason, such as
`INVALID_ARGUMENTS: \`section\` is only for section commands, not
append.`, instead of "It may not exist".
- **`edit_note` section inserts.** `insert_after_section` and
`insert_before_section` are exposed. Agents can add an observation under
`## Observations`; `append` always lands after `## Relations`.
- **README.** The install steps set both slots with `openclaw config
set`, because 2026.10.9 has no `plugins enable --slot`. They also state
that capture and recall require the `contextEngine` slot.

## 4. Startup and tool output

- **Background startup.** Service start no longer waits for `bm`.
- `BmClient.start()` runs connect plus project creation as a startup
gate. Tool calls wait for the gate, and a failed startup is retried by
the next tool call.
  - Schema seeding runs after the gate opens.
  - The `bm --version` probe and the `uv` auto-install are async.
- Measured: the first note write takes 4–9 s and a first start about 12
s, against OpenClaw's 5 s limit. A timed-out start failed the plugin,
and the failed hot reload left the gateway unable to list models.
- **Workspace directory.** The service creates the workspace before
spawning `bm`. On a fresh install, OpenClaw creates it only on the first
agent run, and spawning into it failed with `ENOENT ... posix_spawn
'bm'`.
- **Search previews** use the server's `matched_chunk`, up to 500
characters, in `search_notes`, the CLI and the memory provider. Before,
a fact deep in a day's conversation note was matched but cut off.
- **`build_context`** lists only observations missing from the shown
note body. It shows an unresolved `[[link]]` by its name, with "(no note
yet)", instead of `null`.
- **Errors.** Every tool's catch-all now shows the server's reason
(`describeToolError`/`describeNoteError`). It says "does not exist" only
when the server reported `NOT_FOUND`.

## How it was verified

**Automated.** `just package-check-openclaw` exits 0 with 278 Bun tests
passing. It covers type check, Biome lint, build and the `npm pack` dry
run.

**Live, on OpenClaw 2026.10.9 (macOS VM).** I installed packed tarballs
of this code with both slots set. Basic Memory ran from this branch with
an isolated config.

| Check | Result |
|---|---|
| Tool-free turn, then check for "degraded to legacy" | No warning after
the fix. The only one is from the pre-fix reproduction. |
| Turn captured automatically | 16 turns recorded, each with its own
marker |
| Restart, then check for duplicates | 4 turns across 4 sessions and 1
restart gave 4 entries with 4 distinct markers |
| `openclaw gateway call memory.status` | `{"providerId":
"openclaw-basic-memory", "status": "ready"}` |
| `memory.search` v2 / `memory.get` | Basic Memory hits. A line window
returned `nextFrom`; an unknown id returned `not_found`. |
| `openclaw memory status --agent main` | Exits 0 in about 13 s with
`Health: ready` and no leftover `bm mcp` process |
| Tool-name conflicts after restart | None |
| Agent read/write loop | An OpenClaw agent ran `write_note`,
`edit_note`, `search_notes`, `build_context`, `read_note` and
`delete_note`; each worked on the first try |
| Heartbeat skip | The 16:00 CDT heartbeat turn ran (`trigger=heartbeat`
in the gateway log) and was not recorded. The 15:00 heartbeat, before
the fix, had been. |
| Hot install, brand-new project | "Plugin replacement applied" 0.09 s
after start, instead of a timeout. Connect and schema seeding finished
in the background 2.5 s later. |
| Search preview | `search_notes` "test plant fern" previewed the
matching turn instead of the note's opening |
| `build_context` | The observation is listed once. A link to a missing
note shows `relates_to → **No Such Note Zebra** (no note yet)`. |
| Missing note | `read_note` returned `it does not exist. NOT_FOUND: No
note matches ...` |
| `edit_note` errors and inserts | Append with `section` returned the
`INVALID_ARGUMENTS` reason; `insert_after_section` "Observations" placed
the line directly under that heading |

## Not verified

- **Missing workspace directory:** covered by a unit test that starts
the service with a nonexistent workspace. The VM's workspace already
exists, so this was not reproduced live after the fix.
- **Pre-compaction flush and Active Memory recall:** not exercised live.
The flush plan shape is unit-tested.
- **OpenClaw before 2026.10:** not run. The `afterTurn()` fallback is
unchanged, so the peer range stays `>=2026.5.2`.
- **Automatic recall on CLI runtimes such as `claude-cli`:** these never
call `assemble()`, so recall text is not injected. That is host
behaviour.
- **Access policy:** every OpenClaw caller with memory access can read
every note in the project, the same access `search_notes` already gives.

## Not fixed here: `openclaw memory status` takes 11–13 s

Timestamped output shows where the time goes:

| Stage | Time | Owner |
|---|---|---|
| CLI start until plugins register | 0 → 5.3 s | OpenClaw |
| Second plugin load pass | 5.3 → 8.7 s | OpenClaw |
| `bm mcp` connect | 8.7 → 10.6 s | Basic Memory: #1731, eager FastAPI
import at MCP startup |
| Health call and close | 10.6 → 11.5 s | plugin |

Loading the plugin module takes about 0.2–0.3 s per pass. No plugin
change would make a real difference. The `bm` share is tracked in #1731,
which is waiting on Python 3.15 lazy imports (#1740 was declined).

## Next step

A maintainer reviews and merges.

Closes #1880

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Drew Cain <groksrc@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bm mcp startup imports the full local FastAPI app (api/__init__.py), ~60% of MCP import time; concurrent starts exceed client connect timeouts

3 participants