From 09006fcea93c78c933697afffc8021fa6e410a8b Mon Sep 17 00:00:00 2001 From: Chris Coutinho Date: Tue, 7 Apr 2026 22:46:32 +0200 Subject: [PATCH 1/4] feat: add stdio transport support for local MCP usage Add a lightweight stdio transport path so users can run the server locally with MCP clients like Claude Code using `uvx nextcloud-mcp-server run`. - New `nextcloud_mcp_server/stdio.py` with minimal FastMCP setup for single-user BasicAuth (no OAuth, semantic search, or background sync) - Default transport changed from streamable-http to stdio - Dockerfile updated to explicitly use streamable-http for containers - CLI `--enable-app` now includes news, collectives, and sharing - README Quick Start section with uvx and MCP client config examples Co-Authored-By: Claude Opus 4.6 (1M context) --- Dockerfile | 2 +- README.md | 39 +++++++++-- nextcloud_mcp_server/cli.py | 33 ++++++++- nextcloud_mcp_server/stdio.py | 128 ++++++++++++++++++++++++++++++++++ tests/test_cli.py | 57 +++++++++++++-- tests/unit/test_stdio.py | 96 +++++++++++++++++++++++++ 6 files changed, 342 insertions(+), 13 deletions(-) create mode 100644 nextcloud_mcp_server/stdio.py create mode 100644 tests/unit/test_stdio.py diff --git a/Dockerfile b/Dockerfile index 39b16066..90264468 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,4 +27,4 @@ ENV VIRTUAL_ENV=/app/.venv ENV PATH=/app/.venv/bin:$PATH ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/5/tessdata -ENTRYPOINT ["/app/.venv/bin/nextcloud-mcp-server", "run", "--host", "0.0.0.0"] +ENTRYPOINT ["/app/.venv/bin/nextcloud-mcp-server", "run", "--transport", "streamable-http", "--host", "0.0.0.0"] diff --git a/README.md b/README.md index 1cab6035..601aced4 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,39 @@ This is a **dedicated standalone MCP server** designed for external MCP clients > [!NOTE] > **Looking for AI features inside Nextcloud?** Nextcloud also provides [Context Agent](https://github.com/nextcloud/context_agent), which powers the Assistant app and runs as an ExApp inside Nextcloud. See [docs/comparison-context-agent.md](docs/comparison-context-agent.md) for a detailed comparison of use cases. -## Quick Start (Docker) +## Quick Start + +Run the server locally with [uvx](https://docs.astral.sh/uv/) (no installation required): + +```bash +NEXTCLOUD_HOST=https://your.nextcloud.instance.com \ +NEXTCLOUD_USERNAME=your_username \ +NEXTCLOUD_PASSWORD=your_app_password \ + uvx nextcloud-mcp-server run +``` + +Or add it directly to your MCP client configuration (e.g. `claude_desktop_config.json` or `.claude/settings.json`): + +```json +{ + "mcpServers": { + "nextcloud": { + "command": "uvx", + "args": ["nextcloud-mcp-server", "run"], + "env": { + "NEXTCLOUD_HOST": "https://your.nextcloud.instance.com", + "NEXTCLOUD_USERNAME": "your_username", + "NEXTCLOUD_PASSWORD": "your_app_password" + } + } + } +} +``` + +> [!TIP] +> Generate an [app password](https://docs.nextcloud.com/server/latest/user_manual/en/session_management.html#managing-devices) in Nextcloud under **Settings > Security > Devices & sessions** instead of using your login password. + +### Docker For full features including semantic search, run with Docker: @@ -35,9 +67,6 @@ docker run -p 127.0.0.1:8000:8000 --env-file .env --rm \ curl http://127.0.0.1:8000/health/ready # 4. Connect to the endpoint -http://127.0.0.1:8000/sse - -# Or with --transport streamable-http http://127.0.0.1:8000/mcp ``` @@ -62,7 +91,7 @@ docker compose --profile login-flow up -d # Port 8004 - **Document Processing** - OCR and text extraction from PDFs, DOCX, images with progress notifications - **Flexible Deployment** - Docker, Kubernetes ([Helm chart](https://github.com/cbcoutinho/helm-charts)), VM, or local installation - **Production-Ready Auth** - Basic Auth with app passwords (recommended) or OAuth2/OIDC (experimental) -- **Multiple Transports** - SSE, HTTP, and streamable-http support +- **Multiple Transports** - stdio (default) and streamable-http ## Supported Apps diff --git a/nextcloud_mcp_server/cli.py b/nextcloud_mcp_server/cli.py index 4fcf8612..645453cc 100644 --- a/nextcloud_mcp_server/cli.py +++ b/nextcloud_mcp_server/cli.py @@ -36,9 +36,9 @@ from .app import get_app @click.option( "--transport", "-t", - default="streamable-http", + default="stdio", show_default=True, - type=click.Choice(["streamable-http", "http"]), + type=click.Choice(["stdio", "streamable-http", "http"]), help="MCP transport protocol", ) @click.option( @@ -46,7 +46,18 @@ from .app import get_app "-e", multiple=True, type=click.Choice( - ["notes", "tables", "webdav", "calendar", "contacts", "cookbook", "deck"] + [ + "notes", + "tables", + "webdav", + "calendar", + "contacts", + "cookbook", + "deck", + "news", + "collectives", + "sharing", + ] ), help="Enable specific Nextcloud app APIs. Can be specified multiple times. If not specified, all apps are enabled.", ) @@ -158,6 +169,9 @@ def run( # OAuth with public issuer URL (for Docker/proxy setups) $ nextcloud-mcp-server --nextcloud-host=http://app --oauth \\ --public-issuer-url=http://localhost:8080 + + # stdio transport for local use (e.g. Claude Code) + $ nextcloud-mcp-server run --transport stdio """ # Set env vars from CLI options if provided if nextcloud_host: @@ -241,6 +255,19 @@ def run( enabled_apps = list(enable_app) if enable_app else None + if transport == "stdio": + if oauth is True: + raise click.ClickException( + "stdio transport does not support OAuth mode. " + "Use single-user BasicAuth with NEXTCLOUD_HOST, " + "NEXTCLOUD_USERNAME, and NEXTCLOUD_PASSWORD." + ) + from .stdio import get_stdio_mcp # noqa: PLC0415 + + mcp = get_stdio_mcp(enabled_apps=enabled_apps) + mcp.run(transport="stdio") + return + app = get_app(transport=transport, enabled_apps=enabled_apps) # Get observability settings and create uvicorn logging config diff --git a/nextcloud_mcp_server/stdio.py b/nextcloud_mcp_server/stdio.py new file mode 100644 index 00000000..b4952b90 --- /dev/null +++ b/nextcloud_mcp_server/stdio.py @@ -0,0 +1,128 @@ +"""Lightweight stdio transport for the Nextcloud MCP server. + +Provides a minimal FastMCP instance suitable for ``mcp.run(transport="stdio")``. +Only single-user BasicAuth mode is supported. Background sync, semantic search, +OAuth, and observability infrastructure are deliberately excluded. +""" + +from __future__ import annotations + +import logging +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass +from typing import Callable + +from mcp.server.fastmcp import Context, FastMCP + +from nextcloud_mcp_server.client import NextcloudClient +from nextcloud_mcp_server.config import get_settings +from nextcloud_mcp_server.config_validators import AuthMode, validate_configuration +from nextcloud_mcp_server.context import get_client as get_nextcloud_client +from nextcloud_mcp_server.server import ( + configure_calendar_tools, + configure_collectives_tools, + configure_contacts_tools, + configure_cookbook_tools, + configure_deck_tools, + configure_news_tools, + configure_notes_tools, + configure_sharing_tools, + configure_tables_tools, + configure_webdav_tools, +) + +logger = logging.getLogger(__name__) + + +@dataclass +class StdioContext: + """Minimal lifespan context for stdio transport. + + Carries only the shared :class:`NextcloudClient`. The ``client`` + attribute satisfies the duck-type check in + :func:`nextcloud_mcp_server.context.get_client`. + """ + + client: NextcloudClient + + +@asynccontextmanager +async def stdio_lifespan(server: FastMCP) -> AsyncIterator[StdioContext]: + """Create and tear down a single :class:`NextcloudClient`.""" + logger.info("Starting MCP server in stdio mode (single-user BasicAuth)") + client = NextcloudClient.from_env() + try: + yield StdioContext(client=client) + finally: + await client.close() + logger.info("stdio session shut down") + + +def get_stdio_mcp(enabled_apps: list[str] | None = None) -> FastMCP: + """Return a :class:`FastMCP` instance configured for stdio transport. + + Parameters + ---------- + enabled_apps: + Whitelist of Nextcloud app names to register. ``None`` means all. + + Raises + ------ + ValueError + If the current configuration is not single-user BasicAuth. + """ + settings = get_settings() + mode, config_errors = validate_configuration(settings) + + if config_errors: + raise ValueError( + f"Configuration validation failed for {mode.value} mode:\n" + + "\n".join(f" - {err}" for err in config_errors) + ) + + if mode != AuthMode.SINGLE_USER_BASIC: + raise ValueError( + f"stdio transport only supports single-user BasicAuth mode, " + f"but detected {mode.value}. Set NEXTCLOUD_HOST, NEXTCLOUD_USERNAME, " + f"and NEXTCLOUD_PASSWORD." + ) + + mcp = FastMCP("Nextcloud MCP", lifespan=stdio_lifespan) + + # --- capabilities resource (mirrors app.py) --- + @mcp.resource("nc://capabilities") + async def nc_get_capabilities(): + """Get the Nextcloud Host capabilities""" + ctx: Context = mcp.get_context() + client = await get_nextcloud_client(ctx) + return await client.capabilities() + + # --- tool registration --- + available_apps: dict[str, Callable] = { + "notes": configure_notes_tools, + "tables": configure_tables_tools, + "webdav": configure_webdav_tools, + "sharing": configure_sharing_tools, + "calendar": configure_calendar_tools, + "collectives": configure_collectives_tools, + "contacts": configure_contacts_tools, + "cookbook": configure_cookbook_tools, + "deck": configure_deck_tools, + "news": configure_news_tools, + } + + if enabled_apps is None: + enabled_apps = list(available_apps.keys()) + + for app_name in enabled_apps: + if app_name in available_apps: + logger.info(f"Configuring {app_name} tools") + available_apps[app_name](mcp) + else: + logger.warning( + f"Unknown app: {app_name}. " + f"Available apps: {list(available_apps.keys())}" + ) + + return mcp diff --git a/tests/test_cli.py b/tests/test_cli.py index 0481955f..40570c31 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -108,6 +108,8 @@ def test_cli_options_set_environment_variables(runner, clean_env, monkeypatch): _ = runner.invoke( run, [ + "--transport", + "streamable-http", "--nextcloud-host", "https://test.example.com", "--nextcloud-username", @@ -164,6 +166,8 @@ def test_cli_options_override_environment_variables(runner, monkeypatch): _ = runner.invoke( run, [ + "--transport", + "streamable-http", "--nextcloud-host", "https://from-cli.example.com", "--nextcloud-username", @@ -214,7 +218,7 @@ def test_environment_variables_used_when_cli_not_provided(runner, monkeypatch): monkeypatch.setattr("nextcloud_mcp_server.cli.get_app", mock_get_app) # Don't provide any CLI options - should use env vars - _ = runner.invoke(run, []) + _ = runner.invoke(run, ["--transport", "streamable-http"]) # Verify env vars were used assert captured_env["NEXTCLOUD_HOST"] == "https://from-env.example.com" @@ -246,7 +250,7 @@ def test_default_values(runner, clean_env, monkeypatch): monkeypatch.setattr("nextcloud_mcp_server.cli.get_app", mock_get_app) # Don't provide CLI options or env vars - should use defaults - _ = runner.invoke(run, []) + _ = runner.invoke(run, ["--transport", "streamable-http"]) # Verify default values assert captured_env["NEXTCLOUD_OIDC_SCOPES"] == ( @@ -278,10 +282,55 @@ def test_oauth_token_type_case_normalization(runner, clean_env, monkeypatch): monkeypatch.setattr("nextcloud_mcp_server.cli.get_app", mock_get_app) # Test uppercase JWT - runner.invoke(run, ["--oauth-token-type", "JWT"]) + runner.invoke(run, ["--transport", "streamable-http", "--oauth-token-type", "JWT"]) assert captured_env["NEXTCLOUD_OIDC_TOKEN_TYPE"] in ["JWT", "jwt"] # Test mixed case Bearer captured_env.clear() - runner.invoke(run, ["--oauth-token-type", "Bearer"]) + runner.invoke( + run, ["--transport", "streamable-http", "--oauth-token-type", "Bearer"] + ) assert captured_env["NEXTCLOUD_OIDC_TOKEN_TYPE"] in ["Bearer", "bearer"] + + +def test_help_includes_stdio_transport(runner): + """Test that stdio appears as a transport option in help output.""" + result = runner.invoke(run, ["--help"]) + assert result.exit_code == 0 + assert "stdio" in result.output + + +def test_stdio_rejects_oauth_flag(runner, clean_env, monkeypatch): + """Test that --transport stdio --oauth raises an error.""" + monkeypatch.setenv("NEXTCLOUD_HOST", "https://cloud.example.com") + result = runner.invoke(run, ["--transport", "stdio", "--oauth"]) + assert result.exit_code != 0 + assert "stdio transport does not support OAuth mode" in result.output + + +def test_stdio_calls_get_stdio_mcp(runner, clean_env, monkeypatch): + """Test that --transport stdio invokes the stdio code path.""" + monkeypatch.setenv("NEXTCLOUD_HOST", "https://cloud.example.com") + monkeypatch.setenv("NEXTCLOUD_USERNAME", "admin") + monkeypatch.setenv("NEXTCLOUD_PASSWORD", "secret") + + called_with = {} + + class FakeMcp: + def run(self, transport): + called_with["transport"] = transport + + def mock_get_stdio_mcp(enabled_apps=None): + called_with["enabled_apps"] = enabled_apps + return FakeMcp() + + monkeypatch.setattr( + "nextcloud_mcp_server.cli.get_stdio_mcp", mock_get_stdio_mcp, raising=False + ) + # The lazy import means we need to patch at the module level it imports from + monkeypatch.setattr("nextcloud_mcp_server.stdio.get_stdio_mcp", mock_get_stdio_mcp) + + result = runner.invoke(run, ["--transport", "stdio"]) + assert result.exit_code == 0, result.output + assert called_with.get("transport") == "stdio" + assert called_with.get("enabled_apps") is None diff --git a/tests/unit/test_stdio.py b/tests/unit/test_stdio.py new file mode 100644 index 00000000..371a3139 --- /dev/null +++ b/tests/unit/test_stdio.py @@ -0,0 +1,96 @@ +"""Unit tests for the stdio transport module.""" + +import pytest +from mcp.server.fastmcp import FastMCP + +from nextcloud_mcp_server.config_validators import AuthMode +from nextcloud_mcp_server.stdio import get_stdio_mcp + + +@pytest.fixture +def single_user_env(monkeypatch): + """Set up environment variables for single-user BasicAuth mode.""" + monkeypatch.setenv("NEXTCLOUD_HOST", "https://cloud.example.com") + monkeypatch.setenv("NEXTCLOUD_USERNAME", "admin") + monkeypatch.setenv("NEXTCLOUD_PASSWORD", "secret") + + +@pytest.mark.unit +def test_get_stdio_mcp_returns_fastmcp(single_user_env): + """get_stdio_mcp returns a FastMCP instance with correct env vars.""" + mcp = get_stdio_mcp() + assert isinstance(mcp, FastMCP) + + +@pytest.mark.unit +def test_get_stdio_mcp_rejects_config_errors(monkeypatch): + """get_stdio_mcp raises ValueError when validate_configuration reports errors.""" + monkeypatch.setattr( + "nextcloud_mcp_server.stdio.validate_configuration", + lambda _settings: (AuthMode.SINGLE_USER_BASIC, ["missing nextcloud_host"]), + ) + with pytest.raises(ValueError, match="Configuration validation failed"): + get_stdio_mcp() + + +@pytest.mark.unit +def test_get_stdio_mcp_rejects_non_single_user_mode(monkeypatch): + """get_stdio_mcp raises ValueError for non-single-user modes.""" + monkeypatch.setattr( + "nextcloud_mcp_server.stdio.validate_configuration", + lambda _settings: (AuthMode.MULTI_USER_BASIC, []), + ) + with pytest.raises(ValueError, match="single-user BasicAuth"): + get_stdio_mcp() + + +@pytest.mark.unit +def test_get_stdio_mcp_registers_all_apps_by_default(single_user_env): + """All app tool groups are registered when no filter is specified.""" + mcp = get_stdio_mcp() + tools = mcp._tool_manager.list_tools() + tool_names = {t.name for t in tools} + + # Spot-check representative tools from each app + assert "nc_notes_get_note" in tool_names + assert "nc_webdav_list_directory" in tool_names + assert "nc_calendar_list_calendars" in tool_names + assert "nc_contacts_list_addressbooks" in tool_names + assert "nc_cookbook_list_recipes" in tool_names + assert "deck_get_boards" in tool_names + assert "nc_tables_list_tables" in tool_names + assert "nc_share_list" in tool_names + assert "nc_news_list_feeds" in tool_names + assert "collectives_get_collectives" in tool_names + + +@pytest.mark.unit +def test_get_stdio_mcp_respects_enabled_apps(single_user_env): + """Only specified apps have their tools registered.""" + mcp = get_stdio_mcp(enabled_apps=["notes"]) + tools = mcp._tool_manager.list_tools() + tool_names = {t.name for t in tools} + + assert "nc_notes_get_note" in tool_names + # Other apps should NOT be present + assert "nc_webdav_list_directory" not in tool_names + assert "nc_calendar_list_calendars" not in tool_names + + +@pytest.mark.unit +def test_get_stdio_mcp_no_semantic_tools(single_user_env): + """Semantic search tools are never registered in stdio mode.""" + mcp = get_stdio_mcp() + tools = mcp._tool_manager.list_tools() + tool_names = {t.name for t in tools} + + semantic_names = [n for n in tool_names if "semantic" in n or "vector" in n] + assert semantic_names == [], f"Unexpected semantic tools: {semantic_names}" + + +@pytest.mark.unit +def test_get_stdio_mcp_registers_capabilities_resource(single_user_env): + """The nc://capabilities resource is registered.""" + mcp = get_stdio_mcp() + resources = mcp._resource_manager._resources + assert "nc://capabilities" in resources From e9c46a04a029315b902315a7df50c73f562850e3 Mon Sep 17 00:00:00 2001 From: Chris Coutinho Date: Tue, 7 Apr 2026 23:03:12 +0200 Subject: [PATCH 2/4] fix: address PR review feedback and fix CI test failures - Revert default transport to streamable-http (not a breaking change) - Extract AVAILABLE_APPS constant to server/__init__.py (DRY) - Wrap get_stdio_mcp ValueError in click.ClickException for clean errors - Fix test_stdio.py: call _reload_config() so dynaconf sees env changes - Use lazy %-style logging in stdio.py - Add private API comments in test assertions - Derive --enable-app CLI choices from AVAILABLE_APPS - README: show explicit --transport stdio in uvx examples Co-Authored-By: Claude Opus 4.6 (1M context) --- Dockerfile | 2 +- README.md | 4 +-- nextcloud_mcp_server/app.py | 33 ++++---------------- nextcloud_mcp_server/cli.py | 25 +++++----------- nextcloud_mcp_server/server/__init__.py | 20 +++++++++++++ nextcloud_mcp_server/stdio.py | 40 +++++-------------------- tests/test_cli.py | 14 +++------ tests/unit/test_stdio.py | 8 +++++ 8 files changed, 56 insertions(+), 90 deletions(-) diff --git a/Dockerfile b/Dockerfile index 90264468..39b16066 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,4 +27,4 @@ ENV VIRTUAL_ENV=/app/.venv ENV PATH=/app/.venv/bin:$PATH ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/5/tessdata -ENTRYPOINT ["/app/.venv/bin/nextcloud-mcp-server", "run", "--transport", "streamable-http", "--host", "0.0.0.0"] +ENTRYPOINT ["/app/.venv/bin/nextcloud-mcp-server", "run", "--host", "0.0.0.0"] diff --git a/README.md b/README.md index 601aced4..b5664fd9 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Run the server locally with [uvx](https://docs.astral.sh/uv/) (no installation r NEXTCLOUD_HOST=https://your.nextcloud.instance.com \ NEXTCLOUD_USERNAME=your_username \ NEXTCLOUD_PASSWORD=your_app_password \ - uvx nextcloud-mcp-server run + uvx nextcloud-mcp-server run --transport stdio ``` Or add it directly to your MCP client configuration (e.g. `claude_desktop_config.json` or `.claude/settings.json`): @@ -33,7 +33,7 @@ Or add it directly to your MCP client configuration (e.g. `claude_desktop_config "mcpServers": { "nextcloud": { "command": "uvx", - "args": ["nextcloud-mcp-server", "run"], + "args": ["nextcloud-mcp-server", "run", "--transport", "stdio"], "env": { "NEXTCLOUD_HOST": "https://your.nextcloud.instance.com", "NEXTCLOUD_USERNAME": "your_username", diff --git a/nextcloud_mcp_server/app.py b/nextcloud_mcp_server/app.py index 750727fa..c5a39675 100644 --- a/nextcloud_mcp_server/app.py +++ b/nextcloud_mcp_server/app.py @@ -119,17 +119,8 @@ from nextcloud_mcp_server.observability.metrics import ( set_dependency_health, ) from nextcloud_mcp_server.server import ( - configure_calendar_tools, - configure_collectives_tools, - configure_contacts_tools, - configure_cookbook_tools, - configure_deck_tools, - configure_news_tools, - configure_notes_tools, + AVAILABLE_APPS, configure_semantic_tools, - configure_sharing_tools, - configure_tables_tools, - configure_webdav_tools, ) from nextcloud_mcp_server.server.auth_tools import register_auth_tools from nextcloud_mcp_server.server.oauth_tools import register_oauth_tools @@ -1232,32 +1223,18 @@ def get_app(transport: str = "streamable-http", enabled_apps: list[str] | None = client = await get_nextcloud_client(ctx) return await client.capabilities() - # Define available apps and their configuration functions - available_apps = { - "notes": configure_notes_tools, - "tables": configure_tables_tools, - "webdav": configure_webdav_tools, - "sharing": configure_sharing_tools, - "calendar": configure_calendar_tools, - "collectives": configure_collectives_tools, - "contacts": configure_contacts_tools, - "cookbook": configure_cookbook_tools, - "deck": configure_deck_tools, - "news": configure_news_tools, - } - # If no specific apps are specified, enable all if enabled_apps is None: - enabled_apps = list(available_apps.keys()) + enabled_apps = list(AVAILABLE_APPS.keys()) # Configure only the enabled apps for app_name in enabled_apps: - if app_name in available_apps: + if app_name in AVAILABLE_APPS: logger.info(f"Configuring {app_name} tools") - available_apps[app_name](mcp) + AVAILABLE_APPS[app_name](mcp) else: logger.warning( - f"Unknown app: {app_name}. Available apps: {list(available_apps.keys())}" + f"Unknown app: {app_name}. Available apps: {list(AVAILABLE_APPS.keys())}" ) # Register semantic search tools (cross-app feature) diff --git a/nextcloud_mcp_server/cli.py b/nextcloud_mcp_server/cli.py index 645453cc..615bd577 100644 --- a/nextcloud_mcp_server/cli.py +++ b/nextcloud_mcp_server/cli.py @@ -14,6 +14,7 @@ from nextcloud_mcp_server.migrations import ( upgrade_database, ) from nextcloud_mcp_server.observability import get_uvicorn_logging_config +from nextcloud_mcp_server.server import AVAILABLE_APPS from .app import get_app @@ -36,29 +37,16 @@ from .app import get_app @click.option( "--transport", "-t", - default="stdio", + default="streamable-http", show_default=True, - type=click.Choice(["stdio", "streamable-http", "http"]), + type=click.Choice(["streamable-http", "http", "stdio"]), help="MCP transport protocol", ) @click.option( "--enable-app", "-e", multiple=True, - type=click.Choice( - [ - "notes", - "tables", - "webdav", - "calendar", - "contacts", - "cookbook", - "deck", - "news", - "collectives", - "sharing", - ] - ), + type=click.Choice(sorted(AVAILABLE_APPS.keys())), help="Enable specific Nextcloud app APIs. Can be specified multiple times. If not specified, all apps are enabled.", ) @click.option( @@ -264,7 +252,10 @@ def run( ) from .stdio import get_stdio_mcp # noqa: PLC0415 - mcp = get_stdio_mcp(enabled_apps=enabled_apps) + try: + mcp = get_stdio_mcp(enabled_apps=enabled_apps) + except ValueError as e: + raise click.ClickException(str(e)) from e mcp.run(transport="stdio") return diff --git a/nextcloud_mcp_server/server/__init__.py b/nextcloud_mcp_server/server/__init__.py index c7c053a9..38ba6ea3 100644 --- a/nextcloud_mcp_server/server/__init__.py +++ b/nextcloud_mcp_server/server/__init__.py @@ -1,3 +1,5 @@ +from typing import Callable + from .calendar import configure_calendar_tools from .collectives import configure_collectives_tools from .contacts import configure_contacts_tools @@ -10,7 +12,25 @@ from .sharing import configure_sharing_tools from .tables import configure_tables_tools from .webdav import configure_webdav_tools +# Canonical mapping of app name → tool registration function. +# Used by app.py (HTTP), stdio.py (stdio), and cli.py (--enable-app choices). +# Semantic search is excluded here because it is a cross-app feature gated +# by VECTOR_SYNC_ENABLED, not an individual Nextcloud app. +AVAILABLE_APPS: dict[str, Callable] = { + "notes": configure_notes_tools, + "tables": configure_tables_tools, + "webdav": configure_webdav_tools, + "sharing": configure_sharing_tools, + "calendar": configure_calendar_tools, + "collectives": configure_collectives_tools, + "contacts": configure_contacts_tools, + "cookbook": configure_cookbook_tools, + "deck": configure_deck_tools, + "news": configure_news_tools, +} + __all__ = [ + "AVAILABLE_APPS", "configure_calendar_tools", "configure_collectives_tools", "configure_contacts_tools", diff --git a/nextcloud_mcp_server/stdio.py b/nextcloud_mcp_server/stdio.py index b4952b90..152bb18c 100644 --- a/nextcloud_mcp_server/stdio.py +++ b/nextcloud_mcp_server/stdio.py @@ -11,7 +11,6 @@ import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import dataclass -from typing import Callable from mcp.server.fastmcp import Context, FastMCP @@ -19,18 +18,7 @@ from nextcloud_mcp_server.client import NextcloudClient from nextcloud_mcp_server.config import get_settings from nextcloud_mcp_server.config_validators import AuthMode, validate_configuration from nextcloud_mcp_server.context import get_client as get_nextcloud_client -from nextcloud_mcp_server.server import ( - configure_calendar_tools, - configure_collectives_tools, - configure_contacts_tools, - configure_cookbook_tools, - configure_deck_tools, - configure_news_tools, - configure_notes_tools, - configure_sharing_tools, - configure_tables_tools, - configure_webdav_tools, -) +from nextcloud_mcp_server.server import AVAILABLE_APPS logger = logging.getLogger(__name__) @@ -99,30 +87,18 @@ def get_stdio_mcp(enabled_apps: list[str] | None = None) -> FastMCP: return await client.capabilities() # --- tool registration --- - available_apps: dict[str, Callable] = { - "notes": configure_notes_tools, - "tables": configure_tables_tools, - "webdav": configure_webdav_tools, - "sharing": configure_sharing_tools, - "calendar": configure_calendar_tools, - "collectives": configure_collectives_tools, - "contacts": configure_contacts_tools, - "cookbook": configure_cookbook_tools, - "deck": configure_deck_tools, - "news": configure_news_tools, - } - if enabled_apps is None: - enabled_apps = list(available_apps.keys()) + enabled_apps = list(AVAILABLE_APPS.keys()) for app_name in enabled_apps: - if app_name in available_apps: - logger.info(f"Configuring {app_name} tools") - available_apps[app_name](mcp) + if app_name in AVAILABLE_APPS: + logger.info("Configuring %s tools", app_name) + AVAILABLE_APPS[app_name](mcp) else: logger.warning( - f"Unknown app: {app_name}. " - f"Available apps: {list(available_apps.keys())}" + "Unknown app: %s. Available apps: %s", + app_name, + list(AVAILABLE_APPS.keys()), ) return mcp diff --git a/tests/test_cli.py b/tests/test_cli.py index 40570c31..c97c0132 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -108,8 +108,6 @@ def test_cli_options_set_environment_variables(runner, clean_env, monkeypatch): _ = runner.invoke( run, [ - "--transport", - "streamable-http", "--nextcloud-host", "https://test.example.com", "--nextcloud-username", @@ -166,8 +164,6 @@ def test_cli_options_override_environment_variables(runner, monkeypatch): _ = runner.invoke( run, [ - "--transport", - "streamable-http", "--nextcloud-host", "https://from-cli.example.com", "--nextcloud-username", @@ -218,7 +214,7 @@ def test_environment_variables_used_when_cli_not_provided(runner, monkeypatch): monkeypatch.setattr("nextcloud_mcp_server.cli.get_app", mock_get_app) # Don't provide any CLI options - should use env vars - _ = runner.invoke(run, ["--transport", "streamable-http"]) + _ = runner.invoke(run, []) # Verify env vars were used assert captured_env["NEXTCLOUD_HOST"] == "https://from-env.example.com" @@ -250,7 +246,7 @@ def test_default_values(runner, clean_env, monkeypatch): monkeypatch.setattr("nextcloud_mcp_server.cli.get_app", mock_get_app) # Don't provide CLI options or env vars - should use defaults - _ = runner.invoke(run, ["--transport", "streamable-http"]) + _ = runner.invoke(run, []) # Verify default values assert captured_env["NEXTCLOUD_OIDC_SCOPES"] == ( @@ -282,14 +278,12 @@ def test_oauth_token_type_case_normalization(runner, clean_env, monkeypatch): monkeypatch.setattr("nextcloud_mcp_server.cli.get_app", mock_get_app) # Test uppercase JWT - runner.invoke(run, ["--transport", "streamable-http", "--oauth-token-type", "JWT"]) + runner.invoke(run, ["--oauth-token-type", "JWT"]) assert captured_env["NEXTCLOUD_OIDC_TOKEN_TYPE"] in ["JWT", "jwt"] # Test mixed case Bearer captured_env.clear() - runner.invoke( - run, ["--transport", "streamable-http", "--oauth-token-type", "Bearer"] - ) + runner.invoke(run, ["--oauth-token-type", "Bearer"]) assert captured_env["NEXTCLOUD_OIDC_TOKEN_TYPE"] in ["Bearer", "bearer"] diff --git a/tests/unit/test_stdio.py b/tests/unit/test_stdio.py index 371a3139..06602f80 100644 --- a/tests/unit/test_stdio.py +++ b/tests/unit/test_stdio.py @@ -3,6 +3,7 @@ import pytest from mcp.server.fastmcp import FastMCP +from nextcloud_mcp_server.config import _reload_config from nextcloud_mcp_server.config_validators import AuthMode from nextcloud_mcp_server.stdio import get_stdio_mcp @@ -13,6 +14,9 @@ def single_user_env(monkeypatch): monkeypatch.setenv("NEXTCLOUD_HOST", "https://cloud.example.com") monkeypatch.setenv("NEXTCLOUD_USERNAME", "admin") monkeypatch.setenv("NEXTCLOUD_PASSWORD", "secret") + # Ensure multi-user mode is off (may leak from other tests) + monkeypatch.delenv("ENABLE_MULTI_USER_BASIC_AUTH", raising=False) + _reload_config() @pytest.mark.unit @@ -48,6 +52,7 @@ def test_get_stdio_mcp_rejects_non_single_user_mode(monkeypatch): def test_get_stdio_mcp_registers_all_apps_by_default(single_user_env): """All app tool groups are registered when no filter is specified.""" mcp = get_stdio_mcp() + # NOTE: _tool_manager is a FastMCP internal; may break on SDK upgrades tools = mcp._tool_manager.list_tools() tool_names = {t.name for t in tools} @@ -68,6 +73,7 @@ def test_get_stdio_mcp_registers_all_apps_by_default(single_user_env): def test_get_stdio_mcp_respects_enabled_apps(single_user_env): """Only specified apps have their tools registered.""" mcp = get_stdio_mcp(enabled_apps=["notes"]) + # NOTE: _tool_manager is a FastMCP internal; may break on SDK upgrades tools = mcp._tool_manager.list_tools() tool_names = {t.name for t in tools} @@ -81,6 +87,7 @@ def test_get_stdio_mcp_respects_enabled_apps(single_user_env): def test_get_stdio_mcp_no_semantic_tools(single_user_env): """Semantic search tools are never registered in stdio mode.""" mcp = get_stdio_mcp() + # NOTE: _tool_manager is a FastMCP internal; may break on SDK upgrades tools = mcp._tool_manager.list_tools() tool_names = {t.name for t in tools} @@ -92,5 +99,6 @@ def test_get_stdio_mcp_no_semantic_tools(single_user_env): def test_get_stdio_mcp_registers_capabilities_resource(single_user_env): """The nc://capabilities resource is registered.""" mcp = get_stdio_mcp() + # NOTE: _resource_manager._resources is a FastMCP internal; may break on SDK upgrades resources = mcp._resource_manager._resources assert "nc://capabilities" in resources From 1af85bc05e864baf7ae8961b02550c0d176c5b1e Mon Sep 17 00:00:00 2001 From: Chris Coutinho Date: Tue, 7 Apr 2026 23:26:46 +0200 Subject: [PATCH 3/4] fix: address second round of review feedback - Remove dead monkeypatch in test_stdio_calls_get_stdio_mcp - Add _reload_config() teardown to single_user_env fixture - Tighten AVAILABLE_APPS type to Callable[[FastMCP], None] Co-Authored-By: Claude Opus 4.6 (1M context) --- nextcloud_mcp_server/server/__init__.py | 6 ++++-- tests/test_cli.py | 4 ---- tests/unit/test_stdio.py | 2 ++ 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/nextcloud_mcp_server/server/__init__.py b/nextcloud_mcp_server/server/__init__.py index 38ba6ea3..45fab885 100644 --- a/nextcloud_mcp_server/server/__init__.py +++ b/nextcloud_mcp_server/server/__init__.py @@ -1,4 +1,6 @@ -from typing import Callable +from collections.abc import Callable + +from mcp.server.fastmcp import FastMCP from .calendar import configure_calendar_tools from .collectives import configure_collectives_tools @@ -16,7 +18,7 @@ from .webdav import configure_webdav_tools # Used by app.py (HTTP), stdio.py (stdio), and cli.py (--enable-app choices). # Semantic search is excluded here because it is a cross-app feature gated # by VECTOR_SYNC_ENABLED, not an individual Nextcloud app. -AVAILABLE_APPS: dict[str, Callable] = { +AVAILABLE_APPS: dict[str, Callable[[FastMCP], None]] = { "notes": configure_notes_tools, "tables": configure_tables_tools, "webdav": configure_webdav_tools, diff --git a/tests/test_cli.py b/tests/test_cli.py index c97c0132..9d25dae9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -318,10 +318,6 @@ def test_stdio_calls_get_stdio_mcp(runner, clean_env, monkeypatch): called_with["enabled_apps"] = enabled_apps return FakeMcp() - monkeypatch.setattr( - "nextcloud_mcp_server.cli.get_stdio_mcp", mock_get_stdio_mcp, raising=False - ) - # The lazy import means we need to patch at the module level it imports from monkeypatch.setattr("nextcloud_mcp_server.stdio.get_stdio_mcp", mock_get_stdio_mcp) result = runner.invoke(run, ["--transport", "stdio"]) diff --git a/tests/unit/test_stdio.py b/tests/unit/test_stdio.py index 06602f80..a70053be 100644 --- a/tests/unit/test_stdio.py +++ b/tests/unit/test_stdio.py @@ -17,6 +17,8 @@ def single_user_env(monkeypatch): # Ensure multi-user mode is off (may leak from other tests) monkeypatch.delenv("ENABLE_MULTI_USER_BASIC_AUTH", raising=False) _reload_config() + yield + _reload_config() @pytest.mark.unit From f340380898283d1370a86e3df3fc1443718bdcd6 Mon Sep 17 00:00:00 2001 From: Chris Coutinho Date: Tue, 7 Apr 2026 23:59:39 +0200 Subject: [PATCH 4/4] fix: address third round of review feedback Add BasicAuthLifespanContext Protocol to make the contract between StdioContext and get_client() explicit and type-safe. Document why mcp.get_context() is required for non-template resources. Add News and Collectives to README Supported Apps table, fix transport default. Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 6 ++++-- nextcloud_mcp_server/context.py | 14 +++++++++++++- nextcloud_mcp_server/stdio.py | 12 ++++++++---- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index b5664fd9..396cb33b 100644 --- a/README.md +++ b/README.md @@ -85,13 +85,13 @@ docker compose --profile login-flow up -d # Port 8004 ## Key Features -- **90+ MCP Tools** - Comprehensive API coverage across 8 Nextcloud apps +- **110+ MCP Tools** - Comprehensive API coverage across 10 Nextcloud apps - **MCP Resources** - Structured data URIs for browsing Nextcloud data - **Semantic Search (Experimental)** - Optional vector-powered search for Notes, Files, News items, and Deck cards (requires Qdrant + Ollama) - **Document Processing** - OCR and text extraction from PDFs, DOCX, images with progress notifications - **Flexible Deployment** - Docker, Kubernetes ([Helm chart](https://github.com/cbcoutinho/helm-charts)), VM, or local installation - **Production-Ready Auth** - Basic Auth with app passwords (recommended) or OAuth2/OIDC (experimental) -- **Multiple Transports** - stdio (default) and streamable-http +- **Multiple Transports** - streamable-http (default) and stdio ## Supported Apps @@ -105,6 +105,8 @@ docker compose --profile login-flow up -d # Port 8004 | **Cookbook** | 13 | Recipe management, URL import (schema.org) | | **Tables** | 5 | Row operations on Nextcloud Tables | | **Sharing** | 10+ | Create and manage shares | +| **News** | 8 | Feeds, folders, items, feed health monitoring | +| **Collectives** | 16 | Full CRUD on collectives, pages, and tags | | **Semantic Search** | 2+ | Vector search for Notes, Files, News items, and Deck cards (experimental, opt-in, requires infrastructure) | Want to see another Nextcloud app supported? [Open an issue](https://github.com/cbcoutinho/nextcloud-mcp-server/issues) or contribute a pull request! diff --git a/nextcloud_mcp_server/context.py b/nextcloud_mcp_server/context.py index c94b15be..352a64ac 100644 --- a/nextcloud_mcp_server/context.py +++ b/nextcloud_mcp_server/context.py @@ -1,6 +1,7 @@ """Helper functions for accessing context in MCP tools.""" import logging +from typing import Protocol, runtime_checkable from httpx import BasicAuth from mcp.server.fastmcp import Context @@ -14,6 +15,17 @@ from nextcloud_mcp_server.config import get_settings logger = logging.getLogger(__name__) +@runtime_checkable +class BasicAuthLifespanContext(Protocol): + """Protocol for lifespan contexts that carry a shared NextcloudClient. + + Implemented by :class:`~nextcloud_mcp_server.stdio.StdioContext` and + the single-user lifespan context in ``app.py``. + """ + + client: NextcloudClient + + async def get_client(ctx: Context) -> NextcloudClient: """ Get the appropriate Nextcloud client based on authentication mode. @@ -59,7 +71,7 @@ async def get_client(ctx: Context) -> NextcloudClient: return await _get_client_from_login_flow(ctx, lifespan_ctx.nextcloud_host) # BasicAuth mode - use shared client (no token exchange) - if hasattr(lifespan_ctx, "client"): + if isinstance(lifespan_ctx, BasicAuthLifespanContext): return lifespan_ctx.client # OAuth multi-audience mode (has 'nextcloud_host' attribute) diff --git a/nextcloud_mcp_server/stdio.py b/nextcloud_mcp_server/stdio.py index 152bb18c..4fe1d97c 100644 --- a/nextcloud_mcp_server/stdio.py +++ b/nextcloud_mcp_server/stdio.py @@ -17,6 +17,7 @@ from mcp.server.fastmcp import Context, FastMCP from nextcloud_mcp_server.client import NextcloudClient from nextcloud_mcp_server.config import get_settings from nextcloud_mcp_server.config_validators import AuthMode, validate_configuration +from nextcloud_mcp_server.context import BasicAuthLifespanContext from nextcloud_mcp_server.context import get_client as get_nextcloud_client from nextcloud_mcp_server.server import AVAILABLE_APPS @@ -24,12 +25,12 @@ logger = logging.getLogger(__name__) @dataclass -class StdioContext: +class StdioContext(BasicAuthLifespanContext): """Minimal lifespan context for stdio transport. - Carries only the shared :class:`NextcloudClient`. The ``client`` - attribute satisfies the duck-type check in - :func:`nextcloud_mcp_server.context.get_client`. + Implements :class:`~nextcloud_mcp_server.context.BasicAuthLifespanContext` + so that :func:`~nextcloud_mcp_server.context.get_client` recognises it + as a single-user BasicAuth context. """ client: NextcloudClient @@ -79,6 +80,9 @@ def get_stdio_mcp(enabled_apps: list[str] | None = None) -> FastMCP: mcp = FastMCP("Nextcloud MCP", lifespan=stdio_lifespan) # --- capabilities resource (mirrors app.py) --- + # NOTE: mcp.get_context() is required here because FastMCP's + # FunctionResource (non-template resources) does not support + # context parameter injection — only template resources do. @mcp.resource("nc://capabilities") async def nc_get_capabilities(): """Get the Nextcloud Host capabilities"""