120 lines
5.4 KiB
Python
120 lines
5.4 KiB
Python
"""The MCP protocol over the ``ai-agent`` tools (``mcp_tools.py``): a
|
|
JSON-RPC 2.0 dispatcher, transport-free. The backend's ``/mcp`` route
|
|
(mcpserver/) feeds it from Streamable HTTP.
|
|
|
|
Stateless on purpose: ``initialize`` negotiates a protocol version and every
|
|
other request stands alone (no ``Mcp-Session-Id``), so a hub restart or a
|
|
blue-green deploy never strands a connected app. Tools only — no resources,
|
|
prompts or sampling. Stdlib only, like the CLI.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
import traceback
|
|
|
|
import mcp_tools
|
|
from ai_agent import HubError
|
|
|
|
SERVER_NAME = "ai-agent"
|
|
SERVER_TITLE = "ai-agent hub"
|
|
SERVER_VERSION = "1.0.0"
|
|
# Newest first: an unknown version from the client gets our newest.
|
|
PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
INSTRUCTIONS = """\
|
|
ai-agent is Gabriel's self-hosted hub of coding-agent conversations (Claude Code,
|
|
pi, opencode) running on his homelab and paired machines. Use it to hand work to
|
|
a real agent that can read and change his code, run commands and deploy:
|
|
start_conversation with the task, then wait_for_conversation for its answer
|
|
(each wait returns within ~50 s; call again while it runs). get_conversation /
|
|
search_conversations / list_conversations / past_conversations read what was done
|
|
before. When the user says "conv", "check past conv(s)", "the previous
|
|
conversation" or gives an id like 01a1e40a-… (or a viewer link), they mean one of
|
|
these: look it up here, not in this machine's ~/.claude/projects, which holds its
|
|
own sessions only and names no file after a conversation id. browse looks up
|
|
projects, agents, models, workers and plan usage; live plugins add their own
|
|
plugin_* tools (services, plans, memories, cron jobs: plugin_cron-jobs_*, and
|
|
Send later: plugin_scheduled-conversations_add starts a conversation — or a
|
|
turn in one — at a set time). Every conversation has a link to the ai-agent
|
|
app — give it to the user."""
|
|
|
|
# JSON-RPC error codes.
|
|
PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL = (
|
|
-32700, -32600, -32601, -32602, -32603)
|
|
|
|
|
|
def _error(mid, code: int, message: str) -> dict:
|
|
return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}
|
|
|
|
|
|
def _result(mid, result: dict) -> dict:
|
|
return {"jsonrpc": "2.0", "id": mid, "result": result}
|
|
|
|
|
|
def negotiate(requested: str | None) -> str:
|
|
return requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
|
|
|
|
|
|
def handle(msg, ctx: mcp_tools.Ctx, log=None) -> dict | None:
|
|
"""One JSON-RPC message → its response (``None`` for a notification or a
|
|
client's response). ``log(event, **fields)`` hears every tool call."""
|
|
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
|
|
return _error(None, INVALID_REQUEST, "not a JSON-RPC 2.0 message")
|
|
method, mid = msg.get("method"), msg.get("id")
|
|
if method is None: # a response to something we never ask
|
|
return None
|
|
is_note = "id" not in msg
|
|
params = msg.get("params") or {}
|
|
if not isinstance(params, dict):
|
|
return None if is_note else _error(mid, INVALID_PARAMS, "params must be an object")
|
|
if is_note: # notifications/initialized, cancelled, …
|
|
return None
|
|
if method == "initialize":
|
|
return _result(mid, {
|
|
"protocolVersion": negotiate(params.get("protocolVersion")),
|
|
"capabilities": {"tools": {"listChanged": False}},
|
|
"serverInfo": {"name": SERVER_NAME, "title": SERVER_TITLE,
|
|
"version": SERVER_VERSION},
|
|
"instructions": INSTRUCTIONS,
|
|
})
|
|
if method == "ping":
|
|
return _result(mid, {})
|
|
if method == "tools/list":
|
|
return _result(mid, {"tools": mcp_tools.listing(ctx)})
|
|
if method == "tools/call":
|
|
name = params.get("name")
|
|
args = params.get("arguments") or {}
|
|
if not isinstance(name, str) or not isinstance(args, dict):
|
|
return _error(mid, INVALID_PARAMS, "tools/call takes a name and an arguments object")
|
|
try:
|
|
text = mcp_tools.call(ctx, name, args)
|
|
ok = True
|
|
except KeyError:
|
|
return _error(mid, INVALID_PARAMS, f"unknown tool: {name}")
|
|
except mcp_tools.ToolError as e:
|
|
text, ok = str(e), False
|
|
except HubError as e:
|
|
text, ok = f"hub: {e.detail}" + (f" (HTTP {e.code})" if e.code else ""), False
|
|
except TypeError as e: # a wrong-typed argument reached the function
|
|
text, ok = f"bad arguments: {e}", False
|
|
except Exception as e: # noqa: BLE001 — the model reads it; we log it
|
|
traceback.print_exc(file=sys.stderr)
|
|
text, ok = f"internal error: {type(e).__name__}: {e}", False
|
|
if log:
|
|
log("tool", name=name, ok=ok)
|
|
return _result(mid, {"content": [{"type": "text", "text": text}], "isError": not ok})
|
|
if method in ("resources/list", "prompts/list"):
|
|
return _result(mid, {method.split("/")[0]: []})
|
|
return _error(mid, METHOD_NOT_FOUND, f"method not found: {method}")
|
|
|
|
|
|
def handle_body(body, ctx: mcp_tools.Ctx, log=None):
|
|
"""A POSTed body: one message or (2025-03-26) a batch. ``None`` when
|
|
nothing needs an answer (notifications only)."""
|
|
if isinstance(body, list):
|
|
if not body:
|
|
return _error(None, INVALID_REQUEST, "empty batch")
|
|
out = [r for r in (handle(m, ctx, log) for m in body) if r is not None]
|
|
return out or None
|
|
return handle(body, ctx, log)
|