Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 45 additions & 11 deletions src/basic_memory/cli/commands/hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,25 +576,59 @@ def _capture_envelope(
# --- Structured queries for the session brief ---


async def _query(project_ref: str | None, **search: Any) -> dict[str, Any] | None:
"""One best-effort structured bm_search; any failure reads as 'no data'."""
# Deferred: importing basic_memory.mcp.tools loads the whole tool stack (#886).
from basic_memory.mcp.tools import bm_search
async def _search_notes(
*,
project: str,
note_types: list[str],
filters: dict[str, Any] | None = None,
since: str | None = None,
) -> dict[str, Any]:
"""Search one project's notes by frontmatter, as bm_search does for these arguments.

The brief calls the project search API through its typed client instead of the
bm_search tool. Importing basic_memory.mcp.tools loads every tool, FastMCP's server
and the MCP server just to run a few filtered searches. Without cached bytecode that
import alone took about 9 s of a SessionStart that ran over its timeout (#2101).
"""
# Deferred: the CLI imports this module for every command, and these pull in the
# routing and search client stack (#886).
from basic_memory.mcp.clients.search import SearchClient
from basic_memory.mcp.project_context import get_project_client
from basic_memory.mcp.tool_params import parse_project, routing_arguments
from basic_memory.schemas.base import validate_timeframe
from basic_memory.schemas.search import SearchItemType, SearchQuery

project_name, project_id = routing_arguments(parse_project(project))
search_query = SearchQuery(
note_types=note_types,
metadata_filters=filters,
after_date=validate_timeframe(since) if since else None,
# Note rows only, as bm_search defaults: observations and relations would
# otherwise fill the five slots with fragments of the same notes.
entity_types=[SearchItemType.ENTITY],
)
async with get_project_client(project_name, None, project_id=project_id) as (
client,
active_project,
):
response = await SearchClient(client, active_project.external_id).search(
search_query.model_dump(), page=1, page_size=5
)
return response.model_dump(mode="json", exclude_none=True)


# bm_search takes a project name or id; an unmapped directory reads the default.
async def _query(project_ref: str | None, **search: Any) -> dict[str, Any] | None:
"""One best-effort structured search; any failure reads as 'no data'."""
# A project name or id; an unmapped directory reads the default project.
project = project_ref or ConfigManager().config.default_project
if project is None:
return None
try:
result = await asyncio.wait_for(
bm_search(page_size=5, output_format="json", project=project, context=None, **search),
timeout=QUERY_TIMEOUT_SECONDS,
return await asyncio.wait_for(
_search_notes(project=project, **search), timeout=QUERY_TIMEOUT_SECONDS
)
except Exception:
return None
if not isinstance(result, dict):
return None
return result


@dataclass
Expand Down
File renamed without changes.
6 changes: 3 additions & 3 deletions src/basic_memory/mcp/clients/directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
DirectorySortOrder,
)

# call_* helpers live in basic_memory.mcp.tools.utils; importing that at module
# level executes the whole tools package (fastmcp + mcp SDK) during CLI startup,
# call_* helpers live in basic_memory.mcp.api_calls; importing that at module
# level loads fastmcp.exceptions and the mcp SDK during CLI startup,
# so each method defers the import to call time instead (#886).


Expand Down Expand Up @@ -69,7 +69,7 @@ async def list(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

params: dict[str, Any] = {
"dir_name": dir_name,
Expand Down
4 changes: 2 additions & 2 deletions src/basic_memory/mcp/clients/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self, http_client: AsyncClient, project_id: str):

async def inspect_chunks(self, identifier: str) -> InspectChunksResponse:
"""Inspect one note's search rows and vector chunk manifest."""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

request = InspectChunksRequest(identifier=identifier)
with debug_span(
Expand All @@ -47,7 +47,7 @@ async def inspect_query(
offset: int,
) -> InspectQueryResponse:
"""Run one search and return its execution-native retrieval trace."""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

request = InspectQueryRequest(query=query, limit=limit, offset=offset)
with debug_span(
Expand Down
32 changes: 16 additions & 16 deletions src/basic_memory/mcp/clients/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

from basic_memory.telemetry import debug_span

# call_* helpers live in basic_memory.mcp.tools.utils; importing that at module
# level executes the whole tools package (fastmcp + mcp SDK) during CLI startup,
# call_* helpers live in basic_memory.mcp.api_calls; importing that at module
# level loads fastmcp.exceptions and the mcp SDK during CLI startup,
# so each method defers the import to call time instead (#886).
from basic_memory.runtime.note_content_responses import NOTE_CONTENT_BASE_CHECKSUM_HEADER
from basic_memory.schemas.response import (
Expand Down Expand Up @@ -74,7 +74,7 @@ async def write_note(
expected_checksum: str | None = None,
) -> WriteNoteResponse:
"""Write at an exact path and preserve the service's expected outcomes."""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

with debug_span(
"mcp.client.knowledge.write_note",
Expand Down Expand Up @@ -111,7 +111,7 @@ async def create_entity(self, entity_data: dict[str, Any]) -> EntityResponseV2:
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

with debug_span(
"mcp.client.knowledge.create_entity",
Expand Down Expand Up @@ -146,7 +146,7 @@ async def update_entity(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_put
from basic_memory.mcp.api_calls import call_put

with debug_span(
"mcp.client.knowledge.update_entity",
Expand Down Expand Up @@ -188,7 +188,7 @@ async def get_entity(
ToolError: If the entity or requested section is not found or the
request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

params: dict[str, str | int] = {}
if section is not None:
Expand Down Expand Up @@ -218,7 +218,7 @@ async def get_accepted_note_contents(
entity_ids: list[str],
) -> AcceptedNoteContentBatchResponse:
"""Get accepted Markdown for one bounded note batch."""
from basic_memory.mcp.tools.utils import call_query
from basic_memory.mcp.api_calls import call_query

with debug_span(
"mcp.client.knowledge.get_accepted_note_contents",
Expand Down Expand Up @@ -272,7 +272,7 @@ async def patch_entity(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_patch
from basic_memory.mcp.api_calls import call_patch

with debug_span(
"mcp.client.knowledge.patch_entity",
Expand Down Expand Up @@ -306,7 +306,7 @@ async def delete_entity(
Raises:
ToolError: If the entity is not found or request fails
"""
from basic_memory.mcp.tools.utils import call_delete
from basic_memory.mcp.api_calls import call_delete

with debug_span(
"mcp.client.knowledge.delete_entity",
Expand Down Expand Up @@ -341,7 +341,7 @@ async def move_entity(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_put
from basic_memory.mcp.api_calls import call_put

with debug_span(
"mcp.client.knowledge.move_entity",
Expand Down Expand Up @@ -374,7 +374,7 @@ async def move_directory(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

with debug_span(
"mcp.client.knowledge.move_directory",
Expand Down Expand Up @@ -406,7 +406,7 @@ async def delete_directory(self, directory: str) -> DirectoryDeleteResult:
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

with debug_span(
"mcp.client.knowledge.delete_directory",
Expand Down Expand Up @@ -437,7 +437,7 @@ async def index_file(self, file_path: str) -> EntityResponse:
Raises:
ToolError: If the file does not exist on disk or indexing fails
"""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

with debug_span(
"mcp.client.knowledge.index_file",
Expand All @@ -458,7 +458,7 @@ async def index_file(self, file_path: str) -> EntityResponse:

async def get_orphans(self) -> list[GraphNode]:
"""Get entities that have no incoming or outgoing relations."""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

with debug_span(
"mcp.client.knowledge.get_orphans",
Expand All @@ -483,7 +483,7 @@ async def _resolve_entity_data(
strict: bool = False,
) -> dict[str, Any]:
"""Request the complete entity-resolution payload."""
from basic_memory.mcp.tools.utils import call_query
from basic_memory.mcp.api_calls import call_query

with debug_span(
"mcp.client.knowledge.resolve_entity",
Expand Down Expand Up @@ -535,7 +535,7 @@ async def resolve_link(
"""
from fastmcp.exceptions import ToolError

from basic_memory.mcp.tools.utils import call_query
from basic_memory.mcp.api_calls import call_query

try:
response = await call_query(
Expand Down
8 changes: 4 additions & 4 deletions src/basic_memory/mcp/clients/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
from httpx import AsyncClient


# call_* helpers live in basic_memory.mcp.tools.utils; importing that at module
# level executes the whole tools package (fastmcp + mcp SDK) during CLI startup,
# call_* helpers live in basic_memory.mcp.api_calls; importing that at module
# level loads fastmcp.exceptions and the mcp SDK during CLI startup,
# so each method defers the import to call time instead (#886).
from basic_memory.schemas.memory import (
DEFAULT_CONTEXT_PAGE_SIZE,
Expand Down Expand Up @@ -73,7 +73,7 @@ async def build_context(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

params: dict[str, Any] = {
"depth": depth,
Expand Down Expand Up @@ -126,7 +126,7 @@ async def recent(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

params: dict[str, Any] = {
"timeframe": timeframe,
Expand Down
24 changes: 12 additions & 12 deletions src/basic_memory/mcp/clients/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

from httpx import AsyncClient

# call_* helpers live in basic_memory.mcp.tools.utils; importing that at module
# level executes the whole tools package (fastmcp + mcp SDK) during CLI startup,
# call_* helpers live in basic_memory.mcp.api_calls; importing that at module
# level loads fastmcp.exceptions and the mcp SDK during CLI startup,
# so each method defers the import to call time instead (#886).
from basic_memory.schemas import ProjectIndexStatusResponse, ProjectInfoResponse
from basic_memory.schemas.project_info import ProjectList, ProjectStatusResponse
Expand Down Expand Up @@ -50,7 +50,7 @@ async def list_projects(self) -> ProjectList:
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

response = await call_get(
self.http_client,
Expand All @@ -70,7 +70,7 @@ async def create_project(self, project_data: dict[str, Any]) -> ProjectStatusRes
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

response = await call_post(
self.http_client,
Expand All @@ -94,7 +94,7 @@ async def delete_project(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_delete
from basic_memory.mcp.api_calls import call_delete

url = f"/v2/projects/{project_external_id}"
if delete_notes:
Expand All @@ -117,7 +117,7 @@ async def resolve_project(self, identifier: str) -> ProjectResolveResponse:
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_query
from basic_memory.mcp.api_calls import call_query

response = await call_query(
self.http_client,
Expand All @@ -138,7 +138,7 @@ async def set_default(self, project_external_id: str) -> ProjectStatusResponse:
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_put
from basic_memory.mcp.api_calls import call_put

response = await call_put(
self.http_client,
Expand All @@ -161,7 +161,7 @@ async def update_project(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_patch
from basic_memory.mcp.api_calls import call_patch

response = await call_patch(
self.http_client,
Expand Down Expand Up @@ -190,7 +190,7 @@ async def index(
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_post
from basic_memory.mcp.api_calls import call_post

url = f"/v2/projects/{project_external_id}/index"
params = []
Expand All @@ -215,7 +215,7 @@ async def get_status(self, project_external_id: str) -> ProjectIndexStatusRespon
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

response = await call_get(
self.http_client,
Expand All @@ -225,7 +225,7 @@ async def get_status(self, project_external_id: str) -> ProjectIndexStatusRespon

async def get_doctor_report(self, project_external_id: str) -> ProjectDoctorReport:
"""Report a project's problems and their repairs without changing the project."""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

response = await call_get(self.http_client, f"/v2/projects/{project_external_id}/doctor")
return ProjectDoctorReport.model_validate(response.json())
Expand All @@ -242,7 +242,7 @@ async def get_info(self, project_external_id: str) -> ProjectInfoResponse:
Raises:
ToolError: If the request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

response = await call_get(
self.http_client,
Expand Down
6 changes: 3 additions & 3 deletions src/basic_memory/mcp/clients/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from httpx import AsyncClient, Response

from basic_memory.telemetry import debug_span
# call_* helpers live in basic_memory.mcp.tools.utils; importing that at module
# level executes the whole tools package (fastmcp + mcp SDK) during CLI startup,
# call_* helpers live in basic_memory.mcp.api_calls; importing that at module
# level loads fastmcp.exceptions and the mcp SDK during CLI startup,
# so each method defers the import to call time instead (#886).


Expand Down Expand Up @@ -51,7 +51,7 @@ async def read(self, entity_id: str) -> Response:
Raises:
ToolError: If the resource is not found or request fails
"""
from basic_memory.mcp.tools.utils import call_get
from basic_memory.mcp.api_calls import call_get

with debug_span(
"mcp.client.resource.read",
Expand Down
Loading
Loading