diff --git a/src/basic_memory/mcp/missing_project.py b/src/basic_memory/mcp/missing_project.py new file mode 100644 index 000000000..bf2132703 --- /dev/null +++ b/src/basic_memory/mcp/missing_project.py @@ -0,0 +1,75 @@ +"""Refuse a call that leaves out a required project, instead of failing validation.""" + +from typing import Any, override + +import mcp.types as mt +from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext +from fastmcp.tools import ToolResult + +from basic_memory.mcp.refusals import refusal +from basic_memory.mcp.tool_params import OutputFormat + +DISCOVER_PROJECTS = "bm_project(command='list') to discover projects" + + +class MissingProjectMiddleware(Middleware): + """Refuse a missing or blank ``project`` on any tool whose schema requires it. + + Without this, FastMCP's argument validation answers with pydantic's raw + error (``missing_keyword_only_argument``, ``string_too_short``), which does + not tell the model what ``project`` is or how to find one. A client holding a + tool list cached from before ``project`` became required sends exactly that + call (#1984). + + The check reads the tool's published input schema rather than a list of tool + names, so it covers every tool registered on the server, including ones that + replace or add to the core tools. + """ + + @override + async def on_call_tool( + self, + context: MiddlewareContext[mt.CallToolRequestParams], + call_next: CallNext[mt.CallToolRequestParams, ToolResult], + ) -> ToolResult: + if context.fastmcp_context is None: + return await call_next(context) + name = context.message.name + tool = await context.fastmcp_context.fastmcp.get_tool(name) + # Trigger: an unknown tool, or one whose schema does not require project. + # Why: FastMCP reports unknown tools itself, and optional project scope + # (bm_search, bm_project) is the tool's own decision. + # Outcome: the call proceeds untouched. + if tool is None or "project" not in _required(tool.parameters): + return await call_next(context) + + arguments = context.message.arguments or {} + if _given(arguments.get("project")) or _given(arguments.get("project_id")): + return await call_next(context) + + raise refusal( + "INVALID_ARGUMENTS", + f"{name} needs `project`: the project name, 'workspace/project', or external id.", + try_instead=DISCOVER_PROJECTS, + output_format=_output_format(arguments, tool.parameters), + ) + + +def _required(schema: dict[str, Any]) -> list[Any]: + required = schema.get("required") + return required if isinstance(required, list) else [] + + +def _given(value: Any) -> bool: + return isinstance(value, str) and bool(value.strip()) + + +def _output_format(arguments: dict[str, Any], schema: dict[str, Any]) -> OutputFormat: + """The format the call asked for, else the tool's default, else text.""" + requested = arguments.get("output_format") + if requested in ("text", "json"): + return requested + properties = schema.get("properties") + output_format = properties.get("output_format") if isinstance(properties, dict) else None + default = output_format.get("default") if isinstance(output_format, dict) else None + return "json" if default == "json" else "text" diff --git a/src/basic_memory/mcp/server.py b/src/basic_memory/mcp/server.py index 9e61b030d..2e4ad2699 100644 --- a/src/basic_memory/mcp/server.py +++ b/src/basic_memory/mcp/server.py @@ -20,6 +20,7 @@ from basic_memory.mcp.client_info import MCPClientInfoMiddleware from basic_memory.mcp.container import McpContainer, installed_container as installed_mcp_container from basic_memory.mcp.empty_results import EmptyListResultMiddleware +from basic_memory.mcp.missing_project import MissingProjectMiddleware from basic_memory.read_cache import ReadCacheUnavailable from basic_memory.read_cache.redis import RedisReadCache from basic_memory.read_cache.lifecycle import open_redis_read_cache @@ -253,3 +254,4 @@ async def lifespan(app: FastMCP): ) mcp.add_middleware(MCPClientInfoMiddleware()) mcp.add_middleware(EmptyListResultMiddleware()) +mcp.add_middleware(MissingProjectMiddleware()) diff --git a/test-int/mcp/test_default_project_mode_integration.py b/test-int/mcp/test_default_project_mode_integration.py index d61578ddc..a07aa6117 100644 --- a/test-int/mcp/test_default_project_mode_integration.py +++ b/test-int/mcp/test_default_project_mode_integration.py @@ -29,7 +29,7 @@ async def test_explicit_write_in_default_project(mcp_server, app, test_project): with patch.object(ConfigManager, "config", mock_config): async with Client(mcp_server) as client: - with pytest.raises(ToolError, match="Missing required keyword only argument"): + with pytest.raises(ToolError, match="INVALID_ARGUMENTS: bm_write needs `project`"): await client.call_tool( "bm_write", {"title": "Unscoped write", "content": "Must select the default explicitly."}, @@ -334,7 +334,7 @@ async def test_project_resolution_hierarchy( # Multiple addressable projects require an explicit scope even with a default. with patch.object(ConfigManager, "config", mock_config): async with Client(mcp_server) as client: - with pytest.raises(ToolError, match="Missing required keyword only argument"): + with pytest.raises(ToolError, match="INVALID_ARGUMENTS: bm_write needs `project`"): await client.call_tool( "bm_write", { diff --git a/test-int/mcp/test_param_aliases_integration.py b/test-int/mcp/test_param_aliases_integration.py index 67663ac6a..4afb7f086 100644 --- a/test-int/mcp/test_param_aliases_integration.py +++ b/test-int/mcp/test_param_aliases_integration.py @@ -25,7 +25,9 @@ async def test_read_rejects_removed_pagination(mcp_server, app, test_project): """Exact reads use line bounds, not fuzzy-search pagination.""" async with Client(mcp_server) as client: result = await client.call_tool( - "bm_read", {"identifier": "missing", "page": 1}, raise_on_error=False + "bm_read", + {"identifier": "missing", "project": test_project.name, "page": 1}, + raise_on_error=False, ) assert result.is_error assert "unexpected_keyword_argument" in result.content[0].text diff --git a/test-int/mcp/test_single_project_mcp_integration.py b/test-int/mcp/test_single_project_mcp_integration.py index 4ebc77917..41bc136a9 100644 --- a/test-int/mcp/test_single_project_mcp_integration.py +++ b/test-int/mcp/test_single_project_mcp_integration.py @@ -311,8 +311,8 @@ async def test_constraint_with_invalid_project_override(mcp_server, app, test_pr try: async with Client(mcp_server) as client: - # Blank scope fails validation even when the server is constrained. - with pytest.raises(ToolError, match="at least 1 character"): + # Blank scope is refused even when the server is constrained. + with pytest.raises(ToolError, match="INVALID_ARGUMENTS: bm_write needs `project`"): await client.call_tool( "bm_write", {"project": "", "title": "Blank scope", "content": "Rejected"} ) diff --git a/tests/mcp/test_missing_project.py b/tests/mcp/test_missing_project.py new file mode 100644 index 000000000..805ace9bd --- /dev/null +++ b/tests/mcp/test_missing_project.py @@ -0,0 +1,146 @@ +"""A missing or blank project is refused with a recovery hint, not a pydantic error (#1984).""" + +import json +from typing import Any + +import pytest +from fastmcp import Client, FastMCP + +from basic_memory.mcp import tools +from basic_memory.mcp.missing_project import MissingProjectMiddleware +from basic_memory.mcp.server import mcp +from basic_memory.mcp.tool_params import OutputFormat, ProjectParam + +SCOPED_TOOLS = { + "bm_read": {"identifier": "notes/plan.md"}, + "bm_write": {"identifier": "notes/plan.md", "content": "# Plan"}, + "bm_edit": {"identifier": "notes/plan.md", "command": "append", "content": "tail"}, + "bm_move": {"identifier": "notes/plan.md", "destination": "archive/plan.md"}, + "bm_delete": {"identifier": "notes/plan.md"}, + "bm_list": {"path": "/"}, + "bm_find": {"path": "/"}, + "bm_context": {"identifier": "notes/plan.md"}, + "bm_schema": {"command": "validate"}, +} + +HINT = "Try instead: bm_project(command='list') to discover projects" + + +def _server(*registered: Any) -> FastMCP: + server = FastMCP("missing-project") + server.add_middleware(MissingProjectMiddleware()) + for tool in registered: + server.tool(tool) + return server + + +async def _call(server: FastMCP, name: str, arguments: dict[str, Any]): + async with Client(server) as client: + return await client.call_tool(name, arguments, raise_on_error=False) + + +def _text(result) -> str: + return "".join(block.text for block in result.content) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", SCOPED_TOOLS) +@pytest.mark.parametrize("scope", [{}, {"project": None}, {"project": ""}, {"project": " "}]) +async def test_one_project_tool_refuses_missing_project(name: str, scope: dict[str, Any]): + arguments = {**SCOPED_TOOLS[name], **scope, "output_format": "text"} + result = await _call(_server(getattr(tools, name)), name, arguments) + + assert result.is_error + text = _text(result) + assert text.startswith("INVALID_ARGUMENTS:") + assert f"{name} needs `project`" in text + assert HINT in text + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", SCOPED_TOOLS) +async def test_json_output_format_gets_a_json_refusal(name: str): + arguments = {**SCOPED_TOOLS[name], "output_format": "json"} + result = await _call(_server(getattr(tools, name)), name, arguments) + + assert result.is_error + payload = json.loads(_text(result)) + assert payload["error"] == "INVALID_ARGUMENTS" + assert payload["try_instead"] == "bm_project(command='list') to discover projects" + + +@pytest.mark.asyncio +async def test_refusal_follows_the_tools_default_output_format(): + # bm_context defaults to JSON; bm_list defaults to text. + context = await _call(_server(tools.bm_context), "bm_context", SCOPED_TOOLS["bm_context"]) + listing = await _call(_server(tools.bm_list), "bm_list", SCOPED_TOOLS["bm_list"]) + + assert json.loads(_text(context))["error"] == "INVALID_ARGUMENTS" + assert _text(listing).startswith("INVALID_ARGUMENTS:") + + +async def scoped_echo(note: str, *, project: ProjectParam, output_format: OutputFormat = "text"): + """A tool that is not a core tool but requires project the same way.""" + return f"{project}:{note}" + + +async def unscoped_echo(note: str, project: str | None = None) -> str: + """A tool whose project is optional.""" + return f"{project}:{note}" + + +@pytest.mark.asyncio +async def test_any_tool_requiring_project_is_refused_not_just_core_tools(): + result = await _call(_server(scoped_echo), "scoped_echo", {"note": "plan"}) + + assert result.is_error + assert _text(result).startswith("INVALID_ARGUMENTS: scoped_echo needs `project`") + assert HINT in _text(result) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("key", ["project", "project_id"]) +async def test_given_project_or_alias_passes_through(key: str): + result = await _call(_server(scoped_echo), "scoped_echo", {"note": "plan", key: "main"}) + + assert not result.is_error + assert _text(result) == "main:plan" + + +@pytest.mark.asyncio +async def test_tool_with_optional_project_is_untouched(): + result = await _call(_server(unscoped_echo), "unscoped_echo", {"note": "plan"}) + + assert not result.is_error + assert _text(result) == "None:plan" + + +@pytest.mark.asyncio +async def test_bm_search_keeps_its_own_scope_refusal(): + result = await _call(_server(tools.bm_search), "bm_search", {"query": "plan"}) + + assert result.is_error + assert "Search needs an explicit scope" in _text(result) + assert "needs `project`" not in _text(result) + + +@pytest.mark.asyncio +async def test_unknown_tool_is_reported_by_fastmcp(): + result = await _call(_server(scoped_echo), "no_such_tool", {}) + + assert result.is_error + assert "no_such_tool" in _text(result) + + +def test_basic_memory_server_registers_the_middleware(): + assert any(isinstance(middleware, MissingProjectMiddleware) for middleware in mcp.middleware) + + +@pytest.mark.asyncio +async def test_basic_memory_server_refuses_missing_project(): + async with Client(mcp) as client: + result = await client.call_tool("bm_list", {"path": "/"}, raise_on_error=False) + + assert result.is_error + assert _text(result).startswith("INVALID_ARGUMENTS: bm_list needs `project`") + assert HINT in _text(result)