tasklert-api / src /mcp /server.py
hashir-qt's picture
initial deploy
507973e
Raw History Blame Contribute Delete
8.43 kB
"""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())