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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
- [x] Received shares: list_shares takes shared_with_me (federated shares included), list_pending_shares, accept_share, decline_share; delete_share leaves a received share, federated ones too (2026-09-25)
- [x] Activity search: get_activity takes search, start, end and actor on Nextcloud 35 (refused on older servers, which would ignore them) and returns an empty page instead of failing at the end of the feed; list_activity_filters, get_activity_counts (2026-09-26)
- [x] search_files matches % and _ in the query literally instead of as database wildcards (2026-09-26)
- [x] update_circle_member_level explains when Circles cannot transfer ownership (SQLite or PostgreSQL before nextcloud/circles#2916) instead of passing on the database error (2026-09-26)

### In Progress

Expand Down Expand Up @@ -117,11 +118,11 @@
| File Helpers | — | 36 |
| File Reminders | 3 | 22 |
| Forms | 25 | 34 |
| Circles | 14 | 31 |
| Circles | 14 | 37 |
| Cospend | 16 | 41 |
| Flow | 5 | 58 |
| Pagination | — | 28 |
| **Total** | **223** | **1781** |
| **Total** | **223** | **1787** |

The test counts are what pytest collects, recomputed with `python scripts/sync_progress.py --write`,
which also fails when a test file is not assigned to a row.
Expand Down
2 changes: 1 addition & 1 deletion scripts/sync_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"File Helpers": ["test_files_helpers.py"],
"File Reminders": ["integration/test_reminders.py", "test_reminders.py"],
"Forms": ["integration/test_forms.py"],
"Circles": ["integration/test_circles.py"],
"Circles": ["integration/test_circles.py", "test_circles.py"],
"Cospend": ["integration/test_cospend.py"],
"Flow": ["integration/test_flows.py", "test_flows.py"],
}
Expand Down
28 changes: 24 additions & 4 deletions src/nc_mcp_server/tools/circles.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from mcp.server.fastmcp import FastMCP

from ..annotations import ADDITIVE, ADDITIVE_IDEMPOTENT, DESTRUCTIVE, READONLY
from ..client import NextcloudError
from ..permissions import PermissionLevel, require_permission
from ..state import get_client

Expand Down Expand Up @@ -298,6 +299,8 @@ async def update_circle_member_level(circle_id: str, member_id: str, level: str)
user's singleId or userId — use the "id" field from members).
level: One of "member", "moderator", "admin", "owner". Promoting
someone to "owner" transfers ownership; the caller becomes admin.
Older Circles releases cannot transfer ownership on SQLite or
PostgreSQL; the tool then says so and nothing changes.

