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/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 983338a56..a04f42e85 100644 --- a/src/basic_memory/cli/commands/schema.py +++ b/src/basic_memory/cli/commands/schema.py @@ -17,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 @@ -209,7 +209,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 +287,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 +370,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/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/src/basic_memory/config_models.py b/src/basic_memory/config_models.py index b7f8e7ed9..ccfa011cf 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 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" + ), + ) + cli_output_style: Literal["rich", "plain"] = Field( default="rich", description=( diff --git a/src/basic_memory/mcp/refusals.py b/src/basic_memory/mcp/refusals.py index 304d454b5..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 @@ -35,26 +37,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 --- @@ -118,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/server.py b/src/basic_memory/mcp/server.py index 8521d0db7..6709825a5 100644 --- a/src/basic_memory/mcp/server.py +++ b/src/basic_memory/mcp/server.py @@ -31,6 +31,18 @@ POSIX_TOOLS_TAG = "posix" +PROJECT_DELETE_TAG = "project-delete" + + +def set_project_delete_visibility(server: FastMCP, enabled: bool) -> None: + """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. + """ + server.add_transform(Visibility(enabled, tags={PROJECT_DELETE_TAG})) + + def set_posix_tools_visibility(server: FastMCP, enabled: bool) -> None: """Mark the POSIX tool group visible or hidden. @@ -111,6 +123,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_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 48e1284f2..e2dc0dfdf 100644 --- a/src/basic_memory/mcp/tools/__init__.py +++ b/src/basic_memory/mcp/tools/__init__.py @@ -44,6 +44,9 @@ 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 + +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 @@ -56,7 +59,10 @@ "bm_find", "bm_list", "bm_move", + "bm_project", + "bm_project_delete", "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..e99d9c883 --- /dev/null +++ b/src/basic_memory/mcp/tools/note_schemas.py @@ -0,0 +1,122 @@ +"""bm_schema: validate notes against their schemas, infer schemas, find drift. + +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 + +from fastmcp import Context +from pydantic import AliasChoices, Field + +from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.server import mcp +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"] + + +@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, +) -> 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( + 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, + ) + 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 schema_infer( + note_type=note_type, + threshold=threshold, + project=project_name, + project_id=project_id, + output_format=output_format, + context=context, + ) + 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..13e5f2081 100644 --- a/src/basic_memory/mcp/tools/project_management.py +++ b/src/basic_memory/mcp/tools/project_management.py @@ -28,7 +28,8 @@ ensure_workspace_project_index, resolve_workspace_parameter, ) -from basic_memory.mcp.server import mcp +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 @@ -476,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 @@ -499,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 @@ -585,25 +594,18 @@ 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. 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) + 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). @@ -677,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) @@ -772,7 +777,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. + tags={"projects", PROJECT_DELETE_TAG}, annotations={ "title": "Delete Project", "readOnlyHint": False, @@ -784,8 +790,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. @@ -824,12 +831,18 @@ 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. 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}"', + 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}") @@ -856,8 +869,11 @@ 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)}", + output_format=output_format, ) # Trigger: the delete is served by a cloud backend. @@ -870,14 +886,29 @@ 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 - ) + # 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 + ) from basic_memory.mcp.project_context import invalidate_project_caches 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 new file mode 100644 index 000000000..fc94d7344 --- /dev/null +++ b/src/basic_memory/mcp/tools/projects.py @@ -0,0 +1,190 @@ +"""bm_project and bm_project_delete: projects and workspaces. + +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 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 + +from fastmcp import Context +from pydantic import AliasChoices, Field + +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, + 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 RecentRows, recent_activity_page + +type ProjectCommand = Literal["list", "create", "recent"] + +Workspace = Annotated[ + str | None, + Field(description="In Cloud: the workspace slug, name or id that holds the project."), +] + + +@mcp.tool( + name="bm_project", + title="Projects", + description=( + "Basic Memory projects. `command`: list (projects, grouped by workspace); create " + "(`name`, `path`, optional `set_default`, `workspace`); recent (what changed " + "lately: `since`, `items`, paging; `project` picks the project, else the default " + "project, and with no default every project)." + ), + 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: 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, + page_size: PageSize = 10, + output_format: OutputFormat = "text", + project: ProjectParam = None, + context: Context | None = None, +) -> str | dict[str, Any] | list[dict[str, Any]]: + """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) + 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)) + 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, + project=project_name, + project_id=project_id, + output_format=output_format, + context=context, + ) + # 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 str() as text if output_format == "text": + return text + case RecentRows() as recent: + 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} + + +@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, + output_format: OutputFormat = "text", + context: Context | None = None, +) -> str | dict[str, Any]: + """Delete one project.""" + 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. +set_project_delete_visibility(mcp, False) diff --git a/src/basic_memory/mcp/tools/recent_activity.py b/src/basic_memory/mcp/tools/recent_activity.py index 0ebe2785e..a981a8cf1 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,52 @@ 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 + # Indexing guidance for projects that were never indexed (discovery mode). + guidance: tuple[str, ...] = () + + +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: @@ -230,14 +277,17 @@ async def recent_activity( 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 @@ -260,11 +310,24 @@ async def recent_activity( 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 rows + return RecentRows( + guidance=tuple(unindexed), + 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( @@ -294,6 +357,9 @@ async def recent_activity( ) 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 @@ -330,7 +396,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/src/basic_memory/mcp/tools/schema.py b/src/basic_memory/mcp/tools/schema.py index 6e7834c10..2d71f6835 100644 --- a/src/basic_memory/mcp/tools/schema.py +++ b/src/basic_memory/mcp/tools/schema.py @@ -8,8 +8,11 @@ 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.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 @@ -161,6 +164,16 @@ def _format_drift_report(report: DriftReport) -> str: 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). + + 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) + + def _no_notes_guidance(note_type: str, tool_name: str) -> str: """Build guidance string when no notes of a given type exist. @@ -312,72 +325,66 @@ async def schema_validate( f"note_type={note_type} identifier={identifier}" ) - 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) + schema_client = SchemaClient(client, active_project.external_id) + # 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} " - 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: - 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) - 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 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"), + ) + + # --- 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", @@ -448,66 +455,59 @@ 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) + schema_client = SchemaClient(client, active_project.external_id) + 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} " - f"note_type={note_type} notes_analyzed={result.notes_analyzed} " - f"required={len(result.suggested_required)} " - f"optional={len(result.suggested_optional)}" - ) + 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" - ) + # --- 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"), + ) - 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 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( @@ -572,43 +572,44 @@ 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) + schema_client = SchemaClient(client, active_project.external_id) + # 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} " - 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)}" - ) + 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") + # --- 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"), + ) - if output_format == "json": - return result.model_dump(mode="json", exclude_none=True) + # --- 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"), + ) - 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/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/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..cc5b0f002 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): @@ -227,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/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 e2781cabe..8ba5d3f1c 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: @@ -181,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.""" @@ -189,16 +188,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..0caa499b8 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.command_utils 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/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, diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py new file mode 100644 index 000000000..4f5bb29af --- /dev/null +++ b/tests/mcp/test_tool_bm_project.py @@ -0,0 +1,344 @@ +"""bm_project and bm_schema: one name per group, commands delegate (#1832).""" + +import importlib +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 +from basic_memory.mcp.tools.project_management import delete_project + + +async def _listed_names() -> set[str]: + # The server's own listing: entering a Client would run the lifespan, which + # 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_project_delete_is_hidden_by_default(): + names = await _listed_names() + + assert "bm_project" in names + assert "bm_project_delete" not in names + + +@pytest.mark.asyncio +async def test_bm_project_is_never_destructive(): + (tool,) = [tool for tool in await mcp.list_tools() if tool.name == "bm_project"] + + 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_lists_project_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): + names = await _listed_names() + finally: + set_project_delete_visibility(mcp, False) + + assert "bm_project_delete" in names + + +# --- 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_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 +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, 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 +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 +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"), + [ + ({"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 +async def test_constrained_server_refuses_project_changes(monkeypatch): + monkeypatch.setenv("BASIC_MEMORY_MCP_PROJECT", "only-this") + + 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") + with pytest.raises(ToolError, match='"error": "UNSUPPORTED"'): + 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 --- + + +@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"] + + # 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 Found for 'person'"): + await bm_schema(command="validate", note_type="person", project=test_project.name) + with pytest.raises(ToolError, match="^NOT_FOUND: # No Schemas Defined"): + await bm_schema(command="validate", 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 = ( + "---\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_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) + 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 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")): + 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 Schema Pattern Found"): + 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": "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"), + ], +) +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") + + +@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_page", 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. + + 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") diff --git a/tests/mcp/test_tool_contracts.py b/tests/mcp/test_tool_contracts.py index ca7deeca0..a041a31b6 100644 --- a/tests/mcp/test_tool_contracts.py +++ b/tests/mcp/test_tool_contracts.py @@ -77,6 +77,28 @@ "output_format", "project", ], + "bm_project": [ + "command", + "name", + "path", + "set_default", + "workspace", + "since", + "items", + "page", + "page_size", + "output_format", + "project", + ], + "bm_project_delete": ["name", "delete_notes", "workspace", "output_format"], + "bm_schema": [ + "command", + "note_type", + "identifier", + "threshold", + "output_format", + "project", + ], "bm_write": [ "content", "identifier", @@ -144,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", @@ -289,6 +311,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}, @@ -307,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}, @@ -333,6 +356,9 @@ "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}, + "delete_project": {"readOnlyHint": False, "destructiveHint": True}, } EXPECTED_EDIT_NOTE_OPERATIONS = [ @@ -355,6 +381,9 @@ "bm_edit": tools.bm_edit, "bm_move": tools.bm_move, "bm_delete": tools.bm_delete, + "bm_project": tools.bm_project, + "bm_project_delete": tools.bm_project_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/mcp/test_tool_project_management.py b/tests/mcp/test_tool_project_management.py index 630e0c7a6..2705d7eec 100644 --- a/tests/mcp/test_tool_project_management.py +++ b/tests/mcp/test_tool_project_management.py @@ -4,7 +4,10 @@ from unittest.mock import AsyncMock, patch import httpx +import json + import pytest +from fastmcp.exceptions import ToolError from sqlalchemy import select from basic_memory import db @@ -137,6 +140,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 @@ -198,6 +202,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 @@ -482,7 +487,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 +505,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 @@ -584,12 +590,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 @@ -757,7 +772,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 +787,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 --- @@ -1435,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"] 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 cd79ff7f2..b68332862 100644 --- a/tests/test_man_pages.py +++ b/tests/test_man_pages.py @@ -147,7 +147,10 @@ def test_bundled_pages_are_well_formed_and_sorted() -> None: "bm_find", "bm_list", "bm_move", + "bm_project", + "bm_project_delete", "bm_read", + "bm_schema", "bm_search", "bm_write", }