Merge pull request #689 from cbcoutinho/feat/stdio-transport

feat: add stdio transport support for local MCP usage
This commit is contained in:
Chris Coutinho
2026-04-08 00:09:49 +02:00
committed by GitHub
8 changed files with 352 additions and 39 deletions
+5 -28
View File
@@ -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)
+22 -4
View File
@@ -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
@@ -38,16 +39,14 @@ from .app import get_app
"-t",
default="streamable-http",
show_default=True,
type=click.Choice(["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"]
),
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(
@@ -158,6 +157,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 +243,22 @@ 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
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
app = get_app(transport=transport, enabled_apps=enabled_apps)
# Get observability settings and create uvicorn logging config
+13 -1
View File
@@ -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)
+22
View File
@@ -1,3 +1,7 @@
from collections.abc import Callable
from mcp.server.fastmcp import FastMCP
from .calendar import configure_calendar_tools
from .collectives import configure_collectives_tools
from .contacts import configure_contacts_tools
@@ -10,7 +14,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[[FastMCP], None]] = {
"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",
+108
View File
@@ -0,0 +1,108 @@
"""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 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
logger = logging.getLogger(__name__)
@dataclass
class StdioContext(BasicAuthLifespanContext):
"""Minimal lifespan context for stdio transport.
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
@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) ---
# 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"""
ctx: Context = mcp.get_context()
client = await get_nextcloud_client(ctx)
return await client.capabilities()
# --- tool registration ---
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("Configuring %s tools", app_name)
AVAILABLE_APPS[app_name](mcp)
else:
logger.warning(
"Unknown app: %s. Available apps: %s",
app_name,
list(AVAILABLE_APPS.keys()),
)
return mcp