Returns:
JSON of the updated member (same shape as entries from
Expand All @@ -308,13 +311,30 @@ async def update_circle_member_level(circle_id: str, member_id: str, level: str)
if level not in MEMBER_LEVELS:
raise ValueError(f"Invalid level '{level}'. Must be one of: {sorted(MEMBER_LEVELS)}")
client = get_client()
data = await client.ocs_put_json(
f"apps/circles/circles/{circle_id}/members/{member_id}/level",
json_data={"level": MEMBER_LEVELS[level]},
)
try:
data = await client.ocs_put_json(
f"apps/circles/circles/{circle_id}/members/{member_id}/level",
json_data={"level": MEMBER_LEVELS[level]},
)
except NextcloudError as e:
# Circles releases before the fix of nextcloud/circles#2916 lock the members with a query SQLite
# cannot build and PostgreSQL refuses; the transaction is rolled back, so the old owner keeps it.
if level == "owner" and _refused_row_lock(str(e)):
msg = (
"This server's Circles app cannot transfer ownership: its database refuses the row lock Circles "
"takes, a Circles bug fixed in Nextcloud updates from late September 2026. Nothing was changed; "
"other level changes still work."
)
raise ValueError(msg) from e
raise
return json.dumps(data)


def _refused_row_lock(message: str) -> bool:
"""Whether the database refused Circles' SELECT ... FOR UPDATE (SQLite, or PostgreSQL on an outer join)."""
return "FOR UPDATE" in message and ("not supported" in message or "outer join" in message)


def _register_destructive_tools(mcp: FastMCP) -> None:
@mcp.tool(annotations=DESTRUCTIVE)
@require_permission(PermissionLevel.DESTRUCTIVE)
Expand Down
9 changes: 6 additions & 3 deletions tests/integration/test_circles.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,10 +352,13 @@ async def test_promote_to_owner_transfers_and_demotes_caller(self, nc_mcp: McpTe
level="owner",
)
except ToolError as e:
if "FOR UPDATE" not in str(e):
if "cannot transfer ownership" not in str(e):
raise
# circles locks member rows with SELECT ... FOR UPDATE, which Nextcloud's SQLite platform rejects.
pytest.skip("circles cannot transfer ownership on SQLite")
# The refusal must leave the circle as it was
members = json.loads(await nc_mcp.call("list_circle_members", circle_id=circle["id"]))
levels = {m.get("userId"): m["level"] for m in members}
assert (levels[get_config().user], levels[circle_peer]) == (9, 1)
pytest.skip("this server's Circles predates the ownership transfer fix (nextcloud/circles#2916)")
members: list[dict[str, Any]] = json.loads(await nc_mcp.call("list_circle_members", circle_id=circle["id"]))
peer_level = next(m["level"] for m in members if m.get("userId") == circle_peer)
caller_level = next(m["level"] for m in members if m.get("userId") == get_config().user)
Expand Down
71 changes: 71 additions & 0 deletions tests/test_circles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Unit tests for Circles member level changes."""

from typing import Any
from unittest.mock import AsyncMock, MagicMock

import pytest
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError

from nc_mcp_server.client import NextcloudError
from nc_mcp_server.permissions import PermissionLevel, set_permission_level
from nc_mcp_server.tools import circles

LOCK_ERROR = NextcloudError(
"OCS PUT x: An exception occurred while executing a query: SQLSTATE[0A000]: Feature not supported: 7 ERROR:"
" FOR UPDATE cannot be applied to the nullable side of an outer join",
400,
)


@pytest.fixture
def client(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
set_permission_level(PermissionLevel.WRITE)
mock = MagicMock()
mock.ocs_put_json = AsyncMock(return_value={"id": "m1", "level": 9})
monkeypatch.setattr(circles, "get_client", lambda: mock)
return mock


@pytest.fixture
def mcp(client: MagicMock) -> FastMCP:
server = FastMCP("test-circles")
circles.register(server)
return server


async def _call(mcp: FastMCP, tool: str, **args: Any) -> Any:
return await mcp._tool_manager.call_tool(tool, args)


class TestMemberLevel:
async def test_owner_transfer(self, mcp: FastMCP, client: MagicMock) -> None:
result = await _call(mcp, "update_circle_member_level", circle_id="c", member_id="m1", level="owner")
assert '"level": 9' in result
client.ocs_put_json.assert_awaited_once_with("apps/circles/circles/c/members/m1/level", json_data={"level": 9})

async def test_owner_transfer_the_database_refuses(self, mcp: FastMCP, client: MagicMock) -> None:
client.ocs_put_json.side_effect = LOCK_ERROR
with pytest.raises(ToolError, match=r"cannot transfer ownership.*Nothing was changed"):
await _call(mcp, "update_circle_member_level", circle_id="c", member_id="m1", level="owner")

async def test_other_errors_pass_through(self, mcp: FastMCP, client: MagicMock) -> None:
client.ocs_put_json.side_effect = NextcloudError("OCS PUT x: Member not found", 404)
with pytest.raises(ToolError, match="Member not found"):
await _call(mcp, "update_circle_member_level", circle_id="c", member_id="m1", level="owner")

async def test_sqlite_refusal(self, mcp: FastMCP, client: MagicMock) -> None:
message = "OCS PUT x: Operation 'FOR UPDATE' is not supported by platform."
client.ocs_put_json.side_effect = NextcloudError(message, 500)
with pytest.raises(ToolError, match="cannot transfer ownership"):
await _call(mcp, "update_circle_member_level", circle_id="c", member_id="m1", level="owner")

async def test_other_for_update_errors_pass_through(self, mcp: FastMCP, client: MagicMock) -> None:
client.ocs_put_json.side_effect = NextcloudError("OCS PUT x: deadlock detected while waiting FOR UPDATE", 500)
with pytest.raises(ToolError, match="deadlock detected"):
await _call(mcp, "update_circle_member_level", circle_id="c", member_id="m1", level="owner")

async def test_the_lock_message_only_applies_to_owner(self, mcp: FastMCP, client: MagicMock) -> None:
client.ocs_put_json.side_effect = LOCK_ERROR
with pytest.raises(ToolError, match="FOR UPDATE cannot be applied"):
await _call(mcp, "update_circle_member_level", circle_id="c", member_id="m1", level="admin")
Loading