Skip to content

team-markmesh/mark_mesh_skill

markmesh

Verified

Manage a trademark portfolio through MarkMesh's MCP server — list trademarks, filings and deadlines, run cross-office searches and conflict research for clearance, import or refresh filings from national offices, and register watches that report what changed. Every record carries provenance (source office, fetch time, citable office URL). Use when a user asks about their trademarks, filings, renewal deadlines or clients, wants to search/import a mark from an office (USPTO, EUIPO, DPMA, etc.), wants to check whether a proposed name conflicts with existing marks, or wants to monitor a filing for changes.

FileKindSize
SKILL.mdskill md9.6 KB
examples/watch_bot.pyscript7.2 KB

examples/watch_bot.py

View on GitHub
#!/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()
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 470kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall