#!/usr/bin/env python3
"""
A MarkMesh watch bot in one file. Standard library only.
Polls the marks you're watching and reports what actually changed, with a
link to each office's own record. Run it on a cron and it becomes a
monitoring service.
export MARKMESH_API_KEY=mm_test_...
python3 watch_bot.py --list # what am I watching?
python3 watch_bot.py --watch <filing_id> # start watching one
python3 watch_bot.py # report what changed
Why a watch bot and not a search bot: search is the one thing every
trademark wrapper already does. Monitoring needs a corpus to diff against,
which is the part that's hard to build and the reason this is the example
worth forking.
The bot is deliberately dumb about judgement. It reports changes and cites
sources. It never decides whether a change matters to you, and it never
says a name is clear.
"""
import argparse
import json
import os
import sys
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
BASE_URL = os.environ.get("MARKMESH_BASE_URL", "https://markmesh.com")
MCP_URL = f"{BASE_URL}/api/v1/mcp"
# Where the last-seen timestamp lives. Passing this back as `since` is the
# whole protocol: the server returns only what changed after it, so the bot
# stays cheap no matter how long it's been running.
STATE_FILE = Path(os.environ.get("MARKMESH_STATE", "~/.markmesh_watch_state.json")).expanduser()
class MarkMeshError(RuntimeError):
pass
def call_tool(name, arguments, api_key):
"""One JSON-RPC call to the MCP endpoint."""
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": name, "arguments": arguments},
}
request = urllib.request.Request(
MCP_URL,
data=json.dumps(payload).encode(),
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}",
},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
body = json.loads(response.read())
except urllib.error.HTTPError as exc:
if exc.code == 401:
raise MarkMeshError("401: check MARKMESH_API_KEY") from exc
if exc.code == 429:
raise MarkMeshError("429: rate limited, back off and retry") from exc
raise MarkMeshError(f"HTTP {exc.code}: {exc.read()[:300]!r}") from exc
if "error" in body:
raise MarkMeshError(f"{name} failed: {body['error']}")
return unwrap(body.get("result", {}))
def unwrap(result):
"""MCP returns tool output as content blocks; pull the JSON back out."""
for block in result.get("content", []):
if block.get("type") == "text":
try:
return json.loads(block["text"])
except json.JSONDecodeError:
return block["text"]
return result
def load_since():
if STATE_FILE.exists():
try:
return json.loads(STATE_FILE.read_text())["since"]
except (json.JSONDecodeError, KeyError):
pass
# First run: look back a week rather than reporting the entire history.
return (datetime.now(timezone.utc) - timedelta(days=7)).isoformat()
def save_since(timestamp):
STATE_FILE.write_text(json.dumps({"since": timestamp}, indent=2))
def citation_line(provenance):
"""
Print a link ONLY when it points at this specific record.
`office_portal` means that office publishes no per-record page, so the
URL is just its search form. Printing it next to a mark would look like
a citation and cite nothing.
"""
citation = (provenance or {}).get("citation") or {}
kind = citation.get("kind")
if kind == "office_record":
return f" {citation['url']}"
if kind == "office_portal":
return " (this office publishes no per-record page; look it up in its search)"
return " (no public office URL held for this register)"
def cmd_list(api_key):
result = call_tool("list_watches", {}, api_key)
watches = result if isinstance(result, list) else result.get("results", result)
if not watches:
print("No active watches. Start one with --watch <filing_id>.")
return
print(f"{len(watches)} active watch(es):\n")
for watch in watches:
filing = watch.get("filing") or {}
provenance = filing.get("provenance") or {}
print(f" {filing.get('mark_text') or '(untitled)'} [{provenance.get('office', '?')}]")
print(f" filing_id: {watch.get('filing_id')}")
print(citation_line(provenance))
print()
def cmd_watch(filing_id, api_key):
call_tool(
"create_watch",
{"input": {"filing_id": filing_id, "recipient_mode": "all_members"}},
api_key,
)
print(f"Watching {filing_id}. Run without arguments to poll for changes.")
def cmd_poll(api_key):
since = load_since()
# Stamp BEFORE the call: anything recorded while the request is in
# flight belongs to the next window, not this one. Stamping after would
# silently skip it.
next_since = datetime.now(timezone.utc).isoformat()
print(f"Changes since {since}\n")
# `since` is an ACTION ARGUMENT, so it goes inside `input` — passing it
# flat returns "since: is required", which reads as though you omitted
# it. See the argument-shape table in reference/tools.md.
result = call_tool("watch_changes_since", {"input": {"since": since}}, api_key)
watches = result if isinstance(result, list) else result.get("results", result)
if not watches:
# An empty result means nothing changed. It does not mean the watch
# is broken, and the bot should not imply that it might be.
print("Nothing changed.")
save_since(next_since)
return
for watch in watches:
filing = watch.get("filing") or {}
provenance = filing.get("provenance") or {}
events = filing.get("events") or []
print(f"{filing.get('mark_text') or '(untitled)'} [{provenance.get('office', '?')}]")
for event in events:
occurred = (event.get("occurred_at") or "")[:10]
print(f" {occurred} {event.get('event_type')} {event.get('description') or ''}".rstrip())
print(citation_line(provenance))
fetched = provenance.get("fetched_at")
if fetched:
served = provenance.get("served_from", "?")
print(f" (served_from: {served}, fetched {fetched[:10]})")
print()
save_since(next_since)
def main():
parser = argparse.ArgumentParser(description="MarkMesh watch bot")
parser.add_argument("--list", action="store_true", help="list active watches")
parser.add_argument("--watch", metavar="FILING_ID", help="start watching a filing")
args = parser.parse_args()
api_key = os.environ.get("MARKMESH_API_KEY")
if not api_key:
sys.exit("Set MARKMESH_API_KEY (mm_test_... or mm_live_...)")
try:
if args.list:
cmd_list(api_key)
elif args.watch:
cmd_watch(args.watch, api_key)
else:
cmd_poll(api_key)
except MarkMeshError as exc:
sys.exit(f"error: {exc}")
if __name__ == "__main__":
main()