From d100dd0389a732b5761419fdf19869f147abf994 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 08:06:03 -0500 Subject: [PATCH 01/17] feat(mcp): add bm_project and bm_schema, the grouped 1.0 tools bm_project(command=list|create|recent): - Delegates to list_memory_projects (already grouped by workspace), create_memory_project and recent_activity, with the shared parameter types (`since`, `items`, paging, `project`). - `delete` is opt-in: the tool is registered twice under one name, a `core` version and a `with-delete` version. The composition root shows one from the new enable_project_delete setting (off by default), so tools/list never varies per connection and the destructive annotation is true only when delete exists. - A constrained session refuses create/delete as UNSUPPORTED instead of the old success payload describing the failure. bm_schema(command=validate|infer|diff): - Calls SchemaClient directly; "no schemas", "no notes of this type", "no schema for this type" and "nothing above the threshold" are NOT_FOUND refusals that point to the next bm_* call (C11). - The report formatters move to mcp/schema_reports.py, shared with the legacy schema tools, whose output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/config_models.py | 9 + src/basic_memory/mcp/schema_reports.py | 150 ++++++++++++ src/basic_memory/mcp/server.py | 21 ++ src/basic_memory/mcp/tools/__init__.py | 6 + src/basic_memory/mcp/tools/note_schemas.py | 185 +++++++++++++++ src/basic_memory/mcp/tools/projects.py | 251 +++++++++++++++++++++ src/basic_memory/mcp/tools/schema.py | 162 +------------ tests/mcp/test_tool_bm_project.py | 227 +++++++++++++++++++ tests/mcp/test_tool_contracts.py | 42 ++++ tests/test_man_pages.py | 2 + 10 files changed, 903 insertions(+), 152 deletions(-) create mode 100644 src/basic_memory/mcp/schema_reports.py create mode 100644 src/basic_memory/mcp/tools/note_schemas.py create mode 100644 src/basic_memory/mcp/tools/projects.py create mode 100644 tests/mcp/test_tool_bm_project.py diff --git a/src/basic_memory/config_models.py b/src/basic_memory/config_models.py index b7f8e7ed9..9586d5c0e 100644 --- a/src/basic_memory/config_models.py +++ b/src/basic_memory/config_models.py @@ -607,6 +607,15 @@ def __init__(self, **data: Any) -> None: ... ), ) + enable_project_delete: bool = Field( + default=False, + description=( + "Offer bm_project(command='delete') to MCP clients. Off by default, so an " + "assistant cannot remove a project unless you turn this on. " + "Env: BASIC_MEMORY_ENABLE_PROJECT_DELETE" + ), + ) + cli_output_style: Literal["rich", "plain"] = Field( default="rich", description=( diff --git a/src/basic_memory/mcp/schema_reports.py b/src/basic_memory/mcp/schema_reports.py new file mode 100644 index 000000000..5fcc3569b --- /dev/null +++ b/src/basic_memory/mcp/schema_reports.py @@ -0,0 +1,150 @@ +"""Markdown renderings of schema reports, shared by the schema tools (#1832).""" + +from basic_memory.schemas.schema import DriftReport, InferenceReport, ValidationReport + + +def format_validation_report(report: ValidationReport) -> str: + """Render a ValidationReport as readable markdown. + + Produces output the LLM can display directly instead of trying to + interpret raw JSON, which leads to "undefined — invalid" rendering. + """ + lines: list[str] = [] + + # --- Header --- + type_label = report.note_type or "all" + lines.append(f"# Schema Validation: {type_label}") + lines.append("") + lines.append( + f"Notes: {report.total_notes} | Valid: {report.valid_count} " + f"| Warnings: {report.warning_count} | Errors: {report.error_count}" + ) + lines.append("") + + # --- Per-type breakdown (all-types mode) --- + if report.type_summaries: + lines.append("## By Type") + lines.append("") + for summary in report.type_summaries: + if summary.total_entities == 0: + lines.append(f"- **{summary.note_type}**: no notes") + else: + lines.append( + f"- **{summary.note_type}**: {summary.valid_count}/{summary.total_notes} valid" + ) + lines.append("") + + # --- Per-note results --- + for r in report.results: + status = "valid" if r.passed else "INVALID" + lines.append(f"- **{r.note_identifier}** — {status}") + for w in r.warnings: + lines.append(f" - warning: {w}") + for e in r.errors: + lines.append(f" - error: {e}") + + return "\n".join(lines) + + +def format_inference_report(report: InferenceReport) -> str: + """Render an InferenceReport as readable markdown. + + Without this formatter the LLM receives raw JSON and renders + field names as "undefined". + """ + lines: list[str] = [] + + # --- Header --- + lines.append(f"# Schema Inference: {report.note_type}") + lines.append("") + lines.append(f"Notes analyzed: {report.notes_analyzed}") + lines.append("") + + # --- Suggested schema YAML --- + if report.suggested_schema: + lines.append("## Suggested Schema") + lines.append("") + lines.append("```yaml") + lines.append("---") + lines.append(f"title: {report.note_type.title()}") + lines.append("type: schema") + lines.append(f"entity: {report.note_type}") + lines.append("version: 1") + lines.append("schema:") + for field_name, field_def in report.suggested_schema.items(): + lines.append(f" {field_name}: {field_def}") + lines.append("---") + lines.append("```") + lines.append("") + + # --- Field frequency table --- + if report.field_frequencies: + lines.append("## Field Frequencies") + lines.append("") + for f in report.field_frequencies: + pct = f"{f.percentage:.0%}" + req_marker = "required" if f.name in report.suggested_required else "optional" + samples = ", ".join(f.sample_values[:3]) if f.sample_values else "" + sample_str = f" (e.g. {samples})" if samples else "" + lines.append( + f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total}) " + f"[{req_marker}]{sample_str}" + ) + lines.append("") + + # --- Excluded fields --- + if report.excluded: + lines.append("## Excluded (below threshold)") + lines.append("") + for name in report.excluded: + lines.append(f"- {name}") + lines.append("") + + return "\n".join(lines) + + +def format_drift_report(report: DriftReport) -> str: + """Render a DriftReport as readable markdown. + + Without this formatter the LLM receives raw JSON and renders + field names as "undefined". + """ + lines: list[str] = [] + + # --- Header --- + lines.append(f"# Schema Drift: {report.note_type}") + lines.append("") + + has_drift = report.new_fields or report.dropped_fields or report.cardinality_changes + + if not has_drift: + lines.append("No drift detected — schema matches actual usage.") + return "\n".join(lines) + + # --- New fields --- + if report.new_fields: + lines.append("## New Fields (in notes but not in schema)") + lines.append("") + for f in report.new_fields: + pct = f"{f.percentage:.0%}" + lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") + lines.append("") + + # --- Dropped fields --- + if report.dropped_fields: + lines.append("## Dropped Fields (in schema but rare in notes)") + lines.append("") + for f in report.dropped_fields: + pct = f"{f.percentage:.0%}" + lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") + lines.append("") + + # --- Cardinality changes --- + if report.cardinality_changes: + lines.append("## Cardinality Changes") + lines.append("") + for change in report.cardinality_changes: + lines.append(f"- {change}") + lines.append("") + + return "\n".join(lines) diff --git a/src/basic_memory/mcp/server.py b/src/basic_memory/mcp/server.py index 8521d0db7..c6927e351 100644 --- a/src/basic_memory/mcp/server.py +++ b/src/basic_memory/mcp/server.py @@ -31,6 +31,23 @@ POSIX_TOOLS_TAG = "posix" +# bm_project is registered twice under one name (#1832): a version without the +# delete command and one with it. Exactly one is visible, so tools/list never +# shows both, and calls route to the visible one. +BM_PROJECT_TOOL_KEY = "tool:bm_project@core" +BM_PROJECT_WITH_DELETE_TOOL_KEY = "tool:bm_project@with-delete" + + +def set_project_delete_visibility(server: FastMCP, enabled: bool) -> None: + """Show the bm_project variant with or without the delete command. + + Like set_posix_tools_visibility, the last marks appended win, so this is safe + to call at import, at each lifespan start, and in tests. + """ + server.add_transform(Visibility(enabled, keys={BM_PROJECT_WITH_DELETE_TOOL_KEY})) + server.add_transform(Visibility(not enabled, keys={BM_PROJECT_TOOL_KEY})) + + def set_posix_tools_visibility(server: FastMCP, enabled: bool) -> None: """Mark the POSIX tool group visible or hidden. @@ -111,6 +128,10 @@ async def lifespan(app: FastMCP): # config decides what clients see (no if-checks inside tool bodies). # Outcome: enabled by default; an explicit opt-out hides the POSIX group. set_posix_tools_visibility(app, config.enable_posix_tools) + # Trigger: the enable_project_delete config flag (off by default). + # Why: deleting a project removes it for every client; only the user turns it on. + # Outcome: bm_project lists a delete command, and is marked destructive, only then. + set_project_delete_visibility(app, config.enable_project_delete) standalone_redis_url = None if container.mode.is_cloud else config.redis_url diff --git a/src/basic_memory/mcp/tools/__init__.py b/src/basic_memory/mcp/tools/__init__.py index 48e1284f2..89af7b9e0 100644 --- a/src/basic_memory/mcp/tools/__init__.py +++ b/src/basic_memory/mcp/tools/__init__.py @@ -44,6 +44,10 @@ from basic_memory.mcp.tools.find_files import bm_find from basic_memory.mcp.tools.listing import bm_list from basic_memory.mcp.tools.move import bm_move +from basic_memory.mcp.tools.note_schemas import bm_schema + +# Importing projects registers both bm_project variants (core and with-delete). +from basic_memory.mcp.tools.projects import bm_project from basic_memory.mcp.tools.ranked_search import bm_search from basic_memory.mcp.tools.read import bm_read from basic_memory.mcp.tools.write import bm_write @@ -56,7 +60,9 @@ "bm_find", "bm_list", "bm_move", + "bm_project", "bm_read", + "bm_schema", "bm_search", "bm_write", "build_context", diff --git a/src/basic_memory/mcp/tools/note_schemas.py b/src/basic_memory/mcp/tools/note_schemas.py new file mode 100644 index 000000000..063e1f70e --- /dev/null +++ b/src/basic_memory/mcp/tools/note_schemas.py @@ -0,0 +1,185 @@ +"""bm_schema: validate notes against their schemas, infer schemas, find drift (#1832). + +Replaces schema_validate, schema_infer and schema_diff (SPEC-35.2). It calls the +schema API through the typed SchemaClient, as they do, and shares their report +formatting; what differs is that "nothing to report" cases are refusals (C11), not +success payloads describing a failure. +""" + +from typing import Annotated, Any, Literal + +from fastmcp import Context +from fastmcp.exceptions import ToolError +from pydantic import AliasChoices, Field + +from basic_memory.mcp.clients.schema import SchemaClient +from basic_memory.mcp.note_targets import open_project_target +from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.schema_reports import ( + format_drift_report, + format_inference_report, + format_validation_report, +) +from basic_memory.mcp.server import mcp +from basic_memory.mcp.tool_params import OutputFormat, ProjectParam + +type SchemaCommand = Literal["validate", "infer", "diff"] + + +@mcp.tool( + name="bm_schema", + title="Note schemas", + description=( + "Basic Memory note schemas (Picoschema). `command`: validate notes against their " + "schema (one `note_type`, one note by `identifier`, or every type that has a " + "schema); infer a schema from the notes of a `note_type`; diff a `note_type`'s " + "notes against its schema to find drift. A schema is a note with type: schema " + "whose `entity` field names the note type it describes." + ), + tags={"schema"}, + annotations={ + "title": "Note schemas", + "readOnlyHint": True, + "destructiveHint": False, + "idempotentHint": True, + "openWorldHint": False, + }, +) +async def bm_schema( + command: Annotated[SchemaCommand, Field(description="What to do.")], + note_type: Annotated[ + str | None, + Field( + min_length=1, + validation_alias=AliasChoices("note_type", "type"), + description="The frontmatter `type:` to check. Required for infer and diff.", + ), + ] = None, + identifier: Annotated[ + str | None, + Field( + min_length=1, + validation_alias=AliasChoices("identifier", "file_path"), + description="For validate: one note, instead of a whole note type.", + ), + ] = None, + threshold: Annotated[ + float, + Field( + ge=0, + le=1, + description=("For infer: the share of notes a field must appear in to be suggested."), + ), + ] = 0.25, + output_format: OutputFormat = "text", + project: ProjectParam = None, + context: Context | None = None, +) -> str | dict[str, Any]: + """Validate, infer or diff note schemas.""" + if command != "validate" and identifier is not None: + raise refusal( + "INVALID_ARGUMENTS", + f"{command} works on a note type, not one note; give `note_type`.", + output_format=output_format, + ) + + # A note identifier routes like every bm_* target; otherwise only `project` does. + async with open_project_target( + identifier or "/", project, context, output_format=output_format + ) as target: + schema_client = SchemaClient(target.client, target.project.external_id) + if command == "validate": + note = target.route.path if identifier is not None else None + return await _validate(schema_client, note_type, note, output_format) + if note_type is None: + raise refusal( + "INVALID_ARGUMENTS", + f"{command} needs `note_type`, the frontmatter type to check.", + try_instead="bm_find(filters={'type': ...}) to see which types exist", + output_format=output_format, + ) + if command == "infer": + return await _infer(schema_client, note_type, threshold, output_format) + return await _diff(schema_client, note_type, output_format) + + +def _no_schema(note_type: str, output_format: OutputFormat) -> ToolError: + return refusal( + "NOT_FOUND", + f"No schema note describes type '{note_type}'.", + try_instead=( + f"bm_schema(command='infer', note_type='{note_type}'), then bm_write the " + "suggestion as a note with type: schema" + ), + output_format=output_format, + ) + + +async def _validate( + schema_client: SchemaClient, + note_type: str | None, + identifier: str | None, + output_format: OutputFormat, +) -> str | dict[str, Any]: + report = await schema_client.validate(note_type=note_type, identifier=identifier) + # Trigger: neither note_type nor identifier (every type that has a schema, #1013). + # Why: an empty report then means no schemas exist, not a missing note type. + if note_type is None and identifier is None: + if not report.type_summaries: + raise refusal( + "NOT_FOUND", + "This project has no schema notes, so there is nothing to validate.", + try_instead="bm_schema(command='infer', note_type=...) to draft one", + output_format=output_format, + ) + else: + checked_type = note_type or report.note_type or identifier or "" + if report.total_entities == 0: + raise refusal( + "NOT_FOUND", + f"No notes of type '{checked_type}' in this project.", + try_instead="bm_find(filters={'type': ...}) to see which types exist", + output_format=output_format, + ) + # Notes exist, but none were validated: no schema applies to them. + if report.total_notes == 0: + raise _no_schema(checked_type, output_format) + if output_format == "json": + return report.model_dump(mode="json", exclude_none=True) + return format_validation_report(report) + + +async def _infer( + schema_client: SchemaClient, note_type: str, threshold: float, output_format: OutputFormat +) -> str | dict[str, Any]: + report = await schema_client.infer(note_type, threshold=threshold) + if report.notes_analyzed == 0: + raise refusal( + "NOT_FOUND", + f"No notes of type '{note_type}' in this project.", + try_instead="bm_find(filters={'type': ...}) to see which types exist", + output_format=output_format, + ) + # Every field fell below the threshold: the notes share no structure to suggest. + if not report.suggested_schema: + raise refusal( + "NOT_FOUND", + f"No field appears in {threshold:.0%} of the {report.notes_analyzed} " + f"'{note_type}' notes, so there is no schema to suggest.", + try_instead=f"bm_schema(command='infer', note_type='{note_type}', threshold=0.1)", + output_format=output_format, + ) + if output_format == "json": + return report.model_dump(mode="json", exclude_none=True) + return format_inference_report(report) + + +async def _diff( + schema_client: SchemaClient, note_type: str, output_format: OutputFormat +) -> str | dict[str, Any]: + report = await schema_client.diff(note_type) + if not report.schema_found: + raise _no_schema(note_type, output_format) + if output_format == "json": + return report.model_dump(mode="json", exclude_none=True) + return format_drift_report(report) diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py new file mode 100644 index 000000000..620f70bac --- /dev/null +++ b/src/basic_memory/mcp/tools/projects.py @@ -0,0 +1,251 @@ +"""bm_project: projects and workspaces (SPEC-35.2, #1832). + +Replaces list_memory_projects (which already groups projects by workspace), +create_memory_project, recent_activity and, when enabled, delete_project. Each +command delegates to the implementation of the tool it replaces; this module only +gives them one name, one `command` parameter and the shared parameter types. + +The tool is registered twice under one name: `core` without the delete command and +`with-delete` with it. The composition root shows one of the two from the +enable_project_delete setting (see mcp.server.set_project_delete_visibility). +""" + +import os +from typing import Annotated, Any, Literal + +from fastmcp import Context +from pydantic import AliasChoices, Field + +from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.server import mcp, set_project_delete_visibility +from basic_memory.mcp.tool_params import ( + Items, + OutputFormat, + Page, + PageSize, + ProjectParam, + Since, + parse_project, + routing_arguments, +) +from basic_memory.mcp.tools.project_management import ( + create_memory_project, + delete_project, + list_memory_projects, +) +from basic_memory.mcp.tools.recent_activity import recent_activity + +type ProjectCommand = Literal["list", "create", "recent"] +type ProjectCommandWithDelete = Literal["list", "create", "recent", "delete"] + +_DESCRIPTION = ( + "Basic Memory projects. `command`: list (projects, grouped by workspace); create " + "(`name`, `path`, optional `set_default`, `workspace`); recent (what changed lately: " + "`since`, `items`, paging; omit `project` to see every project)." +) + +# --- Parameters --- + +NewProjectName = Annotated[ + str | None, + Field( + min_length=1, + validation_alias=AliasChoices("name", "project_name"), + description="For create and delete: the project's name.", + ), +] +NewProjectPath = Annotated[ + str | None, + Field( + min_length=1, + validation_alias=AliasChoices("path", "project_path"), + description="For create: the folder that holds the project's notes.", + ), +] +SetDefault = Annotated[bool, Field(description="For create: make the new project the default.")] +Workspace = Annotated[ + str | None, + Field(description="For create and delete in Cloud: the workspace slug, name or id."), +] + + +@mcp.tool( + name="bm_project", + version="core", + title="Projects", + description=_DESCRIPTION, + tags={"projects"}, + annotations={ + "title": "Projects", + "readOnlyHint": False, + "destructiveHint": False, + "idempotentHint": False, + "openWorldHint": False, + }, +) +async def bm_project( + command: Annotated[ProjectCommand, Field(description="What to do.")], + name: NewProjectName = None, + path: NewProjectPath = None, + set_default: SetDefault = False, + workspace: Workspace = None, + since: Since = "7d", + items: Items = None, + page: Page = 1, + page_size: PageSize = 10, + output_format: OutputFormat = "text", + project: ProjectParam = None, + context: Context | None = None, +) -> str | dict[str, Any] | list[dict[str, Any]]: + """List, create, or show recent activity in projects.""" + return await _run_project_command( + command, + name=name, + path=path, + set_default=set_default, + workspace=workspace, + delete_notes=False, + since=since, + items=items, + page=page, + page_size=page_size, + output_format=output_format, + project=project, + context=context, + ) + + +@mcp.tool( + name="bm_project", + version="with-delete", + title="Projects", + description=( + _DESCRIPTION + " delete (`name`, `delete_notes`, `workspace`) removes a project; with " + "delete_notes=true its files go too. This cannot be undone." + ), + tags={"projects"}, + annotations={ + "title": "Projects", + "readOnlyHint": False, + "destructiveHint": True, + "idempotentHint": False, + "openWorldHint": False, + }, +) +async def bm_project_with_delete( + command: Annotated[ProjectCommandWithDelete, Field(description="What to do.")], + name: NewProjectName = None, + path: NewProjectPath = None, + set_default: SetDefault = False, + workspace: Workspace = None, + delete_notes: Annotated[ + bool, Field(description="For delete: also delete the project's files.") + ] = False, + since: Since = "7d", + items: Items = None, + page: Page = 1, + page_size: PageSize = 10, + output_format: OutputFormat = "text", + project: ProjectParam = None, + context: Context | None = None, +) -> str | dict[str, Any] | list[dict[str, Any]]: + """List, create, delete, or show recent activity in projects.""" + return await _run_project_command( + command, + name=name, + path=path, + set_default=set_default, + workspace=workspace, + delete_notes=delete_notes, + since=since, + items=items, + page=page, + page_size=page_size, + output_format=output_format, + project=project, + context=context, + ) + + +# Hidden until the composition root reads enable_project_delete at startup. +set_project_delete_visibility(mcp, False) + + +async def _run_project_command( + command: ProjectCommandWithDelete, + *, + name: str | None, + path: str | None, + set_default: bool, + workspace: str | None, + delete_notes: bool, + since: str, + items: list[Literal["note", "observation", "relation"]] | None, + page: int, + page_size: int, + output_format: OutputFormat, + project: str | None, + context: Context | None, +) -> str | dict[str, Any] | list[dict[str, Any]]: + """Check the arguments a command takes, then run the tool it replaces.""" + # Trigger: the server is constrained to one project (BASIC_MEMORY_MCP_PROJECT). + # Why: such a session serves that project only; adding or removing projects + # belongs to whoever configured it. The replaced tools answered this + # with a success payload describing the failure (C11). + # Outcome: an UNSUPPORTED refusal that names the CLI command instead. + constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT") + if constrained_project and command in ("create", "delete"): + cli = "add" if command == "create" else "remove" + raise refusal( + "UNSUPPORTED", + f"This MCP server is constrained to project '{constrained_project}', so it " + f"cannot {command} projects.", + try_instead=f"the CLI: basic-memory project {cli} ...", + output_format=output_format, + ) + match command: + case "list": + return await list_memory_projects(output_format=output_format, context=context) + case "create": + if name is None or path is None: + raise refusal( + "INVALID_ARGUMENTS", + "create needs `name` and `path`.", + try_instead="bm_project(command='create', name='research', path='~/research')", + output_format=output_format, + ) + return await create_memory_project( + project_name=name, + project_path=path, + set_default=set_default, + workspace=workspace, + output_format=output_format, + context=context, + ) + case "recent": + project_name, project_id = routing_arguments(parse_project(project)) + return await recent_activity( + # recent_activity names whole notes "entity", the API's word. + type=["entity" if item == "note" else item for item in items] if items else "", + timeframe=since, + page=page, + page_size=page_size, + project=project_name, + project_id=project_id, + output_format=output_format, + context=context, + ) + case "delete": + if name is None: + raise refusal( + "INVALID_ARGUMENTS", + "delete needs `name`, the project to delete.", + try_instead="bm_project(command='list') to see project names", + output_format=output_format, + ) + return await delete_project( + project_name=name, + delete_notes=delete_notes, + workspace=workspace, + context=context, + ) diff --git a/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index 6e7834c10..085c3bbd2 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -10,155 +10,13 @@ from fastmcp import Context from basic_memory.mcp.project_context import get_project_client +from basic_memory.mcp.schema_reports import ( + format_drift_report, + format_inference_report, + format_validation_report, +) from basic_memory.mcp.server import mcp -from basic_memory.schemas.schema import DriftReport, InferenceReport, ValidationReport - - -def _format_validation_report(report: ValidationReport) -> str: - """Render a ValidationReport as readable markdown. - - Produces output the LLM can display directly instead of trying to - interpret raw JSON, which leads to "undefined — invalid" rendering. - """ - lines: list[str] = [] - - # --- Header --- - type_label = report.note_type or "all" - lines.append(f"# Schema Validation: {type_label}") - lines.append("") - lines.append( - f"Notes: {report.total_notes} | Valid: {report.valid_count} " - f"| Warnings: {report.warning_count} | Errors: {report.error_count}" - ) - lines.append("") - - # --- Per-type breakdown (all-types mode) --- - if report.type_summaries: - lines.append("## By Type") - lines.append("") - for summary in report.type_summaries: - if summary.total_entities == 0: - lines.append(f"- **{summary.note_type}**: no notes") - else: - lines.append( - f"- **{summary.note_type}**: {summary.valid_count}/{summary.total_notes} valid" - ) - lines.append("") - - # --- Per-note results --- - for r in report.results: - status = "valid" if r.passed else "INVALID" - lines.append(f"- **{r.note_identifier}** — {status}") - for w in r.warnings: - lines.append(f" - warning: {w}") - for e in r.errors: - lines.append(f" - error: {e}") - - return "\n".join(lines) - - -def _format_inference_report(report: InferenceReport) -> str: - """Render an InferenceReport as readable markdown. - - Without this formatter the LLM receives raw JSON and renders - field names as "undefined". - """ - lines: list[str] = [] - - # --- Header --- - lines.append(f"# Schema Inference: {report.note_type}") - lines.append("") - lines.append(f"Notes analyzed: {report.notes_analyzed}") - lines.append("") - - # --- Suggested schema YAML --- - if report.suggested_schema: - lines.append("## Suggested Schema") - lines.append("") - lines.append("```yaml") - lines.append("---") - lines.append(f"title: {report.note_type.title()}") - lines.append("type: schema") - lines.append(f"entity: {report.note_type}") - lines.append("version: 1") - lines.append("schema:") - for field_name, field_def in report.suggested_schema.items(): - lines.append(f" {field_name}: {field_def}") - lines.append("---") - lines.append("```") - lines.append("") - - # --- Field frequency table --- - if report.field_frequencies: - lines.append("## Field Frequencies") - lines.append("") - for f in report.field_frequencies: - pct = f"{f.percentage:.0%}" - req_marker = "required" if f.name in report.suggested_required else "optional" - samples = ", ".join(f.sample_values[:3]) if f.sample_values else "" - sample_str = f" (e.g. {samples})" if samples else "" - lines.append( - f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total}) " - f"[{req_marker}]{sample_str}" - ) - lines.append("") - - # --- Excluded fields --- - if report.excluded: - lines.append("## Excluded (below threshold)") - lines.append("") - for name in report.excluded: - lines.append(f"- {name}") - lines.append("") - - return "\n".join(lines) - - -def _format_drift_report(report: DriftReport) -> str: - """Render a DriftReport as readable markdown. - - Without this formatter the LLM receives raw JSON and renders - field names as "undefined". - """ - lines: list[str] = [] - - # --- Header --- - lines.append(f"# Schema Drift: {report.note_type}") - lines.append("") - - has_drift = report.new_fields or report.dropped_fields or report.cardinality_changes - - if not has_drift: - lines.append("No drift detected — schema matches actual usage.") - return "\n".join(lines) - - # --- New fields --- - if report.new_fields: - lines.append("## New Fields (in notes but not in schema)") - lines.append("") - for f in report.new_fields: - pct = f"{f.percentage:.0%}" - lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") - lines.append("") - - # --- Dropped fields --- - if report.dropped_fields: - lines.append("## Dropped Fields (in schema but rare in notes)") - lines.append("") - for f in report.dropped_fields: - pct = f"{f.percentage:.0%}" - lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") - lines.append("") - - # --- Cardinality changes --- - if report.cardinality_changes: - lines.append("## Cardinality Changes") - lines.append("") - for change in report.cardinality_changes: - lines.append(f"- {change}") - lines.append("") - - return "\n".join(lines) +from basic_memory.schemas.schema import ValidationReport def _no_notes_guidance(note_type: str, tool_name: str) -> str: @@ -339,7 +197,7 @@ async def schema_validate( return _no_schemas_defined_guidance("schema_validate") if output_format == "json": return result.model_dump(mode="json", exclude_none=True) - return _format_validation_report(result) + return format_validation_report(result) # --- No notes guard --- # Trigger: no entities of this type exist in the project @@ -363,7 +221,7 @@ async def schema_validate( if output_format == "json": return result.model_dump(mode="json", exclude_none=True) - return _format_validation_report(result) + return format_validation_report(result) except Exception as e: logger.error(f"Schema validation failed: {e}, project: {active_project.name}") @@ -494,7 +352,7 @@ async def schema_infer( if output_format == "json": return result.model_dump(mode="json", exclude_none=True) - return _format_inference_report(result) + return format_inference_report(result) except Exception as e: logger.error(f"Schema inference failed: {e}, project: {active_project.name}") @@ -598,7 +456,7 @@ async def schema_diff( if output_format == "json": return result.model_dump(mode="json", exclude_none=True) - return _format_drift_report(result) + return format_drift_report(result) except Exception as e: logger.error(f"Schema diff failed: {e}, project: {active_project.name}") diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py new file mode 100644 index 000000000..5737a3530 --- /dev/null +++ b/tests/mcp/test_tool_bm_project.py @@ -0,0 +1,227 @@ +"""bm_project and bm_schema: one name per group, commands delegate (#1832).""" + +from typing import Any + +import pytest +from fastmcp.exceptions import ToolError + +from basic_memory.mcp.server import lifespan, mcp, set_project_delete_visibility +from basic_memory.mcp.tools import bm_project, bm_schema, bm_write +from basic_memory.mcp.tools.projects import bm_project_with_delete + + +async def _listed_bm_project() -> Any: + # The server's own listing: entering a Client would run the lifespan, which + # re-applies the config flag this test sets directly. + (tool,) = [tool for tool in await mcp.list_tools() if tool.name == "bm_project"] + return tool + + +# --- Delete is opt-in --- + + +@pytest.mark.asyncio +async def test_delete_is_hidden_by_default(): + tool = await _listed_bm_project() + + assert tool.parameters["properties"]["command"]["enum"] == ["list", "create", "recent"] + assert tool.annotations.destructive_hint is False + + +@pytest.mark.asyncio +async def test_enabling_delete_swaps_in_the_destructive_variant(): + set_project_delete_visibility(mcp, True) + try: + tool = await _listed_bm_project() + finally: + set_project_delete_visibility(mcp, False) + + assert "delete" in tool.parameters["properties"]["command"]["enum"] + assert tool.annotations.destructive_hint is True + + +@pytest.mark.asyncio +async def test_config_flag_enables_delete_through_lifespan(config_manager): + cfg = config_manager.load_config() + assert cfg.enable_project_delete is False + cfg.enable_project_delete = True + config_manager.save_config(cfg) + + try: + async with lifespan(mcp): + tool = await _listed_bm_project() + finally: + set_project_delete_visibility(mcp, False) + + assert tool.annotations.destructive_hint is True + + +# --- Commands --- + + +@pytest.mark.asyncio +async def test_list(app, test_project): + result = await bm_project(command="list", output_format="json") + + assert isinstance(result, dict) + assert test_project.name in {project["name"] for project in result["projects"]} + + +@pytest.mark.asyncio +async def test_create_and_delete(app, tmp_path_factory): + project_root = tmp_path_factory.mktemp("bm-project-home") + + created = await bm_project(command="create", name="Scratch", path=str(project_root)) + deleted = await bm_project_with_delete(command="delete", name="Scratch") + + assert isinstance(created, str) and created.startswith("✓") + assert isinstance(deleted, str) and deleted.startswith("✓") + + +@pytest.mark.asyncio +async def test_recent_maps_items_and_since(client, test_project): + await bm_write( + identifier="notes/fresh.md", + content="- [fact] something new", + project=test_project.name, + ) + + notes = await bm_project( + command="recent", + items=["note"], + since="1d", + output_format="json", + project=test_project.name, + ) + observations = await bm_project( + command="recent", items=["observation"], output_format="json", project=test_project.name + ) + + assert isinstance(notes, list) and isinstance(observations, list) + assert any(row["title"] == "fresh" for row in notes) + assert all(row["type"] == "observation" for row in observations) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("arguments", "message"), + [ + ({"command": "create", "name": "x"}, "create needs `name` and `path`"), + ({"command": "create", "path": "/tmp/x"}, "create needs `name` and `path`"), + ], +) +async def test_project_argument_refusals(arguments, message): + with pytest.raises(ToolError, match=f"^INVALID_ARGUMENTS: {message}"): + await bm_project(**arguments) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("command", ["create", "delete"]) +async def test_constrained_server_refuses_project_changes(monkeypatch, command): + monkeypatch.setenv("BASIC_MEMORY_MCP_PROJECT", "only-this") + + with pytest.raises(ToolError, match="^UNSUPPORTED: .*constrained to project 'only-this'"): + await bm_project_with_delete(command=command, name="x", path="/tmp/x") + + +@pytest.mark.asyncio +async def test_delete_needs_a_name(): + with pytest.raises(ToolError, match="^INVALID_ARGUMENTS: delete needs `name`"): + await bm_project_with_delete(command="delete") + + +# --- bm_schema --- + + +@pytest.mark.asyncio +async def test_schema_commands_delegate(client, test_project): + for name in ("ada", "grace"): + await bm_write( + identifier=f"people/{name}.md", + content="---\ntype: person\n---\n\n- [role] engineer\n- works_at [[Lab]]", + project=test_project.name, + ) + + inferred = await bm_schema( + command="infer", note_type="person", output_format="json", project=test_project.name + ) + assert isinstance(inferred, dict) and inferred["note_type"] == "person" + assert inferred["suggested_schema"] + + with pytest.raises(ToolError, match="^NOT_FOUND: No schema note describes type 'person'"): + await bm_schema(command="diff", note_type="person", project=test_project.name) + with pytest.raises(ToolError, match="^NOT_FOUND: No schema note describes type 'person'"): + await bm_schema(command="validate", note_type="person", project=test_project.name) + with pytest.raises(ToolError, match="^NOT_FOUND: This project has no schema notes"): + await bm_schema(command="validate", project=test_project.name) + with pytest.raises(ToolError, match="^NOT_FOUND: No notes of type 'robot'"): + await bm_schema(command="validate", note_type="robot", project=test_project.name) + + +PERSON_SCHEMA = ( + "---\ntitle: Person\ntype: schema\nentity: person\nversion: 1\n" + "schema:\n role: string, what they do\nsettings:\n validation: warn\n---\n\n# Person" +) + + +@pytest.mark.asyncio +async def test_schema_reports_once_a_schema_exists(client, test_project): + await bm_write(identifier="schemas/person.md", content=PERSON_SCHEMA, project=test_project.name) + await bm_write( + identifier="people/ada.md", + content="---\ntype: person\n---\n\n- [role] engineer", + project=test_project.name, + ) + + report = await bm_schema( + command="validate", note_type="person", output_format="json", project=test_project.name + ) + text = await bm_schema(command="validate", project=test_project.name) + note = await bm_schema( + command="validate", identifier="people/ada.md", project=test_project.name + ) + drift = await bm_schema( + command="diff", note_type="person", output_format="json", project=test_project.name + ) + drift_text = await bm_schema(command="diff", note_type="person", project=test_project.name) + inferred_text = await bm_schema(command="infer", note_type="person", project=test_project.name) + + assert isinstance(report, dict) and report["total_notes"] == 1 + assert isinstance(text, str) and isinstance(note, str) + assert isinstance(drift, dict) and drift["schema_found"] is True + assert isinstance(drift_text, str) and isinstance(inferred_text, str) + + +@pytest.mark.asyncio +async def test_infer_with_no_notes_of_the_type(client, test_project): + with pytest.raises(ToolError, match="^NOT_FOUND: No notes of type 'robot'"): + await bm_schema(command="infer", note_type="robot", project=test_project.name) + + +@pytest.mark.asyncio +async def test_infer_below_the_threshold(client, test_project): + for name, category in (("ada", "role"), ("grace", "hobby"), ("alan", "pet")): + await bm_write( + identifier=f"people/{name}.md", + content=f"---\ntype: person\n---\n\n- [{category}] something", + project=test_project.name, + ) + + with pytest.raises(ToolError, match="^NOT_FOUND: No field appears in 90%"): + await bm_schema( + command="infer", note_type="person", threshold=0.9, project=test_project.name + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("arguments", "message"), + [ + ({"command": "infer"}, "infer needs `note_type`"), + ({"command": "diff"}, "diff needs `note_type`"), + ({"command": "diff", "identifier": "a.md"}, "diff works on a note type, not one note"), + ], +) +async def test_schema_argument_refusals(client, test_project, arguments, message): + with pytest.raises(ToolError, match=f"^INVALID_ARGUMENTS: {message}"): + await bm_schema(project=test_project.name, **arguments) diff --git a/tests/mcp/test_tool_contracts.py b/tests/mcp/test_tool_contracts.py index ca7deeca0..a35552e2d 100644 --- a/tests/mcp/test_tool_contracts.py +++ b/tests/mcp/test_tool_contracts.py @@ -9,6 +9,7 @@ import pytest from basic_memory.mcp import tools +from basic_memory.mcp.tools.projects import bm_project_with_delete from basic_memory.mcp.server import mcp @@ -77,6 +78,42 @@ "output_format", "project", ], + "bm_project": [ + "command", + "name", + "path", + "set_default", + "workspace", + "since", + "items", + "page", + "page_size", + "output_format", + "project", + ], + # The same tool name with the delete command; shown only with enable_project_delete. + "bm_project_with_delete": [ + "command", + "name", + "path", + "set_default", + "workspace", + "delete_notes", + "since", + "items", + "page", + "page_size", + "output_format", + "project", + ], + "bm_schema": [ + "command", + "note_type", + "identifier", + "threshold", + "output_format", + "project", + ], "bm_write": [ "content", "identifier", @@ -289,6 +326,8 @@ "bm_edit": {"readOnlyHint": False, "destructiveHint": True}, "bm_move": {"readOnlyHint": False, "destructiveHint": False}, "bm_delete": {"readOnlyHint": False, "destructiveHint": True}, + "bm_project": {"readOnlyHint": False, "destructiveHint": False}, + "bm_schema": {"readOnlyHint": True, "destructiveHint": False}, "build_context": {"readOnlyHint": True, "destructiveHint": False}, "fetch": {"readOnlyHint": True, "destructiveHint": False}, "list_directory": {"readOnlyHint": True, "destructiveHint": False}, @@ -355,6 +394,9 @@ "bm_edit": tools.bm_edit, "bm_move": tools.bm_move, "bm_delete": tools.bm_delete, + "bm_project": tools.bm_project, + "bm_project_with_delete": bm_project_with_delete, + "bm_schema": tools.bm_schema, "basic_memory_diagnostics": tools.basic_memory_diagnostics, "build_context": tools.build_context, "cat": tools.cat, diff --git a/tests/test_man_pages.py b/tests/test_man_pages.py index cd79ff7f2..5526738ad 100644 --- a/tests/test_man_pages.py +++ b/tests/test_man_pages.py @@ -147,7 +147,9 @@ def test_bundled_pages_are_well_formed_and_sorted() -> None: "bm_find", "bm_list", "bm_move", + "bm_project", "bm_read", + "bm_schema", "bm_search", "bm_write", } From b0374d10034b9aff548951bf274790175b17787e Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 08:20:53 -0500 Subject: [PATCH 02/17] refactor(mcp): one shape for grouped tools; bm_project_delete as its own tool - bm_project and bm_schema are both thin dispatchers over the tools they replace. The replaced tools now refuse instead of returning a success that describes a failure (#1813): - schema_validate/infer/diff: "no schemas", "no notes of this type", "no schema for this type" and "nothing above the threshold" are NOT_FOUND refusals carrying the old guidance; the broad `except Exception` blocks that turned API failures into success text are gone. - create_memory_project/delete_project: a constrained session is an UNSUPPORTED refusal. - Project delete is a separate tool, bm_project_delete, listed only when enable_project_delete is on (tag visibility, like enable_posix_tools). bm_project is never destructive; the two-version registration and the schema_reports move are gone. - refusal() returns a typed Refusal (a ToolError with code/message), so in-process callers branch on the code: `bm schema validate|infer|diff` still print "nothing to report" and exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/cli/commands/schema.py | 24 +- src/basic_memory/config_models.py | 2 +- src/basic_memory/mcp/refusals.py | 45 +- src/basic_memory/mcp/schema_reports.py | 150 ------- src/basic_memory/mcp/server.py | 15 +- src/basic_memory/mcp/tools/__init__.py | 4 +- src/basic_memory/mcp/tools/note_schemas.py | 150 ++----- .../mcp/tools/project_management.py | 35 +- src/basic_memory/mcp/tools/projects.py | 238 ++++------ src/basic_memory/mcp/tools/schema.py | 423 +++++++++++------- .../test_single_project_mcp_integration.py | 23 +- tests/cli/test_cli_schema.py | 17 + tests/mcp/test_tool_bm_project.py | 77 ++-- tests/mcp/test_tool_contracts.py | 21 +- tests/mcp/test_tool_project_management.py | 27 +- tests/mcp/test_tool_schema.py | 157 ++++--- tests/test_man_pages.py | 1 + 17 files changed, 632 insertions(+), 777 deletions(-) delete mode 100644 src/basic_memory/mcp/schema_reports.py diff --git a/src/basic_memory/cli/commands/schema.py b/src/basic_memory/cli/commands/schema.py index 983338a56..565a3f08e 100644 --- a/src/basic_memory/cli/commands/schema.py +++ b/src/basic_memory/cli/commands/schema.py @@ -9,6 +9,7 @@ """ import json +from collections.abc import Coroutine from typing import Any, Annotated, Optional import typer @@ -166,6 +167,23 @@ def _render_diff_output(data: dict[str, Any]) -> None: # --- Commands --- +def _run_schema_tool(call: Coroutine[Any, Any, Any]) -> Any: + """Run a schema tool; nothing to report keeps the CLI's {"error": message} result. + + The MCP tools refuse "no schemas yet" and "no notes of this type" as NOT_FOUND + (#1813). For the CLI that is not a failure: the command prints the message and + exits 0, as it always has. + """ + from basic_memory.mcp.refusals import Refusal + + try: + return run_with_cleanup(call) + except Refusal as refused: + if refused.code != "NOT_FOUND": + raise + return {"error": refused.message} + + @schema_app.command() def validate( target: Annotated[ @@ -209,7 +227,7 @@ def validate( note_type = target with force_routing(local=local, cloud=cloud): - result = run_with_cleanup( + result = _run_schema_tool( mcp_schema_validate( note_type=note_type, identifier=identifier, @@ -287,7 +305,7 @@ def infer( project_name = _resolve_project_name(project) with force_routing(local=local, cloud=cloud): - result = run_with_cleanup( + result = _run_schema_tool( mcp_schema_infer( note_type=note_type, threshold=threshold, @@ -370,7 +388,7 @@ def diff( project_name = _resolve_project_name(project) with force_routing(local=local, cloud=cloud): - result = run_with_cleanup( + result = _run_schema_tool( mcp_schema_diff( note_type=note_type, project=project_name, diff --git a/src/basic_memory/config_models.py b/src/basic_memory/config_models.py index 9586d5c0e..ccfa011cf 100644 --- a/src/basic_memory/config_models.py +++ b/src/basic_memory/config_models.py @@ -610,7 +610,7 @@ def __init__(self, **data: Any) -> None: ... enable_project_delete: bool = Field( default=False, description=( - "Offer bm_project(command='delete') to MCP clients. Off by default, so an " + "Offer the bm_project_delete tool to MCP clients. Off by default, so an " "assistant cannot remove a project unless you turn this on. " "Env: BASIC_MEMORY_ENABLE_PROJECT_DELETE" ), diff --git a/src/basic_memory/mcp/refusals.py b/src/basic_memory/mcp/refusals.py index 304d454b5..2db2eab5e 100644 --- a/src/basic_memory/mcp/refusals.py +++ b/src/basic_memory/mcp/refusals.py @@ -35,26 +35,53 @@ ] +class Refusal(ToolError): + """A tool error that is a refusal, keeping its parts for in-process callers. + + MCP clients see only the rendered message. The CLI, which calls tool functions + directly, reads `code` to tell "nothing to report" from a failure. + """ + + def __init__( + self, + code: RefusalCode, + message: str, + *, + try_instead: str | None, + output_format: OutputFormat, + ) -> None: + self.code: RefusalCode = code + self.message = message + self.try_instead = try_instead + super().__init__(_render(code, message, try_instead, output_format)) + + +def _render( + code: RefusalCode, message: str, try_instead: str | None, output_format: OutputFormat +) -> str: + if output_format == "json": + payload: dict[str, str] = {"error": code, "message": message} + if try_instead is not None: + payload["try_instead"] = try_instead + return json.dumps(payload) + if try_instead is None: + return f"{code}: {message}" + return f"{code}: {message}\nTry instead: {try_instead}" + + def refusal( code: RefusalCode, message: str, *, try_instead: str | None = None, output_format: OutputFormat = "text", -) -> ToolError: +) -> Refusal: """Build the error a tool raises to refuse a call. Returns the exception rather than raising it, so the call site reads `raise refusal(...)` and the type checker sees the branch end. """ - if output_format == "json": - payload: dict[str, str] = {"error": code, "message": message} - if try_instead is not None: - payload["try_instead"] = try_instead - return ToolError(json.dumps(payload)) - if try_instead is None: - return ToolError(f"{code}: {message}") - return ToolError(f"{code}: {message}\nTry instead: {try_instead}") + return Refusal(code, message, try_instead=try_instead, output_format=output_format) # --- API refusals --- diff --git a/src/basic_memory/mcp/schema_reports.py b/src/basic_memory/mcp/schema_reports.py deleted file mode 100644 index 5fcc3569b..000000000 --- a/src/basic_memory/mcp/schema_reports.py +++ /dev/null @@ -1,150 +0,0 @@ -"""Markdown renderings of schema reports, shared by the schema tools (#1832).""" - -from basic_memory.schemas.schema import DriftReport, InferenceReport, ValidationReport - - -def format_validation_report(report: ValidationReport) -> str: - """Render a ValidationReport as readable markdown. - - Produces output the LLM can display directly instead of trying to - interpret raw JSON, which leads to "undefined — invalid" rendering. - """ - lines: list[str] = [] - - # --- Header --- - type_label = report.note_type or "all" - lines.append(f"# Schema Validation: {type_label}") - lines.append("") - lines.append( - f"Notes: {report.total_notes} | Valid: {report.valid_count} " - f"| Warnings: {report.warning_count} | Errors: {report.error_count}" - ) - lines.append("") - - # --- Per-type breakdown (all-types mode) --- - if report.type_summaries: - lines.append("## By Type") - lines.append("") - for summary in report.type_summaries: - if summary.total_entities == 0: - lines.append(f"- **{summary.note_type}**: no notes") - else: - lines.append( - f"- **{summary.note_type}**: {summary.valid_count}/{summary.total_notes} valid" - ) - lines.append("") - - # --- Per-note results --- - for r in report.results: - status = "valid" if r.passed else "INVALID" - lines.append(f"- **{r.note_identifier}** — {status}") - for w in r.warnings: - lines.append(f" - warning: {w}") - for e in r.errors: - lines.append(f" - error: {e}") - - return "\n".join(lines) - - -def format_inference_report(report: InferenceReport) -> str: - """Render an InferenceReport as readable markdown. - - Without this formatter the LLM receives raw JSON and renders - field names as "undefined". - """ - lines: list[str] = [] - - # --- Header --- - lines.append(f"# Schema Inference: {report.note_type}") - lines.append("") - lines.append(f"Notes analyzed: {report.notes_analyzed}") - lines.append("") - - # --- Suggested schema YAML --- - if report.suggested_schema: - lines.append("## Suggested Schema") - lines.append("") - lines.append("```yaml") - lines.append("---") - lines.append(f"title: {report.note_type.title()}") - lines.append("type: schema") - lines.append(f"entity: {report.note_type}") - lines.append("version: 1") - lines.append("schema:") - for field_name, field_def in report.suggested_schema.items(): - lines.append(f" {field_name}: {field_def}") - lines.append("---") - lines.append("```") - lines.append("") - - # --- Field frequency table --- - if report.field_frequencies: - lines.append("## Field Frequencies") - lines.append("") - for f in report.field_frequencies: - pct = f"{f.percentage:.0%}" - req_marker = "required" if f.name in report.suggested_required else "optional" - samples = ", ".join(f.sample_values[:3]) if f.sample_values else "" - sample_str = f" (e.g. {samples})" if samples else "" - lines.append( - f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total}) " - f"[{req_marker}]{sample_str}" - ) - lines.append("") - - # --- Excluded fields --- - if report.excluded: - lines.append("## Excluded (below threshold)") - lines.append("") - for name in report.excluded: - lines.append(f"- {name}") - lines.append("") - - return "\n".join(lines) - - -def format_drift_report(report: DriftReport) -> str: - """Render a DriftReport as readable markdown. - - Without this formatter the LLM receives raw JSON and renders - field names as "undefined". - """ - lines: list[str] = [] - - # --- Header --- - lines.append(f"# Schema Drift: {report.note_type}") - lines.append("") - - has_drift = report.new_fields or report.dropped_fields or report.cardinality_changes - - if not has_drift: - lines.append("No drift detected — schema matches actual usage.") - return "\n".join(lines) - - # --- New fields --- - if report.new_fields: - lines.append("## New Fields (in notes but not in schema)") - lines.append("") - for f in report.new_fields: - pct = f"{f.percentage:.0%}" - lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") - lines.append("") - - # --- Dropped fields --- - if report.dropped_fields: - lines.append("## Dropped Fields (in schema but rare in notes)") - lines.append("") - for f in report.dropped_fields: - pct = f"{f.percentage:.0%}" - lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") - lines.append("") - - # --- Cardinality changes --- - if report.cardinality_changes: - lines.append("## Cardinality Changes") - lines.append("") - for change in report.cardinality_changes: - lines.append(f"- {change}") - lines.append("") - - return "\n".join(lines) diff --git a/src/basic_memory/mcp/server.py b/src/basic_memory/mcp/server.py index c6927e351..42de14fe8 100644 --- a/src/basic_memory/mcp/server.py +++ b/src/basic_memory/mcp/server.py @@ -31,21 +31,16 @@ POSIX_TOOLS_TAG = "posix" -# bm_project is registered twice under one name (#1832): a version without the -# delete command and one with it. Exactly one is visible, so tools/list never -# shows both, and calls route to the visible one. -BM_PROJECT_TOOL_KEY = "tool:bm_project@core" -BM_PROJECT_WITH_DELETE_TOOL_KEY = "tool:bm_project@with-delete" +PROJECT_DELETE_TAG = "project-delete" def set_project_delete_visibility(server: FastMCP, enabled: bool) -> None: - """Show the bm_project variant with or without the delete command. + """Show or hide bm_project_delete (#1832). - Like set_posix_tools_visibility, the last marks appended win, so this is safe + Like set_posix_tools_visibility, the last mark appended wins, so this is safe to call at import, at each lifespan start, and in tests. """ - server.add_transform(Visibility(enabled, keys={BM_PROJECT_WITH_DELETE_TOOL_KEY})) - server.add_transform(Visibility(not enabled, keys={BM_PROJECT_TOOL_KEY})) + server.add_transform(Visibility(enabled, tags={PROJECT_DELETE_TAG})) def set_posix_tools_visibility(server: FastMCP, enabled: bool) -> None: @@ -130,7 +125,7 @@ async def lifespan(app: FastMCP): set_posix_tools_visibility(app, config.enable_posix_tools) # Trigger: the enable_project_delete config flag (off by default). # Why: deleting a project removes it for every client; only the user turns it on. - # Outcome: bm_project lists a delete command, and is marked destructive, only then. + # Outcome: bm_project_delete is listed only then. set_project_delete_visibility(app, config.enable_project_delete) standalone_redis_url = None if container.mode.is_cloud else config.redis_url diff --git a/src/basic_memory/mcp/tools/__init__.py b/src/basic_memory/mcp/tools/__init__.py index 89af7b9e0..e2dc0dfdf 100644 --- a/src/basic_memory/mcp/tools/__init__.py +++ b/src/basic_memory/mcp/tools/__init__.py @@ -46,8 +46,7 @@ from basic_memory.mcp.tools.move import bm_move from basic_memory.mcp.tools.note_schemas import bm_schema -# Importing projects registers both bm_project variants (core and with-delete). -from basic_memory.mcp.tools.projects import bm_project +from basic_memory.mcp.tools.projects import bm_project, bm_project_delete from basic_memory.mcp.tools.ranked_search import bm_search from basic_memory.mcp.tools.read import bm_read from basic_memory.mcp.tools.write import bm_write @@ -61,6 +60,7 @@ "bm_list", "bm_move", "bm_project", + "bm_project_delete", "bm_read", "bm_schema", "bm_search", diff --git a/src/basic_memory/mcp/tools/note_schemas.py b/src/basic_memory/mcp/tools/note_schemas.py index 063e1f70e..23a804f16 100644 --- a/src/basic_memory/mcp/tools/note_schemas.py +++ b/src/basic_memory/mcp/tools/note_schemas.py @@ -1,27 +1,25 @@ """bm_schema: validate notes against their schemas, infer schemas, find drift (#1832). -Replaces schema_validate, schema_infer and schema_diff (SPEC-35.2). It calls the -schema API through the typed SchemaClient, as they do, and shares their report -formatting; what differs is that "nothing to report" cases are refusals (C11), not -success payloads describing a failure. +Replaces schema_validate, schema_infer and schema_diff (SPEC-35.2). Each command +delegates to the implementation of the tool it replaces; this tool gives them the +1.0 name, one `command` parameter and the shared parameter types. """ from typing import Annotated, Any, Literal from fastmcp import Context -from fastmcp.exceptions import ToolError from pydantic import AliasChoices, Field -from basic_memory.mcp.clients.schema import SchemaClient -from basic_memory.mcp.note_targets import open_project_target from basic_memory.mcp.refusals import refusal -from basic_memory.mcp.schema_reports import ( - format_drift_report, - format_inference_report, - format_validation_report, -) from basic_memory.mcp.server import mcp -from basic_memory.mcp.tool_params import OutputFormat, ProjectParam +from basic_memory.mcp.tool_params import ( + OutputFormat, + ProjectParam, + parse_project, + routing_arguments, +) +from basic_memory.mcp.tools.schema import schema_diff, schema_infer, schema_validate +from basic_memory.schemas.schema import ValidationReport type SchemaCommand = Literal["validate", "infer", "diff"] @@ -74,112 +72,44 @@ async def bm_schema( output_format: OutputFormat = "text", project: ProjectParam = None, context: Context | None = None, -) -> str | dict[str, Any]: +) -> ValidationReport | str | dict[str, Any]: """Validate, infer or diff note schemas.""" - if command != "validate" and identifier is not None: + project_name, project_id = routing_arguments(parse_project(project)) + if command == "validate": + return await schema_validate( + note_type=note_type, + identifier=identifier, + project=project_name, + project_id=project_id, + output_format=output_format, + context=context, + ) + if identifier is not None: raise refusal( "INVALID_ARGUMENTS", f"{command} works on a note type, not one note; give `note_type`.", output_format=output_format, ) - - # A note identifier routes like every bm_* target; otherwise only `project` does. - async with open_project_target( - identifier or "/", project, context, output_format=output_format - ) as target: - schema_client = SchemaClient(target.client, target.project.external_id) - if command == "validate": - note = target.route.path if identifier is not None else None - return await _validate(schema_client, note_type, note, output_format) - if note_type is None: - raise refusal( - "INVALID_ARGUMENTS", - f"{command} needs `note_type`, the frontmatter type to check.", - try_instead="bm_find(filters={'type': ...}) to see which types exist", - output_format=output_format, - ) - if command == "infer": - return await _infer(schema_client, note_type, threshold, output_format) - return await _diff(schema_client, note_type, output_format) - - -def _no_schema(note_type: str, output_format: OutputFormat) -> ToolError: - return refusal( - "NOT_FOUND", - f"No schema note describes type '{note_type}'.", - try_instead=( - f"bm_schema(command='infer', note_type='{note_type}'), then bm_write the " - "suggestion as a note with type: schema" - ), - output_format=output_format, - ) - - -async def _validate( - schema_client: SchemaClient, - note_type: str | None, - identifier: str | None, - output_format: OutputFormat, -) -> str | dict[str, Any]: - report = await schema_client.validate(note_type=note_type, identifier=identifier) - # Trigger: neither note_type nor identifier (every type that has a schema, #1013). - # Why: an empty report then means no schemas exist, not a missing note type. - if note_type is None and identifier is None: - if not report.type_summaries: - raise refusal( - "NOT_FOUND", - "This project has no schema notes, so there is nothing to validate.", - try_instead="bm_schema(command='infer', note_type=...) to draft one", - output_format=output_format, - ) - else: - checked_type = note_type or report.note_type or identifier or "" - if report.total_entities == 0: - raise refusal( - "NOT_FOUND", - f"No notes of type '{checked_type}' in this project.", - try_instead="bm_find(filters={'type': ...}) to see which types exist", - output_format=output_format, - ) - # Notes exist, but none were validated: no schema applies to them. - if report.total_notes == 0: - raise _no_schema(checked_type, output_format) - if output_format == "json": - return report.model_dump(mode="json", exclude_none=True) - return format_validation_report(report) - - -async def _infer( - schema_client: SchemaClient, note_type: str, threshold: float, output_format: OutputFormat -) -> str | dict[str, Any]: - report = await schema_client.infer(note_type, threshold=threshold) - if report.notes_analyzed == 0: + if note_type is None: raise refusal( - "NOT_FOUND", - f"No notes of type '{note_type}' in this project.", + "INVALID_ARGUMENTS", + f"{command} needs `note_type`, the frontmatter type to check.", try_instead="bm_find(filters={'type': ...}) to see which types exist", output_format=output_format, ) - # Every field fell below the threshold: the notes share no structure to suggest. - if not report.suggested_schema: - raise refusal( - "NOT_FOUND", - f"No field appears in {threshold:.0%} of the {report.notes_analyzed} " - f"'{note_type}' notes, so there is no schema to suggest.", - try_instead=f"bm_schema(command='infer', note_type='{note_type}', threshold=0.1)", + if command == "infer": + return await schema_infer( + note_type=note_type, + threshold=threshold, + project=project_name, + project_id=project_id, output_format=output_format, + context=context, ) - if output_format == "json": - return report.model_dump(mode="json", exclude_none=True) - return format_inference_report(report) - - -async def _diff( - schema_client: SchemaClient, note_type: str, output_format: OutputFormat -) -> str | dict[str, Any]: - report = await schema_client.diff(note_type) - if not report.schema_found: - raise _no_schema(note_type, output_format) - if output_format == "json": - return report.model_dump(mode="json", exclude_none=True) - return format_drift_report(report) + return await schema_diff( + note_type=note_type, + project=project_name, + project_id=project_id, + output_format=output_format, + context=context, + ) diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 16a016484..7c796f335 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -28,6 +28,7 @@ ensure_workspace_project_index, resolve_workspace_parameter, ) +from basic_memory.mcp.refusals import refusal from basic_memory.mcp.server import mcp from basic_memory.schemas.project_info import ProjectInfoRequest, ProjectItem, ProjectList from basic_memory.utils import generate_permalink @@ -585,23 +586,17 @@ async def create_memory_project( # Trigger: MCP server is constrained to a single project. # Why: constrained sessions cannot create projects, and workspace selectors # may be invalid or unavailable in that locked context. - # Outcome: return the existing disabled response before opening a routed client. + # Outcome: an UNSUPPORTED refusal before opening a routed client; it used to + # return as a success describing the failure (#1813). constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT") if constrained_project: - if output_format == "json": - return { - "name": project_name, - "path": project_path, - "is_default": False, - "created": False, - "already_exists": False, - "error": "PROJECT_CONSTRAINED", - "message": ( - f"Project creation disabled - MCP server is constrained to project " - f"'{constrained_project}'." - ), - } - return f'# Error\n\nProject creation disabled - MCP server is constrained to project \'{constrained_project}\'.\nUse the CLI to create projects: `basic-memory project add "{project_name}" "{project_path}"`' + raise refusal( + "UNSUPPORTED", + f"Project creation disabled - MCP server is constrained to project " + f"'{constrained_project}'.", + try_instead=f'the CLI: basic-memory project add "{project_name}" "{project_path}"', + output_format=output_format, + ) workspace_id = await _resolve_workspace_routing(workspace, context) @@ -824,10 +819,16 @@ async def delete_project( # Trigger: MCP server is constrained to a single project. # Why: constrained sessions cannot delete projects, and workspace selectors # may be invalid or unavailable in that locked context. - # Outcome: return the existing disabled message before opening a routed client. + # Outcome: an UNSUPPORTED refusal before opening a routed client; it used to + # return as a success describing the failure (#1813). constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT") if constrained_project: - return f"# Error\n\nProject deletion disabled - MCP server is constrained to project '{constrained_project}'.\nUse the CLI to delete projects: `basic-memory project remove \"{project_name}\"`" + raise refusal( + "UNSUPPORTED", + f"Project deletion disabled - MCP server is constrained to project " + f"'{constrained_project}'.", + try_instead=f'the CLI: basic-memory project remove "{project_name}"', + ) workspace_id = await _resolve_workspace_routing(workspace, context) async with get_client(workspace=workspace_id) as client: diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index 620f70bac..49a937462 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -1,23 +1,22 @@ -"""bm_project: projects and workspaces (SPEC-35.2, #1832). +"""bm_project and bm_project_delete: projects and workspaces (SPEC-35.2, #1832). -Replaces list_memory_projects (which already groups projects by workspace), -create_memory_project, recent_activity and, when enabled, delete_project. Each -command delegates to the implementation of the tool it replaces; this module only -gives them one name, one `command` parameter and the shared parameter types. +bm_project replaces list_memory_projects (which already groups projects by +workspace), create_memory_project and recent_activity. bm_project_delete replaces +delete_project, as its own tool so bm_project never needs a destructive annotation. +It is hidden unless the enable_project_delete setting turns it on (see +mcp.server.set_project_delete_visibility). -The tool is registered twice under one name: `core` without the delete command and -`with-delete` with it. The composition root shows one of the two from the -enable_project_delete setting (see mcp.server.set_project_delete_visibility). +Each command delegates to the implementation of the tool it replaces; these tools +give them the 1.0 names, one `command` parameter and the shared parameter types. """ -import os from typing import Annotated, Any, Literal from fastmcp import Context from pydantic import AliasChoices, Field from basic_memory.mcp.refusals import refusal -from basic_memory.mcp.server import mcp, set_project_delete_visibility +from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp, set_project_delete_visibility from basic_memory.mcp.tool_params import ( Items, OutputFormat, @@ -36,44 +35,21 @@ from basic_memory.mcp.tools.recent_activity import recent_activity type ProjectCommand = Literal["list", "create", "recent"] -type ProjectCommandWithDelete = Literal["list", "create", "recent", "delete"] -_DESCRIPTION = ( - "Basic Memory projects. `command`: list (projects, grouped by workspace); create " - "(`name`, `path`, optional `set_default`, `workspace`); recent (what changed lately: " - "`since`, `items`, paging; omit `project` to see every project)." -) - -# --- Parameters --- - -NewProjectName = Annotated[ - str | None, - Field( - min_length=1, - validation_alias=AliasChoices("name", "project_name"), - description="For create and delete: the project's name.", - ), -] -NewProjectPath = Annotated[ - str | None, - Field( - min_length=1, - validation_alias=AliasChoices("path", "project_path"), - description="For create: the folder that holds the project's notes.", - ), -] -SetDefault = Annotated[bool, Field(description="For create: make the new project the default.")] Workspace = Annotated[ str | None, - Field(description="For create and delete in Cloud: the workspace slug, name or id."), + Field(description="In Cloud: the workspace slug, name or id that holds the project."), ] @mcp.tool( name="bm_project", - version="core", title="Projects", - description=_DESCRIPTION, + description=( + "Basic Memory projects. `command`: list (projects, grouped by workspace); create " + "(`name`, `path`, optional `set_default`, `workspace`); recent (what changed " + "lately: `since`, `items`, paging; omit `project` to see every project)." + ), tags={"projects"}, annotations={ "title": "Projects", @@ -85,62 +61,26 @@ ) async def bm_project( command: Annotated[ProjectCommand, Field(description="What to do.")], - name: NewProjectName = None, - path: NewProjectPath = None, - set_default: SetDefault = False, - workspace: Workspace = None, - since: Since = "7d", - items: Items = None, - page: Page = 1, - page_size: PageSize = 10, - output_format: OutputFormat = "text", - project: ProjectParam = None, - context: Context | None = None, -) -> str | dict[str, Any] | list[dict[str, Any]]: - """List, create, or show recent activity in projects.""" - return await _run_project_command( - command, - name=name, - path=path, - set_default=set_default, - workspace=workspace, - delete_notes=False, - since=since, - items=items, - page=page, - page_size=page_size, - output_format=output_format, - project=project, - context=context, - ) - - -@mcp.tool( - name="bm_project", - version="with-delete", - title="Projects", - description=( - _DESCRIPTION + " delete (`name`, `delete_notes`, `workspace`) removes a project; with " - "delete_notes=true its files go too. This cannot be undone." - ), - tags={"projects"}, - annotations={ - "title": "Projects", - "readOnlyHint": False, - "destructiveHint": True, - "idempotentHint": False, - "openWorldHint": False, - }, -) -async def bm_project_with_delete( - command: Annotated[ProjectCommandWithDelete, Field(description="What to do.")], - name: NewProjectName = None, - path: NewProjectPath = None, - set_default: SetDefault = False, - workspace: Workspace = None, - delete_notes: Annotated[ - bool, Field(description="For delete: also delete the project's files.") + name: Annotated[ + str | None, + Field( + min_length=1, + validation_alias=AliasChoices("name", "project_name"), + description="For create: the new project's name.", + ), + ] = None, + path: Annotated[ + str | None, + Field( + min_length=1, + validation_alias=AliasChoices("path", "project_path"), + description="For create: the folder that holds the project's notes.", + ), + ] = None, + set_default: Annotated[ + bool, Field(description="For create: make the new project the default.") ] = False, + workspace: Workspace = None, since: Since = "7d", items: Items = None, page: Page = 1, @@ -149,60 +89,7 @@ async def bm_project_with_delete( project: ProjectParam = None, context: Context | None = None, ) -> str | dict[str, Any] | list[dict[str, Any]]: - """List, create, delete, or show recent activity in projects.""" - return await _run_project_command( - command, - name=name, - path=path, - set_default=set_default, - workspace=workspace, - delete_notes=delete_notes, - since=since, - items=items, - page=page, - page_size=page_size, - output_format=output_format, - project=project, - context=context, - ) - - -# Hidden until the composition root reads enable_project_delete at startup. -set_project_delete_visibility(mcp, False) - - -async def _run_project_command( - command: ProjectCommandWithDelete, - *, - name: str | None, - path: str | None, - set_default: bool, - workspace: str | None, - delete_notes: bool, - since: str, - items: list[Literal["note", "observation", "relation"]] | None, - page: int, - page_size: int, - output_format: OutputFormat, - project: str | None, - context: Context | None, -) -> str | dict[str, Any] | list[dict[str, Any]]: - """Check the arguments a command takes, then run the tool it replaces.""" - # Trigger: the server is constrained to one project (BASIC_MEMORY_MCP_PROJECT). - # Why: such a session serves that project only; adding or removing projects - # belongs to whoever configured it. The replaced tools answered this - # with a success payload describing the failure (C11). - # Outcome: an UNSUPPORTED refusal that names the CLI command instead. - constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT") - if constrained_project and command in ("create", "delete"): - cli = "add" if command == "create" else "remove" - raise refusal( - "UNSUPPORTED", - f"This MCP server is constrained to project '{constrained_project}', so it " - f"cannot {command} projects.", - try_instead=f"the CLI: basic-memory project {cli} ...", - output_format=output_format, - ) + """List or create projects, or show what changed in them.""" match command: case "list": return await list_memory_projects(output_format=output_format, context=context) @@ -235,17 +122,44 @@ async def _run_project_command( output_format=output_format, context=context, ) - case "delete": - if name is None: - raise refusal( - "INVALID_ARGUMENTS", - "delete needs `name`, the project to delete.", - try_instead="bm_project(command='list') to see project names", - output_format=output_format, - ) - return await delete_project( - project_name=name, - delete_notes=delete_notes, - workspace=workspace, - context=context, - ) + + +@mcp.tool( + name="bm_project_delete", + title="Delete project", + description=( + "Remove a Basic Memory project. Its files stay on disk unless `delete_notes=true`; " + "a Cloud project's files are always deleted. This cannot be undone." + ), + tags={"projects", PROJECT_DELETE_TAG}, + annotations={ + "title": "Delete project", + "readOnlyHint": False, + "destructiveHint": True, + "idempotentHint": False, + "openWorldHint": False, + }, +) +async def bm_project_delete( + name: Annotated[ + str, + Field( + min_length=1, + validation_alias=AliasChoices("name", "project_name"), + description="The project to delete, as bm_project(command='list') names it.", + ), + ], + delete_notes: Annotated[ + bool, Field(description="Also delete the project's note files.") + ] = False, + workspace: Workspace = None, + context: Context | None = None, +) -> str: + """Delete one project.""" + return await delete_project( + project_name=name, delete_notes=delete_notes, workspace=workspace, context=context + ) + + +# Hidden until the composition root reads enable_project_delete at startup. +set_project_delete_visibility(mcp, False) diff --git a/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index 085c3bbd2..967b2a88a 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -8,15 +8,169 @@ from loguru import logger from fastmcp import Context +from fastmcp.exceptions import ToolError from basic_memory.mcp.project_context import get_project_client -from basic_memory.mcp.schema_reports import ( - format_drift_report, - format_inference_report, - format_validation_report, -) +from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.tool_params import OutputFormat from basic_memory.mcp.server import mcp -from basic_memory.schemas.schema import ValidationReport +from basic_memory.schemas.schema import DriftReport, InferenceReport, ValidationReport + + +def _format_validation_report(report: ValidationReport) -> str: + """Render a ValidationReport as readable markdown. + + Produces output the LLM can display directly instead of trying to + interpret raw JSON, which leads to "undefined — invalid" rendering. + """ + lines: list[str] = [] + + # --- Header --- + type_label = report.note_type or "all" + lines.append(f"# Schema Validation: {type_label}") + lines.append("") + lines.append( + f"Notes: {report.total_notes} | Valid: {report.valid_count} " + f"| Warnings: {report.warning_count} | Errors: {report.error_count}" + ) + lines.append("") + + # --- Per-type breakdown (all-types mode) --- + if report.type_summaries: + lines.append("## By Type") + lines.append("") + for summary in report.type_summaries: + if summary.total_entities == 0: + lines.append(f"- **{summary.note_type}**: no notes") + else: + lines.append( + f"- **{summary.note_type}**: {summary.valid_count}/{summary.total_notes} valid" + ) + lines.append("") + + # --- Per-note results --- + for r in report.results: + status = "valid" if r.passed else "INVALID" + lines.append(f"- **{r.note_identifier}** — {status}") + for w in r.warnings: + lines.append(f" - warning: {w}") + for e in r.errors: + lines.append(f" - error: {e}") + + return "\n".join(lines) + + +def _format_inference_report(report: InferenceReport) -> str: + """Render an InferenceReport as readable markdown. + + Without this formatter the LLM receives raw JSON and renders + field names as "undefined". + """ + lines: list[str] = [] + + # --- Header --- + lines.append(f"# Schema Inference: {report.note_type}") + lines.append("") + lines.append(f"Notes analyzed: {report.notes_analyzed}") + lines.append("") + + # --- Suggested schema YAML --- + if report.suggested_schema: + lines.append("## Suggested Schema") + lines.append("") + lines.append("```yaml") + lines.append("---") + lines.append(f"title: {report.note_type.title()}") + lines.append("type: schema") + lines.append(f"entity: {report.note_type}") + lines.append("version: 1") + lines.append("schema:") + for field_name, field_def in report.suggested_schema.items(): + lines.append(f" {field_name}: {field_def}") + lines.append("---") + lines.append("```") + lines.append("") + + # --- Field frequency table --- + if report.field_frequencies: + lines.append("## Field Frequencies") + lines.append("") + for f in report.field_frequencies: + pct = f"{f.percentage:.0%}" + req_marker = "required" if f.name in report.suggested_required else "optional" + samples = ", ".join(f.sample_values[:3]) if f.sample_values else "" + sample_str = f" (e.g. {samples})" if samples else "" + lines.append( + f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total}) " + f"[{req_marker}]{sample_str}" + ) + lines.append("") + + # --- Excluded fields --- + if report.excluded: + lines.append("## Excluded (below threshold)") + lines.append("") + for name in report.excluded: + lines.append(f"- {name}") + lines.append("") + + return "\n".join(lines) + + +def _format_drift_report(report: DriftReport) -> str: + """Render a DriftReport as readable markdown. + + Without this formatter the LLM receives raw JSON and renders + field names as "undefined". + """ + lines: list[str] = [] + + # --- Header --- + lines.append(f"# Schema Drift: {report.note_type}") + lines.append("") + + has_drift = report.new_fields or report.dropped_fields or report.cardinality_changes + + if not has_drift: + lines.append("No drift detected — schema matches actual usage.") + return "\n".join(lines) + + # --- New fields --- + if report.new_fields: + lines.append("## New Fields (in notes but not in schema)") + lines.append("") + for f in report.new_fields: + pct = f"{f.percentage:.0%}" + lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") + lines.append("") + + # --- Dropped fields --- + if report.dropped_fields: + lines.append("## Dropped Fields (in schema but rare in notes)") + lines.append("") + for f in report.dropped_fields: + pct = f"{f.percentage:.0%}" + lines.append(f"- **{f.name}** ({f.source}) — {pct} ({f.count}/{f.total})") + lines.append("") + + # --- Cardinality changes --- + if report.cardinality_changes: + lines.append("## Cardinality Changes") + lines.append("") + for change in report.cardinality_changes: + lines.append(f"- {change}") + lines.append("") + + return "\n".join(lines) + + +def _nothing_to_report(output_format: OutputFormat, message: str, guidance: str) -> ToolError: + """A NOT_FOUND refusal: the short message in JSON, the full guidance as text (C11). + + These cases used to return as successful results describing a failure (#1813). + """ + text = message if output_format == "json" else guidance + return refusal("NOT_FOUND", text, output_format=output_format) def _no_notes_guidance(note_type: str, tool_name: str) -> str: @@ -170,72 +324,64 @@ async def schema_validate( f"note_type={note_type} identifier={identifier}" ) - try: - from basic_memory.mcp.clients.schema import SchemaClient - - schema_client = SchemaClient(client, active_project.external_id) - result = await schema_client.validate( - note_type=note_type, - identifier=identifier, - ) + from basic_memory.mcp.clients.schema import SchemaClient - logger.debug( - f"MCP tool response: tool=schema_validate project={active_project.name} " - f"total={result.total_notes} valid={result.valid_count} " - f"warnings={result.warning_count} errors={result.error_count}" - ) + schema_client = SchemaClient(client, active_project.external_id) + result = await schema_client.validate( + note_type=note_type, + identifier=identifier, + ) - # --- All-types mode --- - # Trigger: called with neither identifier nor note_type (#1013) - # Why: an empty report here means "no schemas defined", not - # "no notes of type 'unknown'" — the guards below would mislead - # Outcome: per-type summary, or guidance for defining a first schema - if note_type is None and identifier is None: - if not result.type_summaries: - if output_format == "json": - return {"error": "No schemas defined in this project"} - return _no_schemas_defined_guidance("schema_validate") - if output_format == "json": - return result.model_dump(mode="json", exclude_none=True) - return format_validation_report(result) - - # --- No notes guard --- - # Trigger: no entities of this type exist in the project - # Why: can't validate notes that don't exist yet - # Outcome: return guidance on creating notes of this type - effective_type = note_type or result.note_type or "unknown" - if result.total_entities == 0: - if output_format == "json": - return {"error": f"No notes found of type '{effective_type}'"} - return _no_notes_guidance(effective_type, "schema_validate") - - # --- No schema guard --- - # Trigger: entities exist but none were validated (no schema found) - # Why: notes of this type exist but no schema was found, so none were validated - # Outcome: return guidance on how to create a schema - if result.total_notes == 0: - if output_format == "json": - return {"error": f"No schema found for type '{effective_type}'"} - return _no_schema_guidance(effective_type, "schema_validate") + logger.debug( + f"MCP tool response: tool=schema_validate project={active_project.name} " + f"total={result.total_notes} valid={result.valid_count} " + f"warnings={result.warning_count} errors={result.error_count}" + ) + # --- All-types mode --- + # Trigger: called with neither identifier nor note_type (#1013) + # Why: an empty report here means "no schemas defined", not + # "no notes of type 'unknown'" — the guards below would mislead + # Outcome: per-type summary, or guidance for defining a first schema + if note_type is None and identifier is None: + if not result.type_summaries: + raise _nothing_to_report( + output_format, + "No schemas defined in this project", + _no_schemas_defined_guidance("schema_validate"), + ) if output_format == "json": return result.model_dump(mode="json", exclude_none=True) + return _format_validation_report(result) + + # --- No notes guard --- + # Trigger: no entities of this type exist in the project + # Why: can't validate notes that don't exist yet + # Outcome: a NOT_FOUND refusal with guidance on creating notes of this type + effective_type = note_type or result.note_type or "unknown" + if result.total_entities == 0: + raise _nothing_to_report( + output_format, + f"No notes found of type '{effective_type}'", + _no_notes_guidance(effective_type, "schema_validate"), + ) - return format_validation_report(result) - - except Exception as e: - logger.error(f"Schema validation failed: {e}, project: {active_project.name}") - if output_format == "json": - return {"error": f"Schema validation failed: {e}"} - return ( - f"# Schema Validation Failed\n\n" - f"Error validating schemas: {e}\n\n" - f"## Troubleshooting\n" - f"1. Ensure schema notes exist (type: schema) for the target note type\n" - f"2. Check that notes have the correct type in frontmatter\n" - f"3. Verify the project has been indexed: `basic-memory status`\n" + # --- No schema guard --- + # Trigger: entities exist but none were validated (no schema found) + # Why: notes of this type exist but no schema was found, so none were validated + # Outcome: a NOT_FOUND refusal with guidance on how to create a schema + if result.total_notes == 0: + raise _nothing_to_report( + output_format, + f"No schema found for type '{effective_type}'", + _no_schema_guidance(effective_type, "schema_validate"), ) + if output_format == "json": + return result.model_dump(mode="json", exclude_none=True) + + return _format_validation_report(result) + @mcp.tool( title="Infer Schema", @@ -306,66 +452,47 @@ async def schema_infer( f"note_type={note_type} threshold={threshold}" ) - try: - from basic_memory.mcp.clients.schema import SchemaClient + from basic_memory.mcp.clients.schema import SchemaClient - schema_client = SchemaClient(client, active_project.external_id) - result = await schema_client.infer(note_type, threshold=threshold) + schema_client = SchemaClient(client, active_project.external_id) + result = await schema_client.infer(note_type, threshold=threshold) - logger.debug( - f"MCP tool response: tool=schema_infer project={active_project.name} " - f"note_type={note_type} notes_analyzed={result.notes_analyzed} " - f"required={len(result.suggested_required)} " - f"optional={len(result.suggested_optional)}" - ) - - # --- Empty schema guard --- - # Trigger: notes were analyzed but no fields met the threshold - # Why: returning hundreds of excluded fields overwhelms the LLM context - # Outcome: return actionable guidance instead of a massive empty result - if result.notes_analyzed > 0 and not result.suggested_schema: - if output_format == "json": - return { - "error": ( - f"No schema pattern found for '{note_type}' " - f"(threshold: {threshold:.0%})" - ) - } - return ( - f"# No Schema Pattern Found\n\n" - f"Analyzed {result.notes_analyzed} notes of type '{note_type}', " - f"but no observation or relation appeared in enough notes to suggest " - f"a schema (threshold: {threshold:.0%}).\n\n" - f"This usually means '{note_type}' is too broad — the notes don't " - f"share a consistent structure.\n\n" - f"## Suggestions\n" - f"1. **Use a more specific type** — try `search_notes` with " - f"`note_types` filter to see what types exist\n" - f"2. **Lower the threshold** — " - f'`schema_infer("{note_type}", threshold=0.1)` to include ' - f"rarer fields\n" - f"3. **Create typed notes** — use `write_note` with a specific " - f'`note_type` (e.g., "person", "meeting") to build consistent ' - f"structure\n" - ) + logger.debug( + f"MCP tool response: tool=schema_infer project={active_project.name} " + f"note_type={note_type} notes_analyzed={result.notes_analyzed} " + f"required={len(result.suggested_required)} " + f"optional={len(result.suggested_optional)}" + ) - if output_format == "json": - return result.model_dump(mode="json", exclude_none=True) + # --- Empty schema guard --- + # Trigger: notes were analyzed but no fields met the threshold + # Why: returning hundreds of excluded fields overwhelms the LLM context + # Outcome: a NOT_FOUND refusal with guidance instead of a massive empty result + if result.notes_analyzed > 0 and not result.suggested_schema: + raise _nothing_to_report( + output_format, + f"No schema pattern found for '{note_type}' (threshold: {threshold:.0%})", + f"# No Schema Pattern Found\n\n" + f"Analyzed {result.notes_analyzed} notes of type '{note_type}', " + f"but no observation or relation appeared in enough notes to suggest " + f"a schema (threshold: {threshold:.0%}).\n\n" + f"This usually means '{note_type}' is too broad — the notes don't " + f"share a consistent structure.\n\n" + f"## Suggestions\n" + f"1. **Use a more specific type** — try `search_notes` with " + f"`note_types` filter to see what types exist\n" + f"2. **Lower the threshold** — " + f'`schema_infer("{note_type}", threshold=0.1)` to include ' + f"rarer fields\n" + f"3. **Create typed notes** — use `write_note` with a specific " + f'`note_type` (e.g., "person", "meeting") to build consistent ' + f"structure\n", + ) - return format_inference_report(result) + if output_format == "json": + return result.model_dump(mode="json", exclude_none=True) - except Exception as e: - logger.error(f"Schema inference failed: {e}, project: {active_project.name}") - if output_format == "json": - return {"error": f"Schema inference failed: {e}"} - return ( - f"# Schema Inference Failed\n\n" - f"Error inferring schema for type '{note_type}': {e}\n\n" - f"## Troubleshooting\n" - f"1. Ensure notes of type '{note_type}' exist in the project\n" - f'2. Try searching: `search_notes("{note_type}", note_types=["{note_type}"])`\n' - f"3. Verify the project has been indexed: `basic-memory status`\n" - ) + return _format_inference_report(result) @mcp.tool( @@ -430,43 +557,31 @@ async def schema_diff( f"MCP tool call tool=schema_diff project={active_project.name} note_type={note_type}" ) - try: - from basic_memory.mcp.clients.schema import SchemaClient + from basic_memory.mcp.clients.schema import SchemaClient - schema_client = SchemaClient(client, active_project.external_id) - result = await schema_client.diff(note_type) + schema_client = SchemaClient(client, active_project.external_id) + result = await schema_client.diff(note_type) - logger.debug( - f"MCP tool response: tool=schema_diff project={active_project.name} " - f"note_type={note_type} schema_found={result.schema_found} " - f"new_fields={len(result.new_fields)} " - f"dropped_fields={len(result.dropped_fields)} " - f"cardinality_changes={len(result.cardinality_changes)}" - ) - - # --- No schema guard --- - # Trigger: API reports no schema was found for this type - # Why: diff requires a schema to compare against - # Outcome: return guidance on how to create a schema - if not result.schema_found: - if output_format == "json": - return {"error": f"No schema found for type '{note_type}'"} - return _no_schema_guidance(note_type, "schema_diff") + logger.debug( + f"MCP tool response: tool=schema_diff project={active_project.name} " + f"note_type={note_type} schema_found={result.schema_found} " + f"new_fields={len(result.new_fields)} " + f"dropped_fields={len(result.dropped_fields)} " + f"cardinality_changes={len(result.cardinality_changes)}" + ) - if output_format == "json": - return result.model_dump(mode="json", exclude_none=True) + # --- No schema guard --- + # Trigger: API reports no schema was found for this type + # Why: diff requires a schema to compare against + # Outcome: a NOT_FOUND refusal with guidance on how to create a schema + if not result.schema_found: + raise _nothing_to_report( + output_format, + f"No schema found for type '{note_type}'", + _no_schema_guidance(note_type, "schema_diff"), + ) - return format_drift_report(result) + if output_format == "json": + return result.model_dump(mode="json", exclude_none=True) - except Exception as e: - logger.error(f"Schema diff failed: {e}, project: {active_project.name}") - if output_format == "json": - return {"error": f"Schema diff failed: {e}"} - return ( - f"# Schema Diff Failed\n\n" - f"Error detecting drift for type '{note_type}': {e}\n\n" - f"## Troubleshooting\n" - f"1. Ensure a schema note exists for type '{note_type}'\n" - f"2. Ensure notes of type '{note_type}' exist in the project\n" - f"3. Verify the project has been indexed: `basic-memory status`\n" - ) + return _format_drift_report(result) diff --git a/test-int/mcp/test_single_project_mcp_integration.py b/test-int/mcp/test_single_project_mcp_integration.py index e2781cabe..34801892b 100644 --- a/test-int/mcp/test_single_project_mcp_integration.py +++ b/test-int/mcp/test_single_project_mcp_integration.py @@ -163,16 +163,14 @@ async def test_create_project_disabled_in_constrained_mode(mcp_server, app, test result = await client.call_tool( "create_memory_project", {"project_name": "new-project", "project_path": "/tmp/new-project"}, + raise_on_error=False, ) - assert len(result.content) == 1 + # A refusal is a tool error (#1813), and it still names the way forward. + assert result.is_error response_text = result.content[0].text # pyright: ignore [reportAttributeAccessIssue] - - # Should show error message - assert "# Error" in response_text - assert "Project creation disabled" in response_text + assert response_text.startswith("UNSUPPORTED: Project creation disabled") assert f"constrained to project '{test_project.name}'" in response_text - assert "Use the CLI to create projects:" in response_text assert 'basic-memory project add "new-project" "/tmp/new-project"' in response_text finally: @@ -189,16 +187,15 @@ async def test_delete_project_disabled_in_constrained_mode(mcp_server, app, test try: async with Client(mcp_server) as client: - result = await client.call_tool("delete_project", {"project_name": "some-project"}) + result = await client.call_tool( + "delete_project", {"project_name": "some-project"}, raise_on_error=False + ) - assert len(result.content) == 1 + # A refusal is a tool error (#1813), and it still names the way forward. + assert result.is_error response_text = result.content[0].text # pyright: ignore [reportAttributeAccessIssue] - - # Should show error message - assert "# Error" in response_text - assert "Project deletion disabled" in response_text + assert response_text.startswith("UNSUPPORTED: Project deletion disabled") assert f"constrained to project '{test_project.name}'" in response_text - assert "Use the CLI to delete projects:" in response_text assert 'basic-memory project remove "some-project"' in response_text finally: diff --git a/tests/cli/test_cli_schema.py b/tests/cli/test_cli_schema.py index e2de5af7b..447e5b8f4 100644 --- a/tests/cli/test_cli_schema.py +++ b/tests/cli/test_cli_schema.py @@ -5,9 +5,12 @@ from unittest.mock import AsyncMock, MagicMock, patch +import pytest from typer.testing import CliRunner +from basic_memory.cli.commands.schema import _run_schema_tool from basic_memory.cli.main import app as cli_app +from basic_memory.mcp.refusals import Refusal, refusal runner = CliRunner() @@ -300,3 +303,17 @@ def test_schema_routing_both_flags_error(): ) assert result.exit_code == 1 + + +def test_run_schema_tool_keeps_nothing_to_report_and_reraises_the_rest(): + """NOT_FOUND is "nothing to report" for the CLI; any other refusal still fails.""" + + async def nothing() -> None: + raise refusal("NOT_FOUND", "No schemas defined in this project", output_format="json") + + async def broken() -> None: + raise refusal("INVALID_ARGUMENTS", "bad", output_format="json") + + assert _run_schema_tool(nothing()) == {"error": "No schemas defined in this project"} + with pytest.raises(Refusal): + _run_schema_tool(broken()) diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 5737a3530..7b84c7f18 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -1,47 +1,40 @@ """bm_project and bm_schema: one name per group, commands delegate (#1832).""" -from typing import Any - import pytest from fastmcp.exceptions import ToolError from basic_memory.mcp.server import lifespan, mcp, set_project_delete_visibility -from basic_memory.mcp.tools import bm_project, bm_schema, bm_write -from basic_memory.mcp.tools.projects import bm_project_with_delete +from basic_memory.mcp.tools import bm_project, bm_project_delete, bm_schema, bm_write -async def _listed_bm_project() -> Any: +async def _listed_names() -> set[str]: # The server's own listing: entering a Client would run the lifespan, which - # re-applies the config flag this test sets directly. - (tool,) = [tool for tool in await mcp.list_tools() if tool.name == "bm_project"] - return tool + # re-applies the config flag these tests set directly. + return {tool.name for tool in await mcp.list_tools()} # --- Delete is opt-in --- @pytest.mark.asyncio -async def test_delete_is_hidden_by_default(): - tool = await _listed_bm_project() +async def test_project_delete_is_hidden_by_default(): + names = await _listed_names() - assert tool.parameters["properties"]["command"]["enum"] == ["list", "create", "recent"] - assert tool.annotations.destructive_hint is False + assert "bm_project" in names + assert "bm_project_delete" not in names @pytest.mark.asyncio -async def test_enabling_delete_swaps_in_the_destructive_variant(): - set_project_delete_visibility(mcp, True) - try: - tool = await _listed_bm_project() - finally: - set_project_delete_visibility(mcp, False) +async def test_bm_project_is_never_destructive(): + (tool,) = [tool for tool in await mcp.list_tools() if tool.name == "bm_project"] - assert "delete" in tool.parameters["properties"]["command"]["enum"] - assert tool.annotations.destructive_hint is True + assert tool.parameters["properties"]["command"]["enum"] == ["list", "create", "recent"] + assert tool.annotations is not None + assert tool.annotations.destructive_hint is False @pytest.mark.asyncio -async def test_config_flag_enables_delete_through_lifespan(config_manager): +async def test_config_flag_lists_project_delete_through_lifespan(config_manager): cfg = config_manager.load_config() assert cfg.enable_project_delete is False cfg.enable_project_delete = True @@ -49,11 +42,11 @@ async def test_config_flag_enables_delete_through_lifespan(config_manager): try: async with lifespan(mcp): - tool = await _listed_bm_project() + names = await _listed_names() finally: set_project_delete_visibility(mcp, False) - assert tool.annotations.destructive_hint is True + assert "bm_project_delete" in names # --- Commands --- @@ -72,7 +65,7 @@ async def test_create_and_delete(app, tmp_path_factory): project_root = tmp_path_factory.mktemp("bm-project-home") created = await bm_project(command="create", name="Scratch", path=str(project_root)) - deleted = await bm_project_with_delete(command="delete", name="Scratch") + deleted = await bm_project_delete(name="Scratch") assert isinstance(created, str) and created.startswith("✓") assert isinstance(deleted, str) and deleted.startswith("✓") @@ -116,18 +109,13 @@ async def test_project_argument_refusals(arguments, message): @pytest.mark.asyncio -@pytest.mark.parametrize("command", ["create", "delete"]) -async def test_constrained_server_refuses_project_changes(monkeypatch, command): +async def test_constrained_server_refuses_project_changes(monkeypatch): monkeypatch.setenv("BASIC_MEMORY_MCP_PROJECT", "only-this") - with pytest.raises(ToolError, match="^UNSUPPORTED: .*constrained to project 'only-this'"): - await bm_project_with_delete(command=command, name="x", path="/tmp/x") - - -@pytest.mark.asyncio -async def test_delete_needs_a_name(): - with pytest.raises(ToolError, match="^INVALID_ARGUMENTS: delete needs `name`"): - await bm_project_with_delete(command="delete") + with pytest.raises(ToolError, match="^UNSUPPORTED: Project creation disabled"): + await bm_project(command="create", name="x", path="/tmp/x") + with pytest.raises(ToolError, match="^UNSUPPORTED: Project deletion disabled"): + await bm_project_delete(name="x") # --- bm_schema --- @@ -148,14 +136,17 @@ async def test_schema_commands_delegate(client, test_project): assert isinstance(inferred, dict) and inferred["note_type"] == "person" assert inferred["suggested_schema"] - with pytest.raises(ToolError, match="^NOT_FOUND: No schema note describes type 'person'"): + # The replaced tools now refuse "nothing to report" instead of returning it (C11). + with pytest.raises(ToolError, match="^NOT_FOUND: # No Schema Found for 'person'"): await bm_schema(command="diff", note_type="person", project=test_project.name) - with pytest.raises(ToolError, match="^NOT_FOUND: No schema note describes type 'person'"): + with pytest.raises(ToolError, match="^NOT_FOUND: # No Schema Found for 'person'"): await bm_schema(command="validate", note_type="person", project=test_project.name) - with pytest.raises(ToolError, match="^NOT_FOUND: This project has no schema notes"): + with pytest.raises(ToolError, match="^NOT_FOUND: # No Schemas Defined"): await bm_schema(command="validate", project=test_project.name) - with pytest.raises(ToolError, match="^NOT_FOUND: No notes of type 'robot'"): - await bm_schema(command="validate", note_type="robot", project=test_project.name) + with pytest.raises(ToolError, match='"error": "NOT_FOUND"'): + await bm_schema( + command="validate", note_type="robot", output_format="json", project=test_project.name + ) PERSON_SCHEMA = ( @@ -192,12 +183,6 @@ async def test_schema_reports_once_a_schema_exists(client, test_project): assert isinstance(drift_text, str) and isinstance(inferred_text, str) -@pytest.mark.asyncio -async def test_infer_with_no_notes_of_the_type(client, test_project): - with pytest.raises(ToolError, match="^NOT_FOUND: No notes of type 'robot'"): - await bm_schema(command="infer", note_type="robot", project=test_project.name) - - @pytest.mark.asyncio async def test_infer_below_the_threshold(client, test_project): for name, category in (("ada", "role"), ("grace", "hobby"), ("alan", "pet")): @@ -207,7 +192,7 @@ async def test_infer_below_the_threshold(client, test_project): project=test_project.name, ) - with pytest.raises(ToolError, match="^NOT_FOUND: No field appears in 90%"): + with pytest.raises(ToolError, match="^NOT_FOUND: # No Schema Pattern Found"): await bm_schema( command="infer", note_type="person", threshold=0.9, project=test_project.name ) diff --git a/tests/mcp/test_tool_contracts.py b/tests/mcp/test_tool_contracts.py index a35552e2d..4b4084530 100644 --- a/tests/mcp/test_tool_contracts.py +++ b/tests/mcp/test_tool_contracts.py @@ -9,7 +9,6 @@ import pytest from basic_memory.mcp import tools -from basic_memory.mcp.tools.projects import bm_project_with_delete from basic_memory.mcp.server import mcp @@ -91,21 +90,7 @@ "output_format", "project", ], - # The same tool name with the delete command; shown only with enable_project_delete. - "bm_project_with_delete": [ - "command", - "name", - "path", - "set_default", - "workspace", - "delete_notes", - "since", - "items", - "page", - "page_size", - "output_format", - "project", - ], + "bm_project_delete": ["name", "delete_notes", "workspace"], "bm_schema": [ "command", "note_type", @@ -372,6 +357,8 @@ "ls": {"readOnlyHint": True, "destructiveHint": False}, "man": {"readOnlyHint": True, "destructiveHint": False}, "tail": {"readOnlyHint": True, "destructiveHint": False}, + # Listed only when enable_project_delete is on. + "bm_project_delete": {"readOnlyHint": False, "destructiveHint": True}, } EXPECTED_EDIT_NOTE_OPERATIONS = [ @@ -395,7 +382,7 @@ "bm_move": tools.bm_move, "bm_delete": tools.bm_delete, "bm_project": tools.bm_project, - "bm_project_with_delete": bm_project_with_delete, + "bm_project_delete": tools.bm_project_delete, "bm_schema": tools.bm_schema, "basic_memory_diagnostics": tools.basic_memory_diagnostics, "build_context": tools.build_context, diff --git a/tests/mcp/test_tool_project_management.py b/tests/mcp/test_tool_project_management.py index 630e0c7a6..e7df6ad5f 100644 --- a/tests/mcp/test_tool_project_management.py +++ b/tests/mcp/test_tool_project_management.py @@ -5,6 +5,7 @@ import httpx import pytest +from fastmcp.exceptions import ToolError from sqlalchemy import select from basic_memory import db @@ -482,7 +483,7 @@ async def fake_get_client(*, workspace=None, project_name=None): @pytest.mark.asyncio -async def test_create_memory_project_constrained_with_workspace_returns_disabled_message( +async def test_create_memory_project_constrained_with_workspace_refuses( monkeypatch, tmp_path_factory ): """A constrained MCP session rejects creation before resolving a workspace selector.""" @@ -500,15 +501,16 @@ async def test_create_memory_project_constrained_with_workspace_returns_disabled side_effect=RuntimeError("bad workspace"), ) as mock_resolve_workspace, ): - result = await create_memory_project( - project_name="Any Project", - project_path=str(project_root), - workspace="missing-team", - ) + with pytest.raises( + ToolError, match="^UNSUPPORTED: Project creation disabled.*'locked-project'" + ): + await create_memory_project( + project_name="Any Project", + project_path=str(project_root), + workspace="missing-team", + ) mock_resolve_workspace.assert_not_awaited() - assert "Project creation disabled" in result - assert "locked-project" in result @pytest.mark.asyncio @@ -757,7 +759,7 @@ def test_format_note_file_delete_result_reports_backend_status(status, cloud_rou @pytest.mark.asyncio -async def test_delete_project_constrained_with_workspace_returns_disabled_message(monkeypatch): +async def test_delete_project_constrained_with_workspace_refuses(monkeypatch): """A constrained MCP session rejects deletion before resolving a workspace selector.""" monkeypatch.setenv("BASIC_MEMORY_MCP_PROJECT", "locked-project") @@ -772,11 +774,12 @@ async def test_delete_project_constrained_with_workspace_returns_disabled_messag side_effect=RuntimeError("bad workspace"), ) as mock_resolve_workspace, ): - result = await delete_project("Any Project", workspace="missing-team") + with pytest.raises( + ToolError, match="^UNSUPPORTED: Project deletion disabled.*'locked-project'" + ): + await delete_project("Any Project", workspace="missing-team") mock_resolve_workspace.assert_not_awaited() - assert "Project deletion disabled" in result - assert "locked-project" in result # --- Cloud merge tests --- diff --git a/tests/mcp/test_tool_schema.py b/tests/mcp/test_tool_schema.py index 6c36016cb..d8952b2f6 100644 --- a/tests/mcp/test_tool_schema.py +++ b/tests/mcp/test_tool_schema.py @@ -9,7 +9,10 @@ from pathlib import Path from unittest.mock import AsyncMock, patch +import json + import pytest +from fastmcp.exceptions import ToolError from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from basic_memory.index.local_project import LocalProjectIndexRunner @@ -277,13 +280,13 @@ async def test_schema_validate_by_title(app, test_project, index_project): @pytest.mark.asyncio -async def test_schema_validate_identifier_no_schema_returns_guidance( +async def test_schema_validate_identifier_no_schema_refuses_with_guidance( app, test_project, index_project ): - """When a note exists but no schema is defined, return guidance. + """When a note exists but no schema is defined, refuse with guidance. Regression test for issue #33: when validating a single note by identifier - and no schema exists, the tool should return guidance instead of an empty report. + and no schema exists, the tool should refuse with guidance instead of an empty report. """ project_path = Path(test_project.path) @@ -296,12 +299,15 @@ async def test_schema_validate_identifier_no_schema_returns_guidance( await index_project() - result = await schema_validate( - identifier="Alice", - project=test_project.name, - ) + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_validate( + identifier="Alice", + project=test_project.name, + ) + result = str(refused.value) - # Should return guidance string about missing schema + # The refusal carries guidance about the missing schema assert isinstance(result, str) assert "No Schema Found" in result assert "person" in result @@ -431,10 +437,10 @@ async def test_schema_validate_all_types_json(app, test_project, index_project): @pytest.mark.asyncio -async def test_schema_validate_all_types_no_schemas_returns_guidance( +async def test_schema_validate_all_types_no_schemas_refuses_with_guidance( app, test_project, index_project ): - """With no arguments and no schemas defined, return guidance — not 'unknown'. + """With no arguments and no schemas defined, refuse with guidance — not 'unknown'. Regression test for issue #1013: schema_validate() without note_type or identifier reported "No Notes Found of Type 'unknown'" instead of @@ -451,7 +457,10 @@ async def test_schema_validate_all_types_no_schemas_returns_guidance( await index_project() - result = await schema_validate(project=test_project.name) + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_validate(project=test_project.name) + result = str(refused.value) assert isinstance(result, str) assert "No Schemas Defined" in result @@ -462,9 +471,12 @@ async def test_schema_validate_all_types_no_schemas_returns_guidance( @pytest.mark.asyncio async def test_schema_validate_all_types_no_schemas_json(app, test_project, index_project): """JSON output with no schemas defined returns a clear error dict.""" - result = await schema_validate(project=test_project.name, output_format="json") + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_validate(project=test_project.name, output_format="json") + result = json.loads(str(refused.value)) - assert result == {"error": "No schemas defined in this project"} + assert result == {"error": "NOT_FOUND", "message": "No schemas defined in this project"} # --- write_note metadata → schema workflow --- @@ -589,8 +601,8 @@ async def test_schema_title_mismatch_finds_by_metadata(app, test_project, index_ @pytest.mark.asyncio -async def test_schema_infer_empty_schema_returns_guidance(app, test_project, index_project): - """When notes exist but no fields meet the threshold, return guidance instead of data.""" +async def test_schema_infer_empty_schema_refuses_with_guidance(app, test_project, index_project): + """When notes exist but no fields meet the threshold, refuse with guidance instead of data.""" project_path = Path(test_project.path) # Create notes with completely different observation categories so no field @@ -623,12 +635,15 @@ async def test_schema_infer_empty_schema_returns_guidance(app, test_project, ind await index_project() - result = await schema_infer( - note_type="widget", - project=test_project.name, - ) + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_infer( + note_type="widget", + project=test_project.name, + ) + result = str(refused.value) - # Should return guidance string, not an InferenceReport + # The refusal carries guidance, not an InferenceReport assert isinstance(result, str) assert "No Schema Pattern Found" in result assert "widget" in result @@ -639,14 +654,17 @@ async def test_schema_infer_empty_schema_returns_guidance(app, test_project, ind @pytest.mark.asyncio -async def test_schema_validate_no_notes_returns_guidance(app, test_project, index_project): - """When no notes of the requested type exist, return guidance on creating notes.""" - result = await schema_validate( - note_type="employee", - project=test_project.name, - ) +async def test_schema_validate_no_notes_refuses_with_guidance(app, test_project, index_project): + """When no notes of the requested type exist, refuse with guidance on creating notes.""" + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_validate( + note_type="employee", + project=test_project.name, + ) + result = str(refused.value) - # Should return guidance about creating notes, not about missing schema + # The refusal is about creating notes, not about a missing schema assert isinstance(result, str) assert "No Notes Found" in result assert "employee" in result @@ -655,8 +673,8 @@ async def test_schema_validate_no_notes_returns_guidance(app, test_project, inde @pytest.mark.asyncio -async def test_schema_validate_no_schema_returns_guidance(app, test_project, index_project): - """When notes exist but no schema is defined, return guidance on creating one.""" +async def test_schema_validate_no_schema_refuses_with_guidance(app, test_project, index_project): + """When notes exist but no schema is defined, refuse with guidance on creating one.""" project_path = Path(test_project.path) # Create person notes but no schema note @@ -669,12 +687,15 @@ async def test_schema_validate_no_schema_returns_guidance(app, test_project, ind await index_project() - result = await schema_validate( - note_type="person", - project=test_project.name, - ) + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_validate( + note_type="person", + project=test_project.name, + ) + result = str(refused.value) - # Should return guidance string, not a ValidationReport + # The refusal carries guidance, not a ValidationReport assert isinstance(result, str) assert "No Schema Found" in result assert "person" in result @@ -683,8 +704,8 @@ async def test_schema_validate_no_schema_returns_guidance(app, test_project, ind @pytest.mark.asyncio -async def test_schema_diff_no_schema_returns_guidance(app, test_project, index_project): - """When no schema exists for the type, return guidance on creating one.""" +async def test_schema_diff_no_schema_refuses_with_guidance(app, test_project, index_project): + """When no schema exists for the type, refuse with guidance on creating one.""" project_path = Path(test_project.path) # Create person notes but no schema note @@ -696,12 +717,15 @@ async def test_schema_diff_no_schema_returns_guidance(app, test_project, index_p await index_project() - result = await schema_diff( - note_type="person", - project=test_project.name, - ) + # Nothing to report is a refusal now, not a success (C11, #1813). + with pytest.raises(ToolError) as refused: + await schema_diff( + note_type="person", + project=test_project.name, + ) + result = str(refused.value) - # Should return guidance string, not a DriftReport + # The refusal carries guidance, not a DriftReport assert isinstance(result, str) assert "No Schema Found" in result assert "person" in result @@ -713,48 +737,39 @@ async def test_schema_diff_no_schema_returns_guidance(app, test_project, index_p @pytest.mark.asyncio -async def test_schema_validate_error_returns_guidance(app, test_project): - """When SchemaClient.validate raises, the tool returns a troubleshooting string.""" +async def test_schema_validate_error_propagates(app, test_project): + """When SchemaClient.validate raises, the error reaches the caller as a tool error.""" mock_validate = AsyncMock(side_effect=RuntimeError("connection lost")) with patch("basic_memory.mcp.clients.schema.SchemaClient.validate", mock_validate): - result = await schema_validate( - note_type="person", - project=test_project.name, - ) - - assert isinstance(result, str) - assert "Schema Validation Failed" in result - assert "Troubleshooting" in result + with pytest.raises(RuntimeError, match="connection lost"): + await schema_validate( + note_type="person", + project=test_project.name, + ) @pytest.mark.asyncio -async def test_schema_infer_error_returns_guidance(app, test_project): - """When SchemaClient.infer raises, the tool returns a troubleshooting string.""" +async def test_schema_infer_error_propagates(app, test_project): + """When SchemaClient.infer raises, the error reaches the caller as a tool error.""" mock_infer = AsyncMock(side_effect=RuntimeError("db unavailable")) with patch("basic_memory.mcp.clients.schema.SchemaClient.infer", mock_infer): - result = await schema_infer( - note_type="person", - project=test_project.name, - ) - - assert isinstance(result, str) - assert "Schema Inference Failed" in result - assert "Troubleshooting" in result + with pytest.raises(RuntimeError, match="db unavailable"): + await schema_infer( + note_type="person", + project=test_project.name, + ) @pytest.mark.asyncio -async def test_schema_diff_error_returns_guidance(app, test_project): - """When SchemaClient.diff raises, the tool returns a troubleshooting string.""" +async def test_schema_diff_error_propagates(app, test_project): + """When SchemaClient.diff raises, the error reaches the caller as a tool error.""" mock_diff = AsyncMock(side_effect=RuntimeError("network error")) with patch("basic_memory.mcp.clients.schema.SchemaClient.diff", mock_diff): - result = await schema_diff( - note_type="person", - project=test_project.name, - ) - - assert isinstance(result, str) - assert "Schema Diff Failed" in result - assert "Troubleshooting" in result + with pytest.raises(RuntimeError, match="network error"): + await schema_diff( + note_type="person", + project=test_project.name, + ) diff --git a/tests/test_man_pages.py b/tests/test_man_pages.py index 5526738ad..b68332862 100644 --- a/tests/test_man_pages.py +++ b/tests/test_man_pages.py @@ -148,6 +148,7 @@ def test_bundled_pages_are_well_formed_and_sorted() -> None: "bm_list", "bm_move", "bm_project", + "bm_project_delete", "bm_read", "bm_schema", "bm_search", From d70a399fc6c926db5e356c185b5ceffd343ba4e7 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 09:25:59 -0500 Subject: [PATCH 03/17] fix(mcp): gate legacy delete_project, refuse empty infer, honest recent docs Codex review on #1839: - delete_project carries the project-delete tag, so enable_project_delete hides it as well as bm_project_delete; integration tests that delete projects opt in through a project_delete_enabled fixture. - schema_infer refuses a note type with no notes as NOT_FOUND instead of returning an empty report as a success. - bm_project's `recent` description says what omitting `project` does: the default project, and every project only when there is no default. - bm_project_delete takes output_format; JSON carries the outcome as fields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- .../mcp/tools/project_management.py | 5 +++-- src/basic_memory/mcp/tools/projects.py | 17 ++++++++++++++--- src/basic_memory/mcp/tools/schema.py | 13 ++++++++++++- test-int/conftest.py | 15 +++++++++++++++ .../mcp/test_project_management_integration.py | 3 +++ ...est_recreate_project_indexing_integration.py | 3 +++ .../mcp/test_single_project_mcp_integration.py | 1 + tests/mcp/test_tool_contracts.py | 4 ++-- 8 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 7c796f335..9338e455a 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -29,7 +29,7 @@ resolve_workspace_parameter, ) from basic_memory.mcp.refusals import refusal -from basic_memory.mcp.server import mcp +from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp from basic_memory.schemas.project_info import ProjectInfoRequest, ProjectItem, ProjectList from basic_memory.utils import generate_permalink @@ -767,7 +767,8 @@ def _format_note_file_delete_result( @mcp.tool( title="Delete Project", - tags={"projects"}, + # Hidden unless enable_project_delete is on, like bm_project_delete (#1832). + tags={"projects", PROJECT_DELETE_TAG}, annotations={ "title": "Delete Project", "readOnlyHint": False, diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index 49a937462..5c0d32b04 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -48,7 +48,8 @@ description=( "Basic Memory projects. `command`: list (projects, grouped by workspace); create " "(`name`, `path`, optional `set_default`, `workspace`); recent (what changed " - "lately: `since`, `items`, paging; omit `project` to see every project)." + "lately: `since`, `items`, paging; `project` picks the project, else the default " + "project, and with no default every project)." ), tags={"projects"}, annotations={ @@ -153,12 +154,22 @@ async def bm_project_delete( bool, Field(description="Also delete the project's note files.") ] = False, workspace: Workspace = None, + output_format: OutputFormat = "text", context: Context | None = None, -) -> str: +) -> str | dict[str, Any]: """Delete one project.""" - return await delete_project( + message = await delete_project( project_name=name, delete_notes=delete_notes, workspace=workspace, context=context ) + # delete_project reports in prose; JSON callers get the same facts as fields. + if output_format == "json": + return { + "action": "deleted", + "name": name, + "delete_notes": delete_notes, + "message": message, + } + return message # Hidden until the composition root reads enable_project_delete at startup. diff --git a/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index 967b2a88a..b9cae2ded 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -464,11 +464,22 @@ async def schema_infer( f"optional={len(result.suggested_optional)}" ) + # --- No notes guard --- + # Trigger: no notes of this type exist, so nothing was analyzed + # Why: an empty report would read as a successful inference (C11) + # Outcome: a NOT_FOUND refusal with guidance on creating notes of this type + if result.notes_analyzed == 0: + raise _nothing_to_report( + output_format, + f"No notes found of type '{note_type}'", + _no_notes_guidance(note_type, "schema_infer"), + ) + # --- Empty schema guard --- # Trigger: notes were analyzed but no fields met the threshold # Why: returning hundreds of excluded fields overwhelms the LLM context # Outcome: a NOT_FOUND refusal with guidance instead of a massive empty result - if result.notes_analyzed > 0 and not result.suggested_schema: + if not result.suggested_schema: raise _nothing_to_report( output_format, f"No schema pattern found for '{note_type}' (threshold: {threshold:.0%})", diff --git a/test-int/conftest.py b/test-int/conftest.py index 559a0a8b7..5afdbbe0b 100644 --- a/test-int/conftest.py +++ b/test-int/conftest.py @@ -93,6 +93,7 @@ async def test_my_mcp_tool(mcp_server, app): # Import MCP tools so they're available for testing from basic_memory.mcp import tools # noqa: F401 +from basic_memory.mcp.server import mcp as mcp_instance, set_project_delete_visibility # ============================================================================= @@ -562,6 +563,20 @@ def mcp_server(config_manager, search_service): return server +@pytest.fixture +def project_delete_enabled(config_manager: ConfigManager) -> Generator[None, None, None]: + """Turn on enable_project_delete, so delete_project and bm_project_delete are listed. + + The server lifespan applies the flag when a client connects. Visibility marks + outlive the test on the shared server, so the teardown hides the tools again. + """ + config = config_manager.load_config() + config.enable_project_delete = True + config_manager.save_config(config) + yield + set_project_delete_visibility(mcp_instance, False) + + @pytest_asyncio.fixture async def client(app: FastAPI) -> AsyncGenerator[AsyncClient, None]: """Create test client that both MCP and tests will use.""" diff --git a/test-int/mcp/test_project_management_integration.py b/test-int/mcp/test_project_management_integration.py index f86cf2c46..cde83ecfe 100644 --- a/test-int/mcp/test_project_management_integration.py +++ b/test-int/mcp/test_project_management_integration.py @@ -7,6 +7,9 @@ import pytest from fastmcp import Client +# These tests delete projects through the MCP client, which needs the opt-in. +pytestmark = pytest.mark.usefixtures("project_delete_enabled") + @pytest.mark.asyncio async def test_list_projects_basic_operation(mcp_server, app, test_project): diff --git a/test-int/mcp/test_recreate_project_indexing_integration.py b/test-int/mcp/test_recreate_project_indexing_integration.py index 3c90db0c2..8004685be 100644 --- a/test-int/mcp/test_recreate_project_indexing_integration.py +++ b/test-int/mcp/test_recreate_project_indexing_integration.py @@ -6,6 +6,9 @@ import pytest from fastmcp import Client +# These tests delete projects through the MCP client, which needs the opt-in. +pytestmark = pytest.mark.usefixtures("project_delete_enabled") + def _json_content(tool_result) -> Any: assert len(tool_result.content) == 1 diff --git a/test-int/mcp/test_single_project_mcp_integration.py b/test-int/mcp/test_single_project_mcp_integration.py index 34801892b..8ba5d3f1c 100644 --- a/test-int/mcp/test_single_project_mcp_integration.py +++ b/test-int/mcp/test_single_project_mcp_integration.py @@ -179,6 +179,7 @@ async def test_create_project_disabled_in_constrained_mode(mcp_server, app, test @pytest.mark.asyncio +@pytest.mark.usefixtures("project_delete_enabled") async def test_delete_project_disabled_in_constrained_mode(mcp_server, app, test_project): """Test that delete_project is disabled when server is constrained.""" diff --git a/tests/mcp/test_tool_contracts.py b/tests/mcp/test_tool_contracts.py index 4b4084530..37aba520b 100644 --- a/tests/mcp/test_tool_contracts.py +++ b/tests/mcp/test_tool_contracts.py @@ -90,7 +90,7 @@ "output_format", "project", ], - "bm_project_delete": ["name", "delete_notes", "workspace"], + "bm_project_delete": ["name", "delete_notes", "workspace", "output_format"], "bm_schema": [ "command", "note_type", @@ -331,7 +331,6 @@ # if the target already exists. "create_memory_project": {"readOnlyHint": False, "destructiveHint": False}, "delete_note": {"readOnlyHint": False, "destructiveHint": True}, - "delete_project": {"readOnlyHint": False, "destructiveHint": True}, # edit_note's find_replace/replace_section overwrite existing content, so it is # destructive even though append/prepend are additive. "edit_note": {"readOnlyHint": False, "destructiveHint": True}, @@ -359,6 +358,7 @@ "tail": {"readOnlyHint": True, "destructiveHint": False}, # Listed only when enable_project_delete is on. "bm_project_delete": {"readOnlyHint": False, "destructiveHint": True}, + "delete_project": {"readOnlyHint": False, "destructiveHint": True}, } EXPECTED_EDIT_NOTE_OPERATIONS = [ From aef642a7ba635c0b535574a50f2fa4a0ff1a01ba Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 09:26:30 -0500 Subject: [PATCH 04/17] test(mcp): cover bm_project_delete JSON and infer with no notes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- tests/mcp/test_tool_bm_project.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 7b84c7f18..fe2e46739 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -66,9 +66,13 @@ async def test_create_and_delete(app, tmp_path_factory): created = await bm_project(command="create", name="Scratch", path=str(project_root)) deleted = await bm_project_delete(name="Scratch") + await bm_project(command="create", name="Scratch Two", path=str(project_root)) + deleted_json = await bm_project_delete(name="Scratch Two", output_format="json") assert isinstance(created, str) and created.startswith("✓") assert isinstance(deleted, str) and deleted.startswith("✓") + assert isinstance(deleted_json, dict) + assert deleted_json["action"] == "deleted" and deleted_json["name"] == "Scratch Two" @pytest.mark.asyncio @@ -183,6 +187,12 @@ async def test_schema_reports_once_a_schema_exists(client, test_project): assert isinstance(drift_text, str) and isinstance(inferred_text, str) +@pytest.mark.asyncio +async def test_infer_with_no_notes_of_the_type(client, test_project): + with pytest.raises(ToolError, match="^NOT_FOUND: # No Notes Found of Type 'robot'"): + await bm_schema(command="infer", note_type="robot", project=test_project.name) + + @pytest.mark.asyncio async def test_infer_below_the_threshold(client, test_project): for name, category in (("ada", "role"), ("grace", "hobby"), ("alan", "pet")): From 9505abf6c112cdaa740401f67d307dcbe16810b1 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 10:31:17 -0500 Subject: [PATCH 05/17] docs(mcp): present-tense module docs for bm_project and bm_schema Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/cli/commands/schema.py | 5 ++--- src/basic_memory/mcp/server.py | 2 +- src/basic_memory/mcp/tools/note_schemas.py | 7 +++---- src/basic_memory/mcp/tools/project_management.py | 8 +++----- src/basic_memory/mcp/tools/projects.py | 15 +++++++-------- src/basic_memory/mcp/tools/schema.py | 3 ++- 6 files changed, 18 insertions(+), 22 deletions(-) diff --git a/src/basic_memory/cli/commands/schema.py b/src/basic_memory/cli/commands/schema.py index 565a3f08e..69d4f8723 100644 --- a/src/basic_memory/cli/commands/schema.py +++ b/src/basic_memory/cli/commands/schema.py @@ -170,9 +170,8 @@ def _render_diff_output(data: dict[str, Any]) -> None: def _run_schema_tool(call: Coroutine[Any, Any, Any]) -> Any: """Run a schema tool; nothing to report keeps the CLI's {"error": message} result. - The MCP tools refuse "no schemas yet" and "no notes of this type" as NOT_FOUND - (#1813). For the CLI that is not a failure: the command prints the message and - exits 0, as it always has. + The MCP tools refuse "no schemas yet" and "no notes of this type" as NOT_FOUND. + For the CLI that is not a failure: the command prints the message and exits 0. """ from basic_memory.mcp.refusals import Refusal diff --git a/src/basic_memory/mcp/server.py b/src/basic_memory/mcp/server.py index 42de14fe8..6709825a5 100644 --- a/src/basic_memory/mcp/server.py +++ b/src/basic_memory/mcp/server.py @@ -35,7 +35,7 @@ def set_project_delete_visibility(server: FastMCP, enabled: bool) -> None: - """Show or hide bm_project_delete (#1832). + """Show or hide the project-delete tools (bm_project_delete, delete_project). Like set_posix_tools_visibility, the last mark appended wins, so this is safe to call at import, at each lifespan start, and in tests. diff --git a/src/basic_memory/mcp/tools/note_schemas.py b/src/basic_memory/mcp/tools/note_schemas.py index 23a804f16..06ce9e1a6 100644 --- a/src/basic_memory/mcp/tools/note_schemas.py +++ b/src/basic_memory/mcp/tools/note_schemas.py @@ -1,8 +1,7 @@ -"""bm_schema: validate notes against their schemas, infer schemas, find drift (#1832). +"""bm_schema: validate notes against their schemas, infer schemas, find drift. -Replaces schema_validate, schema_infer and schema_diff (SPEC-35.2). Each command -delegates to the implementation of the tool it replaces; this tool gives them the -1.0 name, one `command` parameter and the shared parameter types. +Each command runs the schema tool implementation of the same purpose; this tool +gives them one `command` parameter and the shared parameter types. """ from typing import Annotated, Any, Literal diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 9338e455a..9d1bfdee7 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -586,8 +586,7 @@ async def create_memory_project( # Trigger: MCP server is constrained to a single project. # Why: constrained sessions cannot create projects, and workspace selectors # may be invalid or unavailable in that locked context. - # Outcome: an UNSUPPORTED refusal before opening a routed client; it used to - # return as a success describing the failure (#1813). + # Outcome: an UNSUPPORTED refusal before opening a routed client. constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT") if constrained_project: raise refusal( @@ -767,7 +766,7 @@ def _format_note_file_delete_result( @mcp.tool( title="Delete Project", - # Hidden unless enable_project_delete is on, like bm_project_delete (#1832). + # Hidden unless enable_project_delete is on, like bm_project_delete. tags={"projects", PROJECT_DELETE_TAG}, annotations={ "title": "Delete Project", @@ -820,8 +819,7 @@ async def delete_project( # Trigger: MCP server is constrained to a single project. # Why: constrained sessions cannot delete projects, and workspace selectors # may be invalid or unavailable in that locked context. - # Outcome: an UNSUPPORTED refusal before opening a routed client; it used to - # return as a success describing the failure (#1813). + # Outcome: an UNSUPPORTED refusal before opening a routed client. constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT") if constrained_project: raise refusal( diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index 5c0d32b04..a535aa48c 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -1,13 +1,12 @@ -"""bm_project and bm_project_delete: projects and workspaces (SPEC-35.2, #1832). +"""bm_project and bm_project_delete: projects and workspaces. -bm_project replaces list_memory_projects (which already groups projects by -workspace), create_memory_project and recent_activity. bm_project_delete replaces -delete_project, as its own tool so bm_project never needs a destructive annotation. -It is hidden unless the enable_project_delete setting turns it on (see -mcp.server.set_project_delete_visibility). +bm_project lists projects (grouped by workspace), creates them, and shows what +changed recently. bm_project_delete removes one; it is its own tool so bm_project +is never destructive, and it is hidden unless the enable_project_delete setting +turns it on (see mcp.server.set_project_delete_visibility). -Each command delegates to the implementation of the tool it replaces; these tools -give them the 1.0 names, one `command` parameter and the shared parameter types. +Each command runs the project tool implementation of the same purpose; these +tools give them one `command` parameter and the shared parameter types. """ from typing import Annotated, Any, Literal diff --git a/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index b9cae2ded..94b365f31 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -167,7 +167,8 @@ def _format_drift_report(report: DriftReport) -> str: def _nothing_to_report(output_format: OutputFormat, message: str, guidance: str) -> ToolError: """A NOT_FOUND refusal: the short message in JSON, the full guidance as text (C11). - These cases used to return as successful results describing a failure (#1813). + A success that describes a failure reads as success to a client that checks + isError, so "nothing to report" is a refusal. """ text = message if output_format == "json" else guidance return refusal("NOT_FOUND", text, output_format=output_format) From a416239617d326ea98fbc2b0da3cab8b78c49006 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 10:35:12 -0500 Subject: [PATCH 06/17] fix(cli): bm tool schema-* keep "nothing to report" as exit 0 The `bm tool schema-validate|infer|diff` wrappers called the MCP tools directly and fell into the generic error path on a NOT_FOUND refusal, exiting 1. They now share run_schema_tool (moved to command_utils) with `bm schema`, so both print {"error": message} and exit 0. Codex review on #1839. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- .../cli/commands/command_utils.py | 17 +++++++++++++ src/basic_memory/cli/commands/schema.py | 25 +++---------------- src/basic_memory/cli/commands/tool.py | 8 +++--- tests/cli/test_cli_schema.py | 6 ++--- tests/cli/test_cli_tool_json_output.py | 18 +++++++++++++ 5 files changed, 46 insertions(+), 28 deletions(-) diff --git a/src/basic_memory/cli/commands/command_utils.py b/src/basic_memory/cli/commands/command_utils.py index 9e8403010..b69cec755 100644 --- a/src/basic_memory/cli/commands/command_utils.py +++ b/src/basic_memory/cli/commands/command_utils.py @@ -159,3 +159,20 @@ async def get_project_info(project: str): else: console.print(f"[red]Project info failed: {literal(e)}[/red]") raise typer.Exit(1) + + +def run_schema_tool(call: Coroutine[Any, Any, Any]) -> Any: + """Run a schema tool; nothing to report keeps the CLI's {"error": message} result. + + The MCP tools refuse "no schemas yet" and "no notes of this type" as NOT_FOUND. + For the CLI that is not a failure: the command prints the message and exits 0. + """ + # Deferred: refusals imports fastmcp, which must not load at CLI startup (#886). + from basic_memory.mcp.refusals import Refusal + + try: + return run_with_cleanup(call) + except Refusal as refused: + if refused.code != "NOT_FOUND": + raise + return {"error": refused.message} diff --git a/src/basic_memory/cli/commands/schema.py b/src/basic_memory/cli/commands/schema.py index 69d4f8723..a04f42e85 100644 --- a/src/basic_memory/cli/commands/schema.py +++ b/src/basic_memory/cli/commands/schema.py @@ -9,7 +9,6 @@ """ import json -from collections.abc import Coroutine from typing import Any, Annotated, Optional import typer @@ -18,7 +17,7 @@ from rich.table import Table from basic_memory.cli.app import app -from basic_memory.cli.commands.command_utils import run_with_cleanup +from basic_memory.cli.commands.command_utils import run_schema_tool from basic_memory.cli.commands.routing import force_routing, validate_routing_flags from basic_memory.config import ConfigManager from basic_memory.cli.markup import literal @@ -167,22 +166,6 @@ def _render_diff_output(data: dict[str, Any]) -> None: # --- Commands --- -def _run_schema_tool(call: Coroutine[Any, Any, Any]) -> Any: - """Run a schema tool; nothing to report keeps the CLI's {"error": message} result. - - The MCP tools refuse "no schemas yet" and "no notes of this type" as NOT_FOUND. - For the CLI that is not a failure: the command prints the message and exits 0. - """ - from basic_memory.mcp.refusals import Refusal - - try: - return run_with_cleanup(call) - except Refusal as refused: - if refused.code != "NOT_FOUND": - raise - return {"error": refused.message} - - @schema_app.command() def validate( target: Annotated[ @@ -226,7 +209,7 @@ def validate( note_type = target with force_routing(local=local, cloud=cloud): - result = _run_schema_tool( + result = run_schema_tool( mcp_schema_validate( note_type=note_type, identifier=identifier, @@ -304,7 +287,7 @@ def infer( project_name = _resolve_project_name(project) with force_routing(local=local, cloud=cloud): - result = _run_schema_tool( + result = run_schema_tool( mcp_schema_infer( note_type=note_type, threshold=threshold, @@ -387,7 +370,7 @@ def diff( project_name = _resolve_project_name(project) with force_routing(local=local, cloud=cloud): - result = _run_schema_tool( + result = run_schema_tool( mcp_schema_diff( note_type=note_type, project=project_name, diff --git a/src/basic_memory/cli/commands/tool.py b/src/basic_memory/cli/commands/tool.py index ec7da7025..deb3ce032 100644 --- a/src/basic_memory/cli/commands/tool.py +++ b/src/basic_memory/cli/commands/tool.py @@ -34,7 +34,7 @@ from rich.tree import Tree from basic_memory.cli.app import app -from basic_memory.cli.commands.command_utils import run_with_cleanup +from basic_memory.cli.commands.command_utils import run_schema_tool, run_with_cleanup from basic_memory.config import ConfigManager from basic_memory.file_utils import has_frontmatter, remove_frontmatter from basic_memory.cli.commands.routing import force_routing, validate_routing_flags @@ -1512,7 +1512,7 @@ def schema_validate( note_type = target with force_routing(local=local, cloud=cloud): - result = run_with_cleanup( + result = run_schema_tool( mcp_schema_validate( note_type=note_type, identifier=identifier, @@ -1575,7 +1575,7 @@ def schema_infer( validate_routing_flags(local, cloud) with force_routing(local=local, cloud=cloud): - result = run_with_cleanup( + result = run_schema_tool( mcp_schema_infer( note_type=note_type, threshold=threshold, @@ -1634,7 +1634,7 @@ def schema_diff( validate_routing_flags(local, cloud) with force_routing(local=local, cloud=cloud): - result = run_with_cleanup( + result = run_schema_tool( mcp_schema_diff( note_type=note_type, project=project, diff --git a/tests/cli/test_cli_schema.py b/tests/cli/test_cli_schema.py index 447e5b8f4..0caa499b8 100644 --- a/tests/cli/test_cli_schema.py +++ b/tests/cli/test_cli_schema.py @@ -8,7 +8,7 @@ import pytest from typer.testing import CliRunner -from basic_memory.cli.commands.schema import _run_schema_tool +from basic_memory.cli.commands.command_utils import run_schema_tool from basic_memory.cli.main import app as cli_app from basic_memory.mcp.refusals import Refusal, refusal @@ -314,6 +314,6 @@ async def nothing() -> None: async def broken() -> None: raise refusal("INVALID_ARGUMENTS", "bad", output_format="json") - assert _run_schema_tool(nothing()) == {"error": "No schemas defined in this project"} + assert run_schema_tool(nothing()) == {"error": "No schemas defined in this project"} with pytest.raises(Refusal): - _run_schema_tool(broken()) + run_schema_tool(broken()) diff --git a/tests/cli/test_cli_tool_json_output.py b/tests/cli/test_cli_tool_json_output.py index 76e378781..9e97ec294 100644 --- a/tests/cli/test_cli_tool_json_output.py +++ b/tests/cli/test_cli_tool_json_output.py @@ -7,10 +7,12 @@ import json from unittest.mock import AsyncMock, patch +import pytest from fastmcp.exceptions import ToolError from typer.testing import CliRunner from basic_memory.cli.main import app as cli_app +from basic_memory.mcp.refusals import refusal runner = CliRunner() @@ -909,6 +911,22 @@ def test_schema_validate_json_output(mock_mcp): assert mock_mcp.call_args.kwargs["output_format"] == "json" +@pytest.mark.parametrize("command", ["schema-validate", "schema-infer", "schema-diff"]) +def test_schema_commands_print_nothing_to_report_and_exit_zero(command): + """A NOT_FOUND refusal is "nothing to report" for the CLI, not a failure.""" + tool = { + "schema-validate": "schema_validate", + "schema-infer": "schema_infer", + "schema-diff": "schema_diff", + }[command] + nothing = refusal("NOT_FOUND", "No schemas defined in this project", output_format="json") + with patch(f"basic_memory.mcp.tools.{tool}", new_callable=AsyncMock, side_effect=nothing): + result = runner.invoke(cli_app, ["tool", command, "person"]) + + assert result.exit_code == 0, f"CLI failed: {result.output}" + assert json.loads(result.output) == {"error": "No schemas defined in this project"} + + @patch( "basic_memory.mcp.tools.schema_validate", new_callable=AsyncMock, From 7a19a4a94480e57b8e3a6eb071bf234ae5a51bfc Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 10:42:21 -0500 Subject: [PATCH 07/17] fix(mcp): bm_project_delete refusals honor output_format delete_project takes no output_format, so in a constrained session a JSON caller got its refusal as text. Refusal.rendered_as() re-renders a delegated refusal in the caller's format, and bm_project_delete uses it. Codex review on #1839. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/refusals.py | 6 ++++++ src/basic_memory/mcp/tools/projects.py | 12 ++++++++---- tests/mcp/test_tool_bm_project.py | 2 ++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/basic_memory/mcp/refusals.py b/src/basic_memory/mcp/refusals.py index 2db2eab5e..8c1a8f741 100644 --- a/src/basic_memory/mcp/refusals.py +++ b/src/basic_memory/mcp/refusals.py @@ -55,6 +55,12 @@ def __init__( self.try_instead = try_instead super().__init__(_render(code, message, try_instead, output_format)) + def rendered_as(self, output_format: OutputFormat) -> "Refusal": + """The same refusal in another output format, for a tool that wraps another.""" + return Refusal( + self.code, self.message, try_instead=self.try_instead, output_format=output_format + ) + def _render( code: RefusalCode, message: str, try_instead: str | None, output_format: OutputFormat diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index a535aa48c..d1bd08f63 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -14,7 +14,7 @@ from fastmcp import Context from pydantic import AliasChoices, Field -from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.refusals import Refusal, refusal from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp, set_project_delete_visibility from basic_memory.mcp.tool_params import ( Items, @@ -157,9 +157,13 @@ async def bm_project_delete( context: Context | None = None, ) -> str | dict[str, Any]: """Delete one project.""" - message = await delete_project( - project_name=name, delete_notes=delete_notes, workspace=workspace, context=context - ) + try: + message = await delete_project( + project_name=name, delete_notes=delete_notes, workspace=workspace, context=context + ) + except Refusal as refused: + # delete_project has no output_format; its refusals are re-rendered here. + raise refused.rendered_as(output_format) from refused # delete_project reports in prose; JSON callers get the same facts as fields. if output_format == "json": return { diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index fe2e46739..3e9eaff6b 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -120,6 +120,8 @@ async def test_constrained_server_refuses_project_changes(monkeypatch): await bm_project(command="create", name="x", path="/tmp/x") with pytest.raises(ToolError, match="^UNSUPPORTED: Project deletion disabled"): await bm_project_delete(name="x") + with pytest.raises(ToolError, match='"error": "UNSUPPORTED"'): + await bm_project_delete(name="x", output_format="json") # --- bm_schema --- From b064c44f4457cc93a8d166325eef07c4fecbc9da Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 11:57:39 -0500 Subject: [PATCH 08/17] fix(mcp): schema diff refuses a type with no notes; missing project is NOT_FOUND Codex review on #1839: - DriftReport carries notes_compared; schema_diff (and so bm_schema diff) refuses a type with a schema but no notes as NOT_FOUND instead of reporting "no drift" for a comparison that never ran. A server that predates the field reports null and is not refused. - delete_project refuses a missing project as NOT_FOUND instead of a bare ValueError, so bm_project_delete renders it in the requested format. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/api/v2/routers/schema_router.py | 1 + src/basic_memory/mcp/tools/project_management.py | 6 ++++-- src/basic_memory/mcp/tools/schema.py | 11 +++++++++++ src/basic_memory/schemas/schema.py | 7 +++++++ .../mcp/test_project_management_integration.py | 9 ++------- tests/mcp/test_tool_bm_project.py | 15 +++++++++++++++ 6 files changed, 40 insertions(+), 9 deletions(-) diff --git a/src/basic_memory/api/v2/routers/schema_router.py b/src/basic_memory/api/v2/routers/schema_router.py index c5fa4d139..9bc310c65 100644 --- a/src/basic_memory/api/v2/routers/schema_router.py +++ b/src/basic_memory/api/v2/routers/schema_router.py @@ -464,6 +464,7 @@ async def search_fn(query: str) -> list[dict[str, Any]]: for f in result.dropped_fields ], cardinality_changes=result.cardinality_changes, + notes_compared=len(notes_data), ) diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 9d1bfdee7..6255009e5 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -856,8 +856,10 @@ async def delete_project( if not target_project: available_projects = [p.name for p in project_list.projects] - raise ValueError( - f"Project '{project_name}' not found. Available projects: {', '.join(available_projects)}" + raise refusal( + "NOT_FOUND", + f"Project '{project_name}' not found. Available projects: " + f"{', '.join(available_projects)}", ) # Trigger: the delete is served by a cloud backend. diff --git a/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index 94b365f31..95a1201c3 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -593,6 +593,17 @@ async def schema_diff( _no_schema_guidance(note_type, "schema_diff"), ) + # --- No notes guard --- + # Trigger: a schema exists but no notes of the type do. + # Why: an empty comparison reads as "no drift", a comparison that never ran. + # Outcome: a NOT_FOUND refusal with guidance on creating notes of this type. + if result.notes_compared == 0: + raise _nothing_to_report( + output_format, + f"No notes found of type '{note_type}'", + _no_notes_guidance(note_type, "schema_diff"), + ) + if output_format == "json": return result.model_dump(mode="json", exclude_none=True) diff --git a/src/basic_memory/schemas/schema.py b/src/basic_memory/schemas/schema.py index 9c0b50c87..ffa865d90 100644 --- a/src/basic_memory/schemas/schema.py +++ b/src/basic_memory/schemas/schema.py @@ -140,3 +140,10 @@ class DriftReport(BaseModel): description="Fields in schema but rare in notes", ) cardinality_changes: list[str] = Field(default_factory=list) + notes_compared: int | None = Field( + default=None, + description=( + "How many notes of the type were compared with the schema; null from a server " + "that predates the field." + ), + ) diff --git a/test-int/mcp/test_project_management_integration.py b/test-int/mcp/test_project_management_integration.py index cde83ecfe..cc5b0f002 100644 --- a/test-int/mcp/test_project_management_integration.py +++ b/test-int/mcp/test_project_management_integration.py @@ -230,14 +230,9 @@ async def test_delete_project_not_found(mcp_server, app, test_project): }, ) - # Should show error about non-existent project + # A missing project is a NOT_FOUND refusal naming it. error_message = str(exc_info.value) - assert "delete_project" in error_message - assert ( - "non-existent-project" in error_message - or "not found" in error_message - or "Invalid request" in error_message - ) + assert "NOT_FOUND: Project 'non-existent-project' not found" in error_message @pytest.mark.asyncio diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 3e9eaff6b..5603d10a8 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -222,3 +222,18 @@ async def test_infer_below_the_threshold(client, test_project): async def test_schema_argument_refusals(client, test_project, arguments, message): with pytest.raises(ToolError, match=f"^INVALID_ARGUMENTS: {message}"): await bm_schema(project=test_project.name, **arguments) + + +@pytest.mark.asyncio +async def test_diff_without_notes_is_not_a_clean_diff(client, test_project): + """A schema with no notes of its type compares nothing; that is not "no drift".""" + await bm_write(identifier="schemas/person.md", content=PERSON_SCHEMA, project=test_project.name) + + with pytest.raises(ToolError, match="^NOT_FOUND: # No Notes Found of Type 'person'"): + await bm_schema(command="diff", note_type="person", project=test_project.name) + + +@pytest.mark.asyncio +async def test_deleting_a_missing_project_is_not_found(app): + with pytest.raises(ToolError, match='"error": "NOT_FOUND"'): + await bm_project_delete(name="no-such-project", output_format="json") From bcd188bec88aa990a768d2f82cee4e0c43eda1d3 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 12:07:50 -0500 Subject: [PATCH 09/17] fix(mcp): bm_project recent has one JSON shape; API delete refusals keep the format Codex review on #1839: - `recent` in JSON returns {"results": rows}, or {"results": [], "guidance": ...} for a never-indexed project, instead of a bare string in that case. The same shape bm_search uses. - bm_project_delete renders the API's own refusals (deleting the default project) in the requested format through api_refusal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/tools/projects.py | 22 +++++++++++++++++++-- tests/mcp/test_tool_bm_project.py | 27 +++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index d1bd08f63..1ce99fdf3 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -12,9 +12,10 @@ from typing import Annotated, Any, Literal from fastmcp import Context +from fastmcp.exceptions import ToolError from pydantic import AliasChoices, Field -from basic_memory.mcp.refusals import Refusal, refusal +from basic_memory.mcp.refusals import Refusal, api_refusal, refusal from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp, set_project_delete_visibility from basic_memory.mcp.tool_params import ( Items, @@ -111,7 +112,7 @@ async def bm_project( ) case "recent": project_name, project_id = routing_arguments(parse_project(project)) - return await recent_activity( + activity = await recent_activity( # recent_activity names whole notes "entity", the API's word. type=["entity" if item == "note" else item for item in items] if items else "", timeframe=since, @@ -122,6 +123,15 @@ async def bm_project( output_format=output_format, context=context, ) + if output_format == "text": + return activity + # One JSON shape, as bm_search has: rows, or no rows plus the reason the + # miss is not final (a project that was never indexed). + match activity: + case list() as rows: + return {"results": rows} + case str() as guidance: + return {"results": [], "guidance": guidance} @mcp.tool( @@ -164,6 +174,14 @@ async def bm_project_delete( except Refusal as refused: # delete_project has no output_format; its refusals are re-rendered here. raise refused.rendered_as(output_format) from refused + except ToolError as error: + # The API's own refusals (deleting the default project) arrive as client errors. + refused_by_api = api_refusal(error) + if refused_by_api is None: + raise + raise refusal( + refused_by_api.code, refused_by_api.message, output_format=output_format + ) from error # delete_project reports in prose; JSON callers get the same facts as fields. if output_format == "json": return { diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 5603d10a8..da61ee92f 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -1,10 +1,13 @@ """bm_project and bm_schema: one name per group, commands delegate (#1832).""" +from typing import Any + import pytest from fastmcp.exceptions import ToolError from basic_memory.mcp.server import lifespan, mcp, set_project_delete_visibility from basic_memory.mcp.tools import bm_project, bm_project_delete, bm_schema, bm_write +from basic_memory.mcp.tools import projects as projects_module async def _listed_names() -> set[str]: @@ -94,9 +97,9 @@ async def test_recent_maps_items_and_since(client, test_project): command="recent", items=["observation"], output_format="json", project=test_project.name ) - assert isinstance(notes, list) and isinstance(observations, list) - assert any(row["title"] == "fresh" for row in notes) - assert all(row["type"] == "observation" for row in observations) + assert isinstance(notes, dict) and isinstance(observations, dict) + assert any(row["title"] == "fresh" for row in notes["results"]) + assert all(row["type"] == "observation" for row in observations["results"]) @pytest.mark.asyncio @@ -237,3 +240,21 @@ async def test_diff_without_notes_is_not_a_clean_diff(client, test_project): async def test_deleting_a_missing_project_is_not_found(app): with pytest.raises(ToolError, match='"error": "NOT_FOUND"'): await bm_project_delete(name="no-such-project", output_format="json") + + +@pytest.mark.asyncio +async def test_recent_guidance_keeps_the_json_shape(client, test_project, monkeypatch): + async def not_indexed(**_kwargs: Any) -> str: + return "Index the project first." + + monkeypatch.setattr(projects_module, "recent_activity", not_indexed) + payload = await bm_project(command="recent", output_format="json", project=test_project.name) + + assert payload == {"results": [], "guidance": "Index the project first."} + + +@pytest.mark.asyncio +async def test_api_refusals_honor_the_output_format(app, test_project): + """Deleting the default project is refused by the API; JSON keeps the refusal shape.""" + with pytest.raises(ToolError, match='"error": "INVALID_ARGUMENTS"'): + await bm_project_delete(name=test_project.name, output_format="json") From 492746d63df71f2af1e354a9a8bcdedd59be830f Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 12:21:06 -0500 Subject: [PATCH 10/17] fix(mcp): project deletion reports the backend's outcome in JSON Codex review on #1839: bm_project_delete wrapped delete_project's prose in JSON, hard-coding action "deleted" and echoing the caller's delete_notes. A Cloud delete always deletes files and can be queued, so that misreported both. delete_project takes output_format and returns the effective delete_notes, deletion_status, file_delete_status and job_id from the API response; bm_project_delete passes the format through. Refusal.rendered_as is no longer needed and is removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/refusals.py | 6 ----- .../mcp/tools/project_management.py | 19 +++++++++++++++- src/basic_memory/mcp/tools/projects.py | 22 +++++++------------ tests/mcp/test_tool_contracts.py | 2 +- tests/mcp/test_tool_project_management.py | 15 +++++++++++-- 5 files changed, 40 insertions(+), 24 deletions(-) diff --git a/src/basic_memory/mcp/refusals.py b/src/basic_memory/mcp/refusals.py index 8c1a8f741..2db2eab5e 100644 --- a/src/basic_memory/mcp/refusals.py +++ b/src/basic_memory/mcp/refusals.py @@ -55,12 +55,6 @@ def __init__( self.try_instead = try_instead super().__init__(_render(code, message, try_instead, output_format)) - def rendered_as(self, output_format: OutputFormat) -> "Refusal": - """The same refusal in another output format, for a tool that wraps another.""" - return Refusal( - self.code, self.message, try_instead=self.try_instead, output_format=output_format - ) - def _render( code: RefusalCode, message: str, try_instead: str | None, output_format: OutputFormat diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 6255009e5..ceb225eaa 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -779,8 +779,9 @@ async def delete_project( project_name: str, delete_notes: bool = False, workspace: str | None = None, + output_format: Literal["text", "json"] = "text", context: Context | None = None, -) -> str: +) -> str | dict[str, Any]: """Delete a Basic Memory project. Removes a project from Basic Memory's configuration and database records. @@ -827,6 +828,7 @@ async def delete_project( f"Project deletion disabled - MCP server is constrained to project " f"'{constrained_project}'.", try_instead=f'the CLI: basic-memory project remove "{project_name}"', + output_format=output_format, ) workspace_id = await _resolve_workspace_routing(workspace, context) @@ -860,6 +862,7 @@ async def delete_project( "NOT_FOUND", f"Project '{project_name}' not found. Available projects: " f"{', '.join(available_projects)}", + output_format=output_format, ) # Trigger: the delete is served by a cloud backend. @@ -880,6 +883,20 @@ async def delete_project( await invalidate_project_caches(context) + # The backend's own account of what happened: a Cloud delete can be queued, + # and its note files are always deleted whatever delete_notes said. + if output_format == "json": + return { + "action": "deleted", + "name": target_project.name, + "external_id": target_project.external_id, + "delete_notes": files_deleted, + "deletion_status": status_response.deletion_status, + "file_delete_status": status_response.file_delete_status if files_deleted else None, + "job_id": status_response.job_id, + "message": status_response.message, + } + result = f"✓ {status_response.message}\n\n" if status_response.old_project: diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index 1ce99fdf3..d69b169ba 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -168,12 +168,15 @@ async def bm_project_delete( ) -> str | dict[str, Any]: """Delete one project.""" try: - message = await delete_project( - project_name=name, delete_notes=delete_notes, workspace=workspace, context=context + return await delete_project( + project_name=name, + delete_notes=delete_notes, + workspace=workspace, + output_format=output_format, + context=context, ) - except Refusal as refused: - # delete_project has no output_format; its refusals are re-rendered here. - raise refused.rendered_as(output_format) from refused + except Refusal: + raise except ToolError as error: # The API's own refusals (deleting the default project) arrive as client errors. refused_by_api = api_refusal(error) @@ -182,15 +185,6 @@ async def bm_project_delete( raise refusal( refused_by_api.code, refused_by_api.message, output_format=output_format ) from error - # delete_project reports in prose; JSON callers get the same facts as fields. - if output_format == "json": - return { - "action": "deleted", - "name": name, - "delete_notes": delete_notes, - "message": message, - } - return message # Hidden until the composition root reads enable_project_delete at startup. diff --git a/tests/mcp/test_tool_contracts.py b/tests/mcp/test_tool_contracts.py index 37aba520b..a041a31b6 100644 --- a/tests/mcp/test_tool_contracts.py +++ b/tests/mcp/test_tool_contracts.py @@ -166,7 +166,7 @@ "output_format", ], "delete_note": ["identifier", "is_directory", "project", "project_id", "output_format"], - "delete_project": ["project_name", "delete_notes", "workspace"], + "delete_project": ["project_name", "delete_notes", "workspace", "output_format"], "edit_note": [ "identifier", "operation", diff --git a/tests/mcp/test_tool_project_management.py b/tests/mcp/test_tool_project_management.py index e7df6ad5f..331b99160 100644 --- a/tests/mcp/test_tool_project_management.py +++ b/tests/mcp/test_tool_project_management.py @@ -138,6 +138,7 @@ async def test_create_and_delete_project_and_name_match_branch( await session.commit() delete_result = await delete_project("My Project") + assert isinstance(delete_result, str) assert delete_result.startswith("✓") # Local routing with delete_notes=False: files are retained on disk. assert "Note files remain on disk" in delete_result @@ -199,6 +200,7 @@ async def test_delete_project_delete_notes_removes_local_files(app, tmp_path_fac assert result.startswith("✓") delete_result = await delete_project("Delete Notes Project", delete_notes=True) + assert isinstance(delete_result, str) assert delete_result.startswith("✓") # The local route deletes the directory before answering, so it reports completion. assert "Note files on disk were deleted along with the project" in delete_result @@ -586,12 +588,21 @@ async def fake_get_client(*, workspace=None, project_name=None): result = await delete_project( "WS Project", delete_notes=delete_notes, workspace="team-paul" ) + structured = await delete_project( + "WS Project", delete_notes=delete_notes, workspace="team-paul", output_format="json" + ) - mock_resolve_workspace.assert_awaited_once_with(workspace="team-paul", context=None) + mock_resolve_workspace.assert_awaited_with(workspace="team-paul", context=None) assert captured["workspace"] == "tenant-abc-123" # The cloud service deletes files on every project delete (basic-memory-cloud#2117), # so the request says so whatever the caller passed. - mock_delete_project.assert_awaited_once_with("project-uuid", delete_notes=True) + mock_delete_project.assert_awaited_with("project-uuid", delete_notes=True) + # JSON reports what the backend did: a queued delete, files included, and its job. + assert isinstance(structured, dict) + assert structured["delete_notes"] is True + assert structured["deletion_status"] == "pending" + assert structured["job_id"] == fake_status.job_id + assert isinstance(result, str) assert result.startswith("✓") assert "Project deletion status: pending" in result assert "Deletion job ID: 28993" in result From 45ccab0598671a60677a7025c1af26ec03f3509b Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 12:29:13 -0500 Subject: [PATCH 11/17] fix(mcp): bm_schema refuses note_type together with identifier Codex review on #1839: the API validates the identifier's note but the report was labeled with the caller's note_type, so one type was checked and another reported. The two scopes are mutually exclusive and refused together. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/tools/note_schemas.py | 8 ++++++++ tests/mcp/test_tool_bm_project.py | 1 + 2 files changed, 9 insertions(+) diff --git a/src/basic_memory/mcp/tools/note_schemas.py b/src/basic_memory/mcp/tools/note_schemas.py index 06ce9e1a6..e99d9c883 100644 --- a/src/basic_memory/mcp/tools/note_schemas.py +++ b/src/basic_memory/mcp/tools/note_schemas.py @@ -73,6 +73,14 @@ async def bm_schema( context: Context | None = None, ) -> ValidationReport | str | dict[str, Any]: """Validate, infer or diff note schemas.""" + # A note's own type decides its schema, so naming both would validate one and + # label the report as the other. + if note_type is not None and identifier is not None: + raise refusal( + "INVALID_ARGUMENTS", + "Give `note_type` to validate a type, or `identifier` to validate one note.", + output_format=output_format, + ) project_name, project_id = routing_arguments(parse_project(project)) if command == "validate": return await schema_validate( diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index da61ee92f..c67d89324 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -218,6 +218,7 @@ async def test_infer_below_the_threshold(client, test_project): ("arguments", "message"), [ ({"command": "infer"}, "infer needs `note_type`"), + ({"command": "validate", "note_type": "person", "identifier": "a.md"}, "Give `note_type`"), ({"command": "diff"}, "diff needs `note_type`"), ({"command": "diff", "identifier": "a.md"}, "diff works on a note type, not one note"), ], From 8800fe8163f1e892aaf3bb02e56abe79b22ffaee Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 12:36:03 -0500 Subject: [PATCH 12/17] fix(mcp): workspace selection failures are refusals in the requested format Codex review on #1839: an unknown or ambiguous workspace selector raised ValueError before the project request, reaching JSON callers as plain text. _resolve_workspace_routing turns it into an INVALID_ARGUMENTS refusal in the caller's format, for project create and delete alike. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- .../mcp/tools/project_management.py | 16 +++++++++---- tests/mcp/test_tool_project_management.py | 24 +++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index ceb225eaa..9ab71d52b 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -477,8 +477,13 @@ def _format_constrained_text(constrained_project: str) -> str: async def _resolve_workspace_routing( workspace: str | None, context: Context | None, + output_format: Literal["text", "json"], ) -> str | None: - """Resolve an optional workspace selector to the routing tenant id.""" + """Resolve an optional workspace selector to the routing tenant id. + + An unknown or ambiguous selector is an INVALID_ARGUMENTS refusal in the + caller's output format, naming the workspaces it could have meant. + """ if workspace is None: return None @@ -500,7 +505,10 @@ async def _resolve_workspace_routing( # uses X-Workspace-ID with the tenant id as its routing authority. # Outcome: resolve once before the project-management request and pass only # the tenant id downstream. - resolved_workspace = await resolve_workspace_parameter(workspace=workspace, context=context) + try: + resolved_workspace = await resolve_workspace_parameter(workspace=workspace, context=context) + except ValueError as error: + raise refusal("INVALID_ARGUMENTS", str(error), output_format=output_format) from error return resolved_workspace.tenant_id @@ -597,7 +605,7 @@ async def create_memory_project( output_format=output_format, ) - workspace_id = await _resolve_workspace_routing(workspace, context) + workspace_id = await _resolve_workspace_routing(workspace, context, output_format) # workspace targets a non-default cloud workspace at create time. # Trigger: caller passed workspace (e.g. a slug discovered via list_workspaces). @@ -831,7 +839,7 @@ async def delete_project( output_format=output_format, ) - workspace_id = await _resolve_workspace_routing(workspace, context) + workspace_id = await _resolve_workspace_routing(workspace, context, output_format) async with get_client(workspace=workspace_id) as client: if context: # pragma: no cover await context.info(f"Deleting project: {project_name}") diff --git a/tests/mcp/test_tool_project_management.py b/tests/mcp/test_tool_project_management.py index 331b99160..2705d7eec 100644 --- a/tests/mcp/test_tool_project_management.py +++ b/tests/mcp/test_tool_project_management.py @@ -4,6 +4,8 @@ from unittest.mock import AsyncMock, patch import httpx +import json + import pytest from fastmcp.exceptions import ToolError from sqlalchemy import select @@ -1449,3 +1451,25 @@ async def test_list_memory_projects_aggregates_without_config_workspace(app, tes mock_index.assert_awaited_once() assert "- cloud-proj (cloud) [00000000-0000-0000-0000-000000000001]" in result + + +@pytest.mark.asyncio +async def test_unknown_workspace_is_a_refusal_in_the_requested_format(): + """A workspace selector that names no workspace refuses; JSON keeps the shape.""" + with ( + patch( + "basic_memory.mcp.tools.project_management.is_factory_mode", + return_value=True, + ), + patch( + "basic_memory.mcp.tools.project_management.resolve_workspace_parameter", + new_callable=AsyncMock, + side_effect=ValueError("Workspace 'nope' not found. Available: team-paul"), + ), + ): + with pytest.raises(ToolError) as refused: + await delete_project("Any Project", workspace="nope", output_format="json") + + payload = json.loads(str(refused.value)) + assert payload["error"] == "INVALID_ARGUMENTS" + assert "Workspace 'nope' not found" in payload["message"] From 26efe4acbc7644f3b1ac81a8a860e9a02fab1f4b Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 12:43:58 -0500 Subject: [PATCH 13/17] fix(mcp): legacy delete_project renders API refusals in the requested format The API-refusal translation moves from the bm_project_delete wrapper into the shared delete_project implementation, so both registered tools honor output_format when the API refuses (deleting the default project). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- .../mcp/tools/project_management.py | 22 +++++++++++---- src/basic_memory/mcp/tools/projects.py | 28 ++++++------------- tests/mcp/test_tool_bm_project.py | 8 +++++- 3 files changed, 32 insertions(+), 26 deletions(-) diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 9ab71d52b..5d972cac3 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -8,6 +8,7 @@ from typing import Any, Literal from fastmcp import Context +from fastmcp.exceptions import ToolError from loguru import logger from basic_memory.config import ( @@ -28,7 +29,7 @@ ensure_workspace_project_index, resolve_workspace_parameter, ) -from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.refusals import api_refusal, refusal from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp from basic_memory.schemas.project_info import ProjectInfoRequest, ProjectItem, ProjectList from basic_memory.utils import generate_permalink @@ -883,10 +884,21 @@ async def delete_project( cloud_routed = _routes_to_cloud(workspace_id) files_deleted = delete_notes or cloud_routed - # Delete project using project external_id - status_response = await project_client.delete_project( - target_project.external_id, delete_notes=files_deleted - ) + # Trigger: the API refuses the delete (the default project, for one). + # Why: its refusal arrives as a client ToolError in plain text; every tool + # that runs this implementation promises refusals in output_format. + # Outcome: the API's code and message, rendered in the requested format. + try: + status_response = await project_client.delete_project( + target_project.external_id, delete_notes=files_deleted + ) + except ToolError as error: + refused_by_api = api_refusal(error) + if refused_by_api is None: + raise + raise refusal( + refused_by_api.code, refused_by_api.message, output_format=output_format + ) from error from basic_memory.mcp.project_context import invalidate_project_caches await invalidate_project_caches(context) diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index d69b169ba..2f82228e9 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -12,10 +12,9 @@ from typing import Annotated, Any, Literal from fastmcp import Context -from fastmcp.exceptions import ToolError from pydantic import AliasChoices, Field -from basic_memory.mcp.refusals import Refusal, api_refusal, refusal +from basic_memory.mcp.refusals import refusal from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp, set_project_delete_visibility from basic_memory.mcp.tool_params import ( Items, @@ -167,24 +166,13 @@ async def bm_project_delete( context: Context | None = None, ) -> str | dict[str, Any]: """Delete one project.""" - try: - return await delete_project( - project_name=name, - delete_notes=delete_notes, - workspace=workspace, - output_format=output_format, - context=context, - ) - except Refusal: - raise - except ToolError as error: - # The API's own refusals (deleting the default project) arrive as client errors. - refused_by_api = api_refusal(error) - if refused_by_api is None: - raise - raise refusal( - refused_by_api.code, refused_by_api.message, output_format=output_format - ) from error + return await delete_project( + project_name=name, + delete_notes=delete_notes, + workspace=workspace, + output_format=output_format, + context=context, + ) # Hidden until the composition root reads enable_project_delete at startup. diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index c67d89324..72ab36ffc 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -8,6 +8,7 @@ from basic_memory.mcp.server import lifespan, mcp, set_project_delete_visibility from basic_memory.mcp.tools import bm_project, bm_project_delete, bm_schema, bm_write from basic_memory.mcp.tools import projects as projects_module +from basic_memory.mcp.tools.project_management import delete_project async def _listed_names() -> set[str]: @@ -256,6 +257,11 @@ async def not_indexed(**_kwargs: Any) -> str: @pytest.mark.asyncio async def test_api_refusals_honor_the_output_format(app, test_project): - """Deleting the default project is refused by the API; JSON keeps the refusal shape.""" + """Deleting the default project is refused by the API; JSON keeps the refusal shape. + + The legacy delete_project runs the same implementation, so it honors the format too. + """ with pytest.raises(ToolError, match='"error": "INVALID_ARGUMENTS"'): await bm_project_delete(name=test_project.name, output_format="json") + with pytest.raises(ToolError, match='"error": "INVALID_ARGUMENTS"'): + await delete_project(project_name=test_project.name, output_format="json") From 0df63afac6ac02a7a6826c348473c996601b32ae Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 12:51:03 -0500 Subject: [PATCH 14/17] refactor(mcp): one api_refusals block for project create and delete API refusals from the project client arrive as plain-text ToolErrors. refusals.api_refusals(output_format) re-renders them in the requested format, and project creation (a path inside another project, a colliding permalink) and deletion both run their client call inside it, so bm_project create and the legacy create tool honor output_format too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/refusals.py | 23 +++++++++++++++++++ .../mcp/tools/project_management.py | 22 ++++++------------ tests/mcp/test_tool_bm_project.py | 9 ++++++++ 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/src/basic_memory/mcp/refusals.py b/src/basic_memory/mcp/refusals.py index 2db2eab5e..2bb6f27c7 100644 --- a/src/basic_memory/mcp/refusals.py +++ b/src/basic_memory/mcp/refusals.py @@ -9,6 +9,8 @@ """ import json +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import dataclass from typing import Literal @@ -145,6 +147,27 @@ def api_refusal(error: ToolError) -> ApiRefusal | None: ) +@contextmanager +def api_refusals(output_format: OutputFormat) -> Iterator[None]: + """Re-render the API's own refusals in the requested format. + + A typed client raises an API refusal as a plain-text ToolError; inside this + block it becomes a refusal in `output_format`. Refusals raised here already + and failures with an unknown outcome pass through unchanged. + """ + try: + yield + except Refusal: + raise + except ToolError as error: + refused_by_api = api_refusal(error) + if refused_by_api is None: + raise + raise refusal( + refused_by_api.code, refused_by_api.message, output_format=output_format + ) from error + + # --- Failed note changes --- # bm_write, bm_edit, bm_move and bm_delete fail the same few ways, so one place # words them. Every path given here is already qualified the way the call diff --git a/src/basic_memory/mcp/tools/project_management.py b/src/basic_memory/mcp/tools/project_management.py index 5d972cac3..13e5f2081 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -8,7 +8,6 @@ from typing import Any, Literal from fastmcp import Context -from fastmcp.exceptions import ToolError from loguru import logger from basic_memory.config import ( @@ -29,7 +28,7 @@ ensure_workspace_project_index, resolve_workspace_parameter, ) -from basic_memory.mcp.refusals import api_refusal, refusal +from basic_memory.mcp.refusals import api_refusals, refusal from basic_memory.mcp.server import PROJECT_DELETE_TAG, mcp from basic_memory.schemas.project_info import ProjectInfoRequest, ProjectItem, ProjectList from basic_memory.utils import generate_permalink @@ -680,7 +679,10 @@ async def create_memory_project( ) return result - status_response = await project_client.create_project(project_request.model_dump()) + # The API refuses some creates (a path inside another project, a name whose + # permalink collides). + with api_refusals(output_format): + status_response = await project_client.create_project(project_request.model_dump()) from basic_memory.mcp.project_context import invalidate_project_caches await invalidate_project_caches(context) @@ -884,21 +886,11 @@ async def delete_project( cloud_routed = _routes_to_cloud(workspace_id) files_deleted = delete_notes or cloud_routed - # Trigger: the API refuses the delete (the default project, for one). - # Why: its refusal arrives as a client ToolError in plain text; every tool - # that runs this implementation promises refusals in output_format. - # Outcome: the API's code and message, rendered in the requested format. - try: + # The API refuses some deletes (the default project, for one). + with api_refusals(output_format): status_response = await project_client.delete_project( target_project.external_id, delete_notes=files_deleted ) - except ToolError as error: - refused_by_api = api_refusal(error) - if refused_by_api is None: - raise - raise refusal( - refused_by_api.code, refused_by_api.message, output_format=output_format - ) from error from basic_memory.mcp.project_context import invalidate_project_caches await invalidate_project_caches(context) diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 72ab36ffc..c7dac6c8d 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -128,6 +128,15 @@ async def test_constrained_server_refuses_project_changes(monkeypatch): await bm_project_delete(name="x", output_format="json") +@pytest.mark.asyncio +async def test_create_api_refusals_honor_the_output_format(app, test_project): + """The API refuses a project nested inside another; JSON keeps the refusal shape.""" + nested = f"{test_project.path}/nested" + + with pytest.raises(ToolError, match='"error": "INVALID_ARGUMENTS"'): + await bm_project(command="create", name="Nested", path=nested, output_format="json") + + # --- bm_schema --- From 6d8729e760421cb1e92202dcedbae5813594ca73 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 13:12:51 -0500 Subject: [PATCH 15/17] fix(mcp): bm_project recent JSON carries page, page_size and has_more recent_activity_page returns text, or RecentRows (rows plus paging) for JSON callers. The legacy recent_activity tool is a wrapper that keeps its list-of-rows JSON, and bm_project(command='recent') returns the rows with page, page_size and has_more. In discovery mode has_more is true when any project has another page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/tools/projects.py | 23 +++++--- src/basic_memory/mcp/tools/recent_activity.py | 59 ++++++++++++++++++- tests/mcp/test_tool_bm_project.py | 17 +++++- 3 files changed, 88 insertions(+), 11 deletions(-) diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index 2f82228e9..5b09bdcfe 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -31,7 +31,7 @@ delete_project, list_memory_projects, ) -from basic_memory.mcp.tools.recent_activity import recent_activity +from basic_memory.mcp.tools.recent_activity import RecentRows, recent_activity_page type ProjectCommand = Literal["list", "create", "recent"] @@ -111,9 +111,10 @@ async def bm_project( ) case "recent": project_name, project_id = routing_arguments(parse_project(project)) - activity = await recent_activity( + activity = await recent_activity_page( # recent_activity names whole notes "entity", the API's word. type=["entity" if item == "note" else item for item in items] if items else "", + depth=1, timeframe=since, page=page, page_size=page_size, @@ -122,13 +123,19 @@ async def bm_project( output_format=output_format, context=context, ) - if output_format == "text": - return activity - # One JSON shape, as bm_search has: rows, or no rows plus the reason the - # miss is not final (a project that was never indexed). + # Text is returned as rendered. JSON has one shape, as bm_search has: rows + # with paging, or no rows plus the reason the miss is not final (a project + # that was never indexed). match activity: - case list() as rows: - return {"results": rows} + case str() as text if output_format == "text": + return text + case RecentRows() as recent: + return { + "results": recent.rows, + "page": recent.page, + "page_size": recent.page_size, + "has_more": recent.has_more, + } case str() as guidance: return {"results": [], "guidance": guidance} diff --git a/src/basic_memory/mcp/tools/recent_activity.py b/src/basic_memory/mcp/tools/recent_activity.py index 0ebe2785e..616b6d3ce 100644 --- a/src/basic_memory/mcp/tools/recent_activity.py +++ b/src/basic_memory/mcp/tools/recent_activity.py @@ -1,5 +1,6 @@ """Recent activity tool for Basic Memory MCP server.""" +from dataclasses import dataclass from datetime import timezone from pathlib import PurePosixPath from typing import Any, Annotated, List, Union, Optional, Literal @@ -149,6 +150,50 @@ async def recent_activity( - For focused queries, consider using build_context with a specific URI - Max timeframe is 1 year in the past """ + page_result = await recent_activity_page( + type=type, + depth=depth, + timeframe=timeframe, + page=page, + page_size=page_size, + project=project, + project_id=project_id, + output_format=output_format, + context=context, + ) + match page_result: + case RecentRows(rows=rows): + return rows + case str() as text: + return text + + +@dataclass(frozen=True, slots=True) +class RecentRows: + """One page of recent activity as rows, and whether another page follows. + + In discovery mode `has_more` is true when any project has another page. + """ + + rows: list[dict[str, Any]] + page: int + page_size: int + has_more: bool + + +async def recent_activity_page( + *, + type: str | list[str], + depth: int, + timeframe: str, + page: int, + page_size: int, + project: str | None, + project_id: str | None, + output_format: Literal["text", "json"], + context: Context | None, +) -> str | RecentRows: + """Recent activity as text, or as rows with paging for JSON callers.""" # Validate pagination arguments before they reach the API layer, # where negative offset would cause a database error. if page < 1: @@ -264,7 +309,12 @@ async def recent_activity( rows: list[dict[str, Any]] = [] for project_name, project_activity in projects_activity.items(): rows.extend(_extract_recent_rows(project_activity.activity, project_name)) - return rows + return RecentRows( + rows=rows, + page=page, + page_size=page_size, + has_more=any(activity.activity.has_more for activity in projects_activity.values()), + ) # Build summary stats summary = ActivityStats( @@ -330,7 +380,12 @@ async def recent_activity( return guidance if output_format == "json": - return _extract_recent_rows(activity_data) + return RecentRows( + rows=_extract_recent_rows(activity_data), + page=page, + page_size=page_size, + has_more=activity_data.has_more, + ) # Format project-specific mode output. Pass the external id so onboarding examples # route by id, not by a name that can collide across cloud workspaces. diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index c7dac6c8d..db59a71b2 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -103,6 +103,21 @@ async def test_recent_maps_items_and_since(client, test_project): assert all(row["type"] == "observation" for row in observations["results"]) +@pytest.mark.asyncio +async def test_recent_json_carries_paging(client, test_project): + """A full page says another follows, so JSON callers know to ask for page 2.""" + for name in ("one", "two"): + await bm_write(identifier=f"notes/{name}.md", content="# x", project=test_project.name) + + first = await bm_project( + command="recent", page_size=1, output_format="json", project=test_project.name + ) + + assert isinstance(first, dict) + assert (first["page"], first["page_size"], first["has_more"]) == (1, 1, True) + assert len(first["results"]) == 1 + + @pytest.mark.asyncio @pytest.mark.parametrize( ("arguments", "message"), @@ -258,7 +273,7 @@ async def test_recent_guidance_keeps_the_json_shape(client, test_project, monkey async def not_indexed(**_kwargs: Any) -> str: return "Index the project first." - monkeypatch.setattr(projects_module, "recent_activity", not_indexed) + monkeypatch.setattr(projects_module, "recent_activity_page", not_indexed) payload = await bm_project(command="recent", output_format="json", project=test_project.name) assert payload == {"results": [], "guidance": "Index the project first."} From 8fd583a80a0bdefd1a0f69b396a7541d029686bc Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 13:32:17 -0500 Subject: [PATCH 16/17] fix(mcp): recent discovery keeps activity beside unindexed-project guidance Discovery mode returned the first unindexed project's guidance and stopped, hiding the activity of every other project. It now checks every project: with no activity anywhere it returns the indexing guidance as before; otherwise text appends each unindexed project's guidance after the summary, and bm_project(command='recent') JSON returns the rows with a `guidance` field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/tools/projects.py | 6 +++- src/basic_memory/mcp/tools/recent_activity.py | 20 ++++++++++-- tests/mcp/test_tool_bm_project.py | 32 +++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index 5b09bdcfe..fc94d7344 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -130,12 +130,16 @@ async def bm_project( case str() as text if output_format == "text": return text case RecentRows() as recent: - return { + payload: dict[str, Any] = { "results": recent.rows, "page": recent.page, "page_size": recent.page_size, "has_more": recent.has_more, } + # Projects never indexed, beside the activity of those that were. + if recent.guidance: + payload["guidance"] = "\n\n".join(recent.guidance) + return payload case str() as guidance: return {"results": [], "guidance": guidance} diff --git a/src/basic_memory/mcp/tools/recent_activity.py b/src/basic_memory/mcp/tools/recent_activity.py index 616b6d3ce..a981a8cf1 100644 --- a/src/basic_memory/mcp/tools/recent_activity.py +++ b/src/basic_memory/mcp/tools/recent_activity.py @@ -179,6 +179,8 @@ class RecentRows: page: int page_size: int has_more: bool + # Indexing guidance for projects that were never indexed (discovery mode). + guidance: tuple[str, ...] = () async def recent_activity_page( @@ -275,14 +277,17 @@ async def recent_activity_page( most_active_count = 0 active_projects = 0 + # Guidance for each project that was never indexed, kept beside the + # activity of the projects that were, so neither hides the other. + unindexed: list[str] = [] + # Query each project's activity for project_info in project_list.projects: project_activity = await _get_project_activity(client, project_info, params, depth) - # Discovery must not hide an unindexed project in an empty summary. if not project_activity.item_count: guidance = await project_index_required(client, project_info) if guidance is not None: - return guidance + unindexed.append(guidance) projects_activity[project_info.name] = project_activity # Aggregate stats @@ -305,11 +310,19 @@ async def recent_activity_page( most_active_count = item_count most_active_project = project_info.name + # Trigger: no project has activity and some were never indexed. + # Why: an empty summary would read as "nothing happened" when the + # unindexed projects were never searched. + # Outcome: the indexing guidance alone, as before. + if unindexed and active_projects == 0: + return "\n\n".join(unindexed) + if output_format == "json": rows: list[dict[str, Any]] = [] for project_name, project_activity in projects_activity.items(): rows.extend(_extract_recent_rows(project_activity.activity, project_name)) return RecentRows( + guidance=tuple(unindexed), rows=rows, page=page, page_size=page_size, @@ -344,6 +357,9 @@ async def recent_activity_page( ) guidance_lines.append(f"Suggested project: '{suggested_project}' {suffix}".strip()) + # Projects never indexed are named after the activity found elsewhere. + for project_guidance in unindexed: + guidance_lines.extend(["", project_guidance]) guidance = "\n".join(guidance_lines) # Format discovery mode output diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index db59a71b2..76f121896 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -1,5 +1,6 @@ """bm_project and bm_schema: one name per group, commands delegate (#1832).""" +import importlib from typing import Any import pytest @@ -118,6 +119,37 @@ async def test_recent_json_carries_paging(client, test_project): assert len(first["results"]) == 1 +@pytest.mark.asyncio +async def test_recent_discovery_keeps_activity_beside_unindexed_guidance( + client, test_project, second_project, monkeypatch +): + """One unindexed project does not hide the activity found in the others.""" + await bm_write(identifier="notes/fresh.md", content="# fresh", project=test_project.name) + + async def no_project(*_args: Any, **_kwargs: Any) -> None: + return None + + async def only_second_unindexed(_client: Any, project: Any) -> str | None: + return ( + f"'{project.name}' has never been indexed" + if project.name == second_project.name + else None + ) + + # The tools package re-exports the function under the module's name. + recent_activity_module = importlib.import_module("basic_memory.mcp.tools.recent_activity") + monkeypatch.setattr(recent_activity_module, "resolve_project_parameter", no_project) + monkeypatch.setattr(recent_activity_module, "project_index_required", only_second_unindexed) + + payload = await bm_project(command="recent", output_format="json") + text = await bm_project(command="recent") + + assert isinstance(payload, dict) and isinstance(text, str) + assert any(row["title"] == "fresh" for row in payload["results"]) + assert payload["guidance"] == f"'{second_project.name}' has never been indexed" + assert "fresh" in text and f"'{second_project.name}' has never been indexed" in text + + @pytest.mark.asyncio @pytest.mark.parametrize( ("arguments", "message"), From 731eae0a9bfaaab573806ab9f16bd03e9c5b2b18 Mon Sep 17 00:00:00 2001 From: phernandez Date: Fri, 23 Oct 2026 13:43:22 -0500 Subject: [PATCH 17/17] fix(mcp): schema tools render API refusals in the requested format schema_validate, schema_infer and schema_diff run their SchemaClient call inside api_refusals(output_format), so an invalid schema definition (a 400 from the API) reaches bm_schema and the legacy schema tools as a refusal in the requested format, as project create and delete already do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018CoZ3jWnMJsyQsik4tPySk Signed-off-by: phernandez --- src/basic_memory/mcp/tools/schema.py | 19 ++++++++++++------- tests/mcp/test_tool_bm_project.py | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index 95a1201c3..2d71f6835 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -11,7 +11,7 @@ from fastmcp.exceptions import ToolError from basic_memory.mcp.project_context import get_project_client -from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.refusals import api_refusals, refusal from basic_memory.mcp.tool_params import OutputFormat from basic_memory.mcp.server import mcp from basic_memory.schemas.schema import DriftReport, InferenceReport, ValidationReport @@ -328,10 +328,12 @@ async def schema_validate( from basic_memory.mcp.clients.schema import SchemaClient schema_client = SchemaClient(client, active_project.external_id) - result = await schema_client.validate( - note_type=note_type, - identifier=identifier, - ) + # The API refuses an invalid schema definition with a 400. + with api_refusals(output_format): + result = await schema_client.validate( + note_type=note_type, + identifier=identifier, + ) logger.debug( f"MCP tool response: tool=schema_validate project={active_project.name} " @@ -456,7 +458,8 @@ async def schema_infer( from basic_memory.mcp.clients.schema import SchemaClient schema_client = SchemaClient(client, active_project.external_id) - result = await schema_client.infer(note_type, threshold=threshold) + with api_refusals(output_format): + result = await schema_client.infer(note_type, threshold=threshold) logger.debug( f"MCP tool response: tool=schema_infer project={active_project.name} " @@ -572,7 +575,9 @@ async def schema_diff( from basic_memory.mcp.clients.schema import SchemaClient schema_client = SchemaClient(client, active_project.external_id) - result = await schema_client.diff(note_type) + # The API refuses an invalid schema definition with a 400. + with api_refusals(output_format): + result = await schema_client.diff(note_type) logger.debug( f"MCP tool response: tool=schema_diff project={active_project.name} " diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 76f121896..4f5bb29af 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -221,6 +221,27 @@ async def test_schema_commands_delegate(client, test_project): ) +@pytest.mark.asyncio +async def test_schema_api_refusals_honor_the_output_format(client, test_project): + """An invalid inline schema is refused by the API; JSON keeps the refusal shape.""" + await bm_write( + identifier="people/odd.md", + content=( + "---\ntype: invalid_mode\nschema:\n name: string\nsettings:\n" + " validation: banana\n---\n\n- [name] Odd" + ), + project=test_project.name, + ) + + with pytest.raises(ToolError, match='"error": "INVALID_ARGUMENTS"'): + await bm_schema( + command="validate", + identifier="people/odd.md", + output_format="json", + project=test_project.name, + ) + + @pytest.mark.asyncio async def test_schema_reports_once_a_schema_exists(client, test_project): await bm_write(identifier="schemas/person.md", content=PERSON_SCHEMA, project=test_project.name)