|
| 1 | +import logging |
| 2 | +from collections.abc import AsyncIterator |
| 3 | +from contextlib import asynccontextmanager |
| 4 | +from dataclasses import dataclass |
| 5 | + |
| 6 | +from mcp.server.fastmcp import Context, FastMCP |
| 7 | + |
| 8 | +from nextcloud_mcp_server.client import NextcloudClient |
| 9 | +from nextcloud_mcp_server.config import setup_logging |
| 10 | +from nextcloud_mcp_server.server import ( |
| 11 | + configure_calendar_tools, |
| 12 | + configure_notes_tools, |
| 13 | + configure_tables_tools, |
| 14 | + configure_webdav_tools, |
| 15 | +) |
| 16 | + |
| 17 | +setup_logging() |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class AppContext: |
| 22 | + client: NextcloudClient |
| 23 | + |
| 24 | + |
| 25 | +@asynccontextmanager |
| 26 | +async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]: |
| 27 | + """Manage application lifecycle with type-safe context""" |
| 28 | + # Initialize on startup |
| 29 | + logging.info("Creating Nextcloud client") |
| 30 | + client = NextcloudClient.from_env() |
| 31 | + logging.info("Client initialization wait complete.") |
| 32 | + try: |
| 33 | + yield AppContext(client=client) |
| 34 | + finally: |
| 35 | + # Cleanup on shutdown |
| 36 | + await client.close() |
| 37 | + |
| 38 | + |
| 39 | +# Create an MCP server |
| 40 | +mcp = FastMCP("Nextcloud MCP", lifespan=app_lifespan) |
| 41 | + |
| 42 | +logger = logging.getLogger(__name__) |
| 43 | + |
| 44 | + |
| 45 | +@mcp.resource("nc://capabilities") |
| 46 | +async def nc_get_capabilities(): |
| 47 | + """Get the Nextcloud Host capabilities""" |
| 48 | + ctx: Context = ( |
| 49 | + mcp.get_context() |
| 50 | + ) # https://github.com/modelcontextprotocol/python-sdk/issues/244 |
| 51 | + client: NextcloudClient = ctx.request_context.lifespan_context.client |
| 52 | + return await client.capabilities() |
| 53 | + |
| 54 | + |
| 55 | +configure_notes_tools(mcp) |
| 56 | +configure_tables_tools(mcp) |
| 57 | +configure_webdav_tools(mcp) |
| 58 | +configure_calendar_tools(mcp) |
| 59 | + |
| 60 | + |
| 61 | +def run(): |
| 62 | + mcp.run() |
0 commit comments