Spaces:
Sleeping
Sleeping
File size: 8,430 Bytes
507973e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | """Official MCP SDK server — exposes the same 5 task operations as discoverable tools."""
import json
from mcp import types
from mcp.server import Server
from ..core.database import async_session
from ..core.logging import get_logger
from ..models.todo import TodoCreate, TodoUpdate
from ..services import todo_service
logger = get_logger(__name__)
server = Server("todo-mcp-server")
# ---------------------------------------------------------------------------
# Tool definitions
# ---------------------------------------------------------------------------
_TOOL_DEFS: list[types.Tool] = [
types.Tool(
name="add_task",
description="Create a new task for the authenticated user.",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "Authenticated user ID."},
"title": {"type": "string", "description": "Short title for the task (1-200 chars)."},
"description": {"type": "string", "description": "Optional longer description."},
"priority": {"type": "string", "enum": ["high", "medium", "low"], "description": "Task priority. Defaults to medium."},
"tags": {"type": "array", "items": {"type": "string"}, "description": "Optional list of tags."},
"due_date": {"type": "string", "description": "Optional due date (ISO 8601)."},
"recurrence": {"type": "string", "enum": ["none", "daily", "weekly", "monthly"], "description": "Recurrence pattern. Defaults to none."},
},
"required": ["user_id", "title"],
},
),
types.Tool(
name="list_tasks",
description="Retrieve the user's tasks with optional filters.",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "Authenticated user ID."},
"status": {"type": "string", "enum": ["all", "pending", "completed"], "description": "Filter by status."},
"priority": {"type": "string", "enum": ["high", "medium", "low"], "description": "Filter by priority."},
"tag": {"type": "string", "description": "Filter by tag."},
"search": {"type": "string", "description": "Search by keyword in title or description."},
},
"required": ["user_id"],
},
),
types.Tool(
name="complete_task",
description="Mark a task as completed (toggle completed flag).",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "Authenticated user ID."},
"task_id": {"type": "integer", "description": "ID of the task to complete."},
},
"required": ["user_id", "task_id"],
},
),
types.Tool(
name="delete_task",
description="Permanently remove a task from the user's list.",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "Authenticated user ID."},
"task_id": {"type": "integer", "description": "ID of the task to delete."},
},
"required": ["user_id", "task_id"],
},
),
types.Tool(
name="update_task",
description="Modify a task's title and/or description.",
inputSchema={
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "Authenticated user ID."},
"task_id": {"type": "integer", "description": "ID of the task to update."},
"title": {"type": "string", "description": "New title (omit to keep current)."},
"description": {"type": "string", "description": "New description (omit to keep current)."},
},
"required": ["user_id", "task_id"],
},
),
]
# ---------------------------------------------------------------------------
# Handlers
# ---------------------------------------------------------------------------
@server.list_tools()
async def list_tools() -> list[types.Tool]:
"""Return the catalogue of available tools."""
return _TOOL_DEFS
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
"""Dispatch a tool call to the matching todo_service function."""
logger.info("MCP tool %s called: %s", name, arguments)
try:
result = await _dispatch(name, arguments)
except Exception as exc:
logger.error("MCP tool %s failed: %s", name, exc, exc_info=True)
result = {"error": str(exc)}
logger.info("MCP tool %s result: %s", name, result)
return [types.TextContent(type="text", text=json.dumps(result))]
async def _dispatch(name: str, args: dict) -> dict:
"""Route to the correct todo_service call."""
user_id: str = args["user_id"]
if name == "add_task":
async with async_session() as session:
todo = await todo_service.create(
session,
TodoCreate(
title=args["title"],
description=args.get("description") or None,
priority=args.get("priority", "medium"),
tags=args.get("tags", []),
due_date=args.get("due_date") or None,
recurrence=args.get("recurrence", "none"),
),
user_id,
)
return {"task_id": todo.id, "status": "created", "title": todo.title}
if name == "list_tasks":
async with async_session() as session:
todos, _ = await todo_service.list_todos(
session,
user_id,
status=args.get("status", "all"),
priority=args.get("priority"),
tag=args.get("tag"),
search=args.get("search"),
)
return {
"tasks": [
{
"id": t.id,
"title": t.title,
"completed": t.completed,
"priority": t.priority,
"tags": t.tags or [],
"due_date": t.due_date.isoformat() if t.due_date else None,
"recurrence": t.recurrence,
}
for t in todos
]
}
if name == "complete_task":
task_id = int(args["task_id"])
async with async_session() as session:
todo = await todo_service.toggle(session, task_id, user_id)
if todo is None:
return {"error": "Task not found"}
return {"task_id": todo.id, "status": "completed", "title": todo.title}
if name == "delete_task":
task_id = int(args["task_id"])
async with async_session() as session:
todo = await todo_service.get(session, task_id, user_id)
if todo is None:
return {"error": "Task not found"}
title = todo.title
await todo_service.delete(session, task_id, user_id)
return {"task_id": task_id, "status": "deleted", "title": title}
if name == "update_task":
task_id = int(args["task_id"])
async with async_session() as session:
todo = await todo_service.update(
session,
task_id,
TodoUpdate(
title=args.get("title") or None,
description=args.get("description") or None,
),
user_id,
)
if todo is None:
return {"error": "Task not found"}
return {"task_id": todo.id, "status": "updated", "title": todo.title}
return {"error": f"Unknown tool: {name}"}
# ---------------------------------------------------------------------------
# stdio entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import asyncio
from mcp.server.stdio import stdio_server
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options(),
)
asyncio.run(main())
|