Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
d100dd0
feat(mcp): add bm_project and bm_schema, the grouped 1.0 tools
phernandez Oct 23, 2026
b0374d1
refactor(mcp): one shape for grouped tools; bm_project_delete as its …
phernandez Oct 23, 2026
d70a399
fix(mcp): gate legacy delete_project, refuse empty infer, honest rece…
phernandez Oct 23, 2026
aef642a
test(mcp): cover bm_project_delete JSON and infer with no notes
phernandez Oct 23, 2026
9505abf
docs(mcp): present-tense module docs for bm_project and bm_schema
phernandez Oct 23, 2026
a416239
fix(cli): bm tool schema-* keep "nothing to report" as exit 0
phernandez Oct 23, 2026
7a19a4a
fix(mcp): bm_project_delete refusals honor output_format
phernandez Oct 23, 2026
b064c44
fix(mcp): schema diff refuses a type with no notes; missing project i…
phernandez Oct 23, 2026
bcd188b
fix(mcp): bm_project recent has one JSON shape; API delete refusals k…
phernandez Oct 23, 2026
492746d
fix(mcp): project deletion reports the backend's outcome in JSON
phernandez Oct 23, 2026
45ccab0
fix(mcp): bm_schema refuses note_type together with identifier
phernandez Oct 23, 2026
8800fe8
fix(mcp): workspace selection failures are refusals in the requested …
phernandez Oct 23, 2026
26efe4a
fix(mcp): legacy delete_project renders API refusals in the requested…
phernandez Oct 23, 2026
0df63af
refactor(mcp): one api_refusals block for project create and delete
phernandez Oct 23, 2026
6d8729e
fix(mcp): bm_project recent JSON carries page, page_size and has_more
phernandez Oct 23, 2026
8fd583a
fix(mcp): recent discovery keeps activity beside unindexed-project gu…
phernandez Oct 23, 2026
731eae0
fix(mcp): schema tools render API refusals in the requested format
phernandez Oct 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/basic_memory/api/v2/routers/schema_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)


Expand Down
17 changes: 17 additions & 0 deletions src/basic_memory/cli/commands/command_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
8 changes: 4 additions & 4 deletions src/basic_memory/cli/commands/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions src/basic_memory/cli/commands/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 9 additions & 0 deletions src/basic_memory/config_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=(
Expand Down
68 changes: 59 additions & 9 deletions src/basic_memory/mcp/refusals.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"""

import json
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Literal

Expand All @@ -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 ---
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions src/basic_memory/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
6 changes: 6 additions & 0 deletions src/basic_memory/mcp/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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",
Expand Down
122 changes: 122 additions & 0 deletions src/basic_memory/mcp/tools/note_schemas.py
Original file line number Diff line number Diff line change
@@ -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(
Comment thread
phernandez marked this conversation as resolved.
Resolved
note_type=note_type,
identifier=identifier,
Comment thread
phernandez marked this conversation as resolved.
Resolved
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,
Comment thread
phernandez marked this conversation as resolved.
Resolved
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,
)
Loading
Loading