""" KanBot MCP server — THE whole API surface. Agents, the CLI, the web view, and the Telegram bot are all just clients of these 9 tools. There is no other way to touch the board. All state transitions flow through move_card(), which: 1. validates the (from -> to) against the frozen TRANSITIONS table, 2. enforces the guard token that transition requires, 3. records the transition idempotently in board_events, 4. lets the DB NOTIFY trigger publish the event for the Conductor. Run as a stdio MCP server: python -m core.mcp_server """ from __future__ import annotations import json from datetime import datetime, timezone from mcp.server.fastmcp import FastMCP from . import db from .contract import ( DRY_RUN_DEFAULT, LEASE_SECONDS_DEFAULT, Card, Column, GuardFailed, IllegalTransition, Role, ThreadEntry, check_guard, lookup_transition, ) mcp = FastMCP("kanbot") def _now() -> str: return datetime.now(timezone.utc).isoformat() # --------------------------------------------------------------------------- # # Guard enforcement — the heart of the state machine's integrity. # --------------------------------------------------------------------------- # async def _check_guard(card: Card, to: Column, *, requires: str | None, reason: str | None, actor: str, worker: str | None, critic_verdict: str | None) -> None: del actor # the ledger records the actor; the guard does not branch on it check_guard(card, to, requires, reason=reason, worker=worker, critic_verdict=critic_verdict) async def _log_transition(card: Card, to: Column, actor: str, reason: str | None) -> bool: """Idempotent. Returns True if this transition was newly applied.""" # Compute attempt increment BEFORE the insert so the idempotency key # includes the new attempt value, avoiding collisions on re-approvals. new_attempt = card.attempt + 1 if to == Column.READY and card.column in (Column.REVIEW, Column.BLOCKED) else card.attempt async with (await db.pool()).acquire() as c: async with c.transaction(): inserted = await c.fetchval( """INSERT INTO board_events (card_id,from_col,to_col,attempt,actor,reason) VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (card_id,from_col,to_col,attempt) DO NOTHING RETURNING id""", card.id, card.column.value, to.value, new_attempt, actor, reason, ) if inserted is None: return False # replay -> no-op await c.execute( 'UPDATE cards SET "column"=$2, attempt=$3 WHERE id=$1', card.id, to.value, new_attempt, ) return True # --------------------------------------------------------------------------- # # The 9 tools # --------------------------------------------------------------------------- # @mcp.tool() async def list_column(column: str) -> str: """List all cards in a column. column ∈ backlog|ready|in-flight|review|blocked|done.""" cards = await db.list_column(Column(column)) return json.dumps([{"id": c.id, "title": c.title, "role": c.agent_role.value, "worker": c.assigned_worker, "attempt": c.attempt} for c in cards]) @mcp.tool() async def get_card(card_id: str) -> str: """Full card detail including the inter-agent thread.""" card = await db.get_card(card_id) if not card: return json.dumps({"error": f"{card_id} not found"}) return json.dumps({ "id": card.id, "title": card.title, "column": card.column.value, "role": card.agent_role.value, "spec": card.spec, "acceptance_criteria": card.acceptance_criteria, "worker": card.assigned_worker, "parent": card.parent, "children": card.children, "attempt": card.attempt, "tags": card.tags, "requires_human": card.requires_human, "lease_expires_at": card.lease_expires_at, "thread": [e.__dict__ for e in card.thread], }) @mcp.tool() async def create_card(title: str, spec: str = "", role: str = "executor", acceptance_criteria: list[str] | None = None, tags: list[str] | None = None, parent: str = "") -> str: """Create a new card. Lands in BACKLOG. Fires an INSERT NOTIFY event.""" cid = await db.next_card_id() card = Card(id=cid, title=title, spec=spec, agent_role=Role(role), acceptance_criteria=acceptance_criteria or [], tags=tags or [], parent=parent or None) await db.insert_card(card) if parent: await db.add_child(parent, cid) return json.dumps({"id": cid, "column": "backlog"}) @mcp.tool() async def claim_card(card_id: str, worker: str, lease_seconds: int = LEASE_SECONDS_DEFAULT) -> str: """Atomically claim a READY card: set a lease and move it to IN-FLIGHT. Loses the race gracefully if another worker already claimed it.""" card = await db.get_card(card_id) if not card: return json.dumps({"error": "not found"}) if card.column != Column.READY: return json.dumps({"error": f"cannot claim; card is {card.column.value}"}) await db.set_lease(card_id, worker, lease_seconds) return await move_card(card_id, "in-flight", actor=worker, worker=worker, reason="claimed") @mcp.tool() async def move_card(card_id: str, to_column: str, actor: str = "human:remy", reason: str = "", worker: str = "", critic_verdict: str = "") -> str: """The one true state transition. Validates against TRANSITIONS, enforces the guard, records idempotently, and lets the DB NOTIFY the Conductor. critic_verdict ∈ ""|pass|fail (used only for review-> moves).""" card = await db.get_card(card_id) if not card: return json.dumps({"error": "not found"}) to = Column(to_column) try: t = lookup_transition(card.column, to) await _check_guard(card, to, requires=t.requires, reason=reason or None, actor=actor, worker=worker or None, critic_verdict=critic_verdict or None) except (IllegalTransition, GuardFailed) as e: return json.dumps({"error": str(e), "rejected": True}) applied = await _log_transition(card, to, actor, reason or None) if to != Column.IN_FLIGHT: await db.clear_lease(card_id) if applied and reason: await db.append_thread(card_id, ThreadEntry( role="system", author=actor, ts=_now(), content=f"{card.column.value} → {to.value}: {reason}", kind="comment")) return json.dumps({"id": card_id, "from": card.column.value, "to": to.value, "applied": applied, "idempotent_noop": not applied}) @mcp.tool() async def comment(card_id: str, text: str, author: str = "human:remy", kind: str = "comment") -> str: """Append to the card thread — the inter-agent comms bus. kind ∈ comment|artifact|tool_call|tool_result|eval. In DRY-RUN, executors post tool_call proposals here for human approval.""" await db.append_thread(card_id, ThreadEntry( role="system", author=author, ts=_now(), content=text, kind=kind)) return json.dumps({"ok": True, "card_id": card_id, "kind": kind}) @mcp.tool() async def spawn_subtask(parent: str, title: str, spec: str = "", role: str = "executor", acceptance_criteria: list[str] | None = None, tags: list[str] | None = None) -> str: """Planner tool: create a child card under a parent (lands in BACKLOG).""" return await create_card(title=title, spec=spec, role=role, acceptance_criteria=acceptance_criteria, tags=tags, parent=parent) @mcp.tool() async def block_card(card_id: str, reason: str, actor: str = "system") -> str: """Park a card in BLOCKED with a mandatory reason (guard enforced).""" card = await db.get_card(card_id) if not card: return json.dumps({"error": "not found"}) return await move_card(card_id, "blocked", actor=actor, reason=reason) @mcp.tool() async def request_human(card_id: str, question: str, actor: str = "system") -> str: """Flag a card for human decision. Sets requires_human and posts the question; the Conductor relays these to Telegram. Does NOT move the card by itself.""" async with (await db.pool()).acquire() as c: await c.execute("UPDATE cards SET requires_human=TRUE WHERE id=$1", card_id) await db.append_thread(card_id, ThreadEntry( role="system", author=actor, ts=_now(), content=f"HUMAN NEEDED: {question}", kind="comment")) return json.dumps({"ok": True, "card_id": card_id, "relay": "telegram"}) if __name__ == "__main__": mcp.run()