mocop 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mocop-0.1.0/.gitignore ADDED
@@ -0,0 +1,33 @@
1
+ # Generated by Cargo
2
+ # will have compiled files and executables
3
+ debug
4
+ target
5
+
6
+ # These are backup files generated by rustfmt
7
+ **/*.rs.bk
8
+
9
+ # MSVC Windows builds of rustc generate these, which store debugging information
10
+ *.pdb
11
+
12
+ # Generated by cargo mutants
13
+ # Contains mutation testing data
14
+ **/mutants.out*/
15
+
16
+ # rustc will dump stack traces when hitting an internal compiler error to PWD
17
+ rustc-ice-*.txt
18
+
19
+ # RustRover
20
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
21
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
22
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
23
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
24
+ #.idea/
25
+
26
+ node_modules
27
+ dist
28
+ build
29
+ .wrangler
30
+ .dev.vars
31
+
32
+ .build
33
+ dist
mocop-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.5
2
+ Name: mocop
3
+ Version: 0.1.0
4
+ Summary: Command line for mocop: search APIs, MCP servers and agents, score a website's agent-readiness, manage your domains.
5
+ Project-URL: Homepage, https://mocop.ai/docs#cli
6
+ Project-URL: Documentation, https://mocop.ai/docs
7
+ Author: Mayberry Tech
8
+ License: MIT
9
+ Keywords: a2a,agents,api,cli,llms.txt,mcp,openapi,search
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+
13
+ # mocop
14
+
15
+ Command line for [mocop](https://mocop.ai): search APIs, MCP servers and agents, score a website's agent-readiness, and manage your domains. Pure Python standard library, no dependencies.
16
+
17
+ ```
18
+ pipx install mocop # or: uvx mocop search "send sms"
19
+ mocop --help
20
+ mocop search "send sms" --type api --limit 5
21
+ mocop analyze example.com
22
+ mocop auth login # OAuth in the browser; --device for headless machines
23
+ ```
24
+
25
+ Add `--json` for machine-readable output. Set `MOCOP_TOKEN` to use a bearer token in CI. Docs: https://mocop.ai/docs#cli
mocop-0.1.0/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # mocop
2
+
3
+ Command line for [mocop](https://mocop.ai): search APIs, MCP servers and agents, score a website's agent-readiness, and manage your domains. Pure Python standard library, no dependencies.
4
+
5
+ ```
6
+ pipx install mocop # or: uvx mocop search "send sms"
7
+ mocop --help
8
+ mocop search "send sms" --type api --limit 5
9
+ mocop analyze example.com
10
+ mocop auth login # OAuth in the browser; --device for headless machines
11
+ ```
12
+
13
+ Add `--json` for machine-readable output. Set `MOCOP_TOKEN` to use a bearer token in CI. Docs: https://mocop.ai/docs#cli
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mocop"
7
+ version = "0.1.0"
8
+ description = "Command line for mocop: search APIs, MCP servers and agents, score a website's agent-readiness, manage your domains."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ keywords = ["mcp", "agents", "api", "search", "cli", "llms.txt", "openapi", "a2a"]
13
+ authors = [{ name = "Mayberry Tech" }]
14
+ dependencies = []
15
+
16
+ [project.urls]
17
+ Homepage = "https://mocop.ai/docs#cli"
18
+ Documentation = "https://mocop.ai/docs"
19
+
20
+ [project.scripts]
21
+ mocop = "mocop.cli:main"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/mocop"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,485 @@
1
+ """mocop CLI: search the agentic web, score sites, manage your domains. Standard library only."""
2
+ import base64, hashlib, http.server, json, os, secrets, socketserver, sys, threading, time, urllib.error, urllib.parse, urllib.request, webbrowser
3
+ from . import __version__ as VERSION
4
+
5
+ BASE = os.environ.get("MOCOP_URL", "https://mocop.ai").rstrip("/")
6
+ CRED = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.path.expanduser("~"), ".config"), "mocop", "credentials.json")
7
+ SCOPES = "openid profile email offline_access mocop:read mocop:domains"
8
+ RESOURCE = "https://mocop.ai/api/v1"
9
+ VALUE_FLAGS = {"type", "limit", "offset", "q", "has", "sort", "group", "kind", "method", "version"}
10
+
11
+ HELP = f"""mocop {VERSION}: search the agentic web from your terminal
12
+
13
+ Usage: mocop <command> [options] (add --json for machine-readable output)
14
+
15
+ Search & browse
16
+ search <query> [--type api|mcp|agent|website|capability] [--limit N]
17
+ browse [--q text] [--has api|mcp|agent] [--sort popular|capabilities|signals|name] [--limit N]
18
+ org <slug> [kind [item]] an organization, or its apis/mcp/agents
19
+ entity <slug> one API, MCP server or agent
20
+ capabilities <slug> [--q text] [--group g] [--method M] [--removed] [--limit N]
21
+ versions <slug> [version]
22
+ site <domain> everything indexed for a domain
23
+ guide how to make a website agent-ready (markdown)
24
+
25
+ Score a website
26
+ analyze <domain> [--refresh] agent-readiness score out of 10 with fixes
27
+
28
+ Your account (needs: mocop auth login)
29
+ whoami
30
+ domains [list|add <d>|verify <d>|dns <d>|remove <d>]
31
+ favorites [list|add <d>|rm <d>]
32
+ collections [list|create <name>|rm <id>|add <id> <d>|remove <id> <d>]
33
+ activity
34
+
35
+ Auth & agents
36
+ auth login [--device] [--no-browser] sign in (browser OAuth, or device code for headless)
37
+ auth status | auth logout | auth token
38
+ mcp stdio MCP server bridging to {BASE}/mcp (for MCP clients)
39
+
40
+ Environment: MOCOP_URL (default https://mocop.ai), MOCOP_TOKEN (bearer token), MOCOP_OUTPUT=json
41
+ Docs: https://mocop.ai/docs Guide: https://mocop.ai/guide"""
42
+
43
+
44
+ def die(msg, code=1):
45
+ print(f"mocop: {msg}", file=sys.stderr)
46
+ sys.exit(code)
47
+
48
+
49
+ def parse(argv):
50
+ flags, pos, i = {}, [], 0
51
+ while i < len(argv):
52
+ a = argv[i]
53
+ if a.startswith("--"):
54
+ k, _, v = a[2:].partition("=")
55
+ if v:
56
+ flags[k] = v
57
+ elif k in VALUE_FLAGS and i + 1 < len(argv) and not argv[i + 1].startswith("-"):
58
+ i += 1
59
+ flags[k] = argv[i]
60
+ else:
61
+ flags[k] = True
62
+ elif a == "-h":
63
+ flags["help"] = True
64
+ elif a == "-v":
65
+ flags["version"] = True
66
+ elif a == "-j":
67
+ flags["json"] = True
68
+ else:
69
+ pos.append(a)
70
+ i += 1
71
+ return flags, pos
72
+
73
+
74
+ FLAGS, POS = parse(sys.argv[1:])
75
+ JSON_OUT = bool(FLAGS.get("json")) or os.environ.get("MOCOP_OUTPUT") == "json"
76
+
77
+
78
+ def out(v):
79
+ print(v if isinstance(v, str) else json.dumps(v, indent=2, ensure_ascii=False))
80
+
81
+
82
+ # ---------- credentials + http ----------
83
+ def load_creds():
84
+ try:
85
+ with open(CRED) as f:
86
+ return json.load(f)
87
+ except Exception:
88
+ return None
89
+
90
+
91
+ def save_creds(c):
92
+ os.makedirs(os.path.dirname(CRED), exist_ok=True)
93
+ fd = os.open(CRED, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
94
+ with os.fdopen(fd, "w") as f:
95
+ json.dump(c, f, indent=2)
96
+ os.chmod(CRED, 0o600)
97
+
98
+
99
+ def post_form(path, data):
100
+ req = urllib.request.Request(BASE + path, data=urllib.parse.urlencode(data).encode(), method="POST", headers={"content-type": "application/x-www-form-urlencoded"})
101
+ return urllib.request.urlopen(req, timeout=30)
102
+
103
+
104
+ def refresh(c):
105
+ if not c or not c.get("refresh_token") or not c.get("client_id"):
106
+ return None
107
+ try:
108
+ t = json.load(post_form("/api/auth/oauth2/token", {"grant_type": "refresh_token", "refresh_token": c["refresh_token"], "client_id": c["client_id"], "resource": RESOURCE}))
109
+ except Exception:
110
+ return None
111
+ n = {**c, "access_token": t["access_token"], "refresh_token": t.get("refresh_token") or c["refresh_token"], "expires_at": time.time() * 1000 + t.get("expires_in", 3600) * 1000 - 30000}
112
+ save_creds(n)
113
+ return n
114
+
115
+
116
+ def token():
117
+ if os.environ.get("MOCOP_TOKEN"):
118
+ return os.environ["MOCOP_TOKEN"]
119
+ c = load_creds()
120
+ if not c:
121
+ return None
122
+ if c.get("expires_at") and time.time() * 1000 > c["expires_at"]:
123
+ c = refresh(c) or c
124
+ return c.get("access_token")
125
+
126
+
127
+ def api(path, method="GET", body=None, auth=False):
128
+ headers = {"accept": "application/json", "user-agent": f"mocop-cli-py/{VERSION}"}
129
+ data = None
130
+ if body is not None:
131
+ headers["content-type"] = "application/json"
132
+ data = json.dumps(body).encode()
133
+ t = token()
134
+ if t:
135
+ headers["authorization"] = f"Bearer {t}"
136
+ elif auth:
137
+ die("not signed in. Run: mocop auth login", 2)
138
+ try:
139
+ r = urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, method=method, headers=headers), timeout=60)
140
+ text = r.read().decode()
141
+ except urllib.error.HTTPError as e:
142
+ text = e.read().decode()
143
+ if e.code == 401:
144
+ die("session expired. Run: mocop auth login" if t else "this needs sign-in. Run: mocop auth login", 2)
145
+ try:
146
+ j = json.loads(text)
147
+ msg = j.get("detail") or j.get("title") or j.get("error") or text[:200]
148
+ except Exception:
149
+ msg = text[:200]
150
+ die(f"{e.code} {msg}")
151
+ except urllib.error.URLError as e:
152
+ die(f"cannot reach {BASE}: {e.reason}")
153
+ try:
154
+ return json.loads(text)
155
+ except Exception:
156
+ return text
157
+
158
+
159
+ def qs(**kw):
160
+ p = {k: v for k, v in kw.items() if v not in (None, "", True, False)}
161
+ return ("?" + urllib.parse.urlencode(p)) if p else ""
162
+
163
+
164
+ def enc(s):
165
+ return urllib.parse.quote(str(s), safe="")
166
+
167
+
168
+ # ---------- output helpers ----------
169
+ def clip(s, n=110):
170
+ s = " ".join(str(s or "").split())
171
+ return s if len(s) <= n else s[: n - 1] + "…"
172
+
173
+
174
+ def ago(t):
175
+ if not t:
176
+ return "never"
177
+ s = round(time.time() - t / 1000)
178
+ return "just now" if s < 120 else f"{round(s / 60)}m ago" if s < 3600 else f"{round(s / 3600)}h ago" if s < 86400 else f"{round(s / 86400)}d ago"
179
+
180
+
181
+ def bar(n):
182
+ k = round(n)
183
+ return "█" * k + "░" * (10 - k)
184
+
185
+
186
+ def printed(v, human):
187
+ out(v) if JSON_OUT else human(v)
188
+
189
+
190
+ def print_results(r):
191
+ rows = r.get("results") or []
192
+ if r.get("organizations"):
193
+ out("Organizations")
194
+ for o in r["organizations"]:
195
+ out(f" {o['name']:<34} {o['slug']}")
196
+ out("")
197
+ if not rows:
198
+ return out("No results.")
199
+ for e in rows:
200
+ out(f"{e['type']:<10} {clip(e['name'], 40):<40} {(e.get('domain') or ''):<28} {(e.get('verification') or ''):<17} {e.get('path') or '/e/' + e['slug']}")
201
+ out(f"\n{r.get('total', len(rows))} total. Open: {BASE}<path>")
202
+
203
+
204
+ def analyze(domain):
205
+ r = api("/api/v1/analyze" + qs(domain=domain, refresh="1" if FLAGS.get("refresh") else "", source="cli"))
206
+ if JSON_OUT:
207
+ return out(r)
208
+ out(f"{r['domain']}: {r['score']}/10 ({r['grade']}) {r.get('verdict', {}).get('label', '')}")
209
+ c = r["counts"]
210
+ out(f"{c['passed']} passed, {c['partial']} partial, {c['missing']} missing\n")
211
+ for i in r["items"]:
212
+ out(f"{i['title']:<36} {bar(i['score'])} {i['score']:>4}/10 {i['status']}")
213
+ if r.get("recommendations"):
214
+ out("\nFix next:")
215
+ for x in r["recommendations"]:
216
+ out(f" +{x['pts']} {x['title']}: {x['text']} ({BASE}/guide#step-{x['step']})")
217
+ out(f"\nFull report: {BASE}/analyze/{r['domain']}")
218
+
219
+
220
+ # ---------- auth ----------
221
+ def b64u(b):
222
+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
223
+
224
+
225
+ def login_browser():
226
+ result = {}
227
+
228
+ class H(http.server.BaseHTTPRequestHandler):
229
+ def log_message(self, *a):
230
+ pass
231
+
232
+ def do_GET(self):
233
+ u = urllib.parse.urlparse(self.path)
234
+ if u.path != "/callback":
235
+ self.send_response(404); self.end_headers(); return
236
+ q = urllib.parse.parse_qs(u.query)
237
+ self.send_response(200); self.send_header("content-type", "text/html"); self.end_headers()
238
+ if q.get("state", [""])[0] != result["state"] or not q.get("code"):
239
+ result["error"] = (q.get("error_description") or q.get("error") or ["sign-in failed"])[0]
240
+ self.wfile.write(b"<h3>Sign-in failed. You can close this tab.</h3>")
241
+ else:
242
+ result["code"] = q["code"][0]
243
+ self.wfile.write(b"<h3>Signed in to mocop. You can close this tab and return to your terminal.</h3>")
244
+
245
+ srv = socketserver.TCPServer(("127.0.0.1", 0), H)
246
+ port = srv.server_address[1]
247
+ redirect = f"http://127.0.0.1:{port}/callback"
248
+ reg = urllib.request.Request(BASE + "/api/auth/oauth2/register", method="POST", headers={"content-type": "application/json"}, data=json.dumps({"client_name": "mocop CLI (python)", "application_type": "native", "redirect_uris": [redirect], "token_endpoint_auth_method": "none", "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "scope": SCOPES}).encode())
249
+ try:
250
+ client_id = json.load(urllib.request.urlopen(reg, timeout=30))["client_id"]
251
+ except Exception as e:
252
+ srv.server_close(); die(f"could not register the CLI with {BASE} ({e}). Try: mocop auth login --device")
253
+ verifier = b64u(secrets.token_bytes(32))
254
+ result["state"] = b64u(secrets.token_bytes(16))
255
+ url = BASE + "/api/auth/oauth2/authorize" + qs(response_type="code", client_id=client_id, redirect_uri=redirect, scope=SCOPES, state=result["state"], code_challenge=b64u(hashlib.sha256(verifier.encode()).digest()), code_challenge_method="S256", resource=RESOURCE)
256
+ print(f"Opening your browser to sign in…\nIf it does not open, visit:\n{url}\n", file=sys.stderr)
257
+ if not FLAGS.get("no-browser"):
258
+ webbrowser.open(url)
259
+ srv.timeout = 1
260
+ end = time.time() + 300
261
+ while time.time() < end and "code" not in result and "error" not in result:
262
+ srv.handle_request()
263
+ srv.server_close()
264
+ if "error" in result:
265
+ die(result["error"])
266
+ if "code" not in result:
267
+ die("timed out waiting for sign-in")
268
+ try:
269
+ t = json.load(post_form("/api/auth/oauth2/token", {"grant_type": "authorization_code", "code": result["code"], "redirect_uri": redirect, "client_id": client_id, "code_verifier": verifier, "resource": RESOURCE}))
270
+ except urllib.error.HTTPError as e:
271
+ die(f"token exchange failed ({e.code}): {e.read().decode()[:200]}")
272
+ save_creds({"base": BASE, "client_id": client_id, "access_token": t["access_token"], "refresh_token": t.get("refresh_token"), "expires_at": time.time() * 1000 + t.get("expires_in", 3600) * 1000 - 30000})
273
+
274
+
275
+ def login_device():
276
+ client_id = "mocop-cli"
277
+
278
+ def pj(path, body):
279
+ req = urllib.request.Request(BASE + path, method="POST", headers={"content-type": "application/json"}, data=json.dumps(body).encode())
280
+ try:
281
+ r = urllib.request.urlopen(req, timeout=30)
282
+ return r.status, json.load(r)
283
+ except urllib.error.HTTPError as e:
284
+ try:
285
+ return e.code, json.loads(e.read().decode())
286
+ except Exception:
287
+ return e.code, {}
288
+
289
+ st, d = pj("/api/auth/device/code", {"client_id": client_id, "scope": "openid profile email"})
290
+ if st != 200:
291
+ die(f"device sign-in is not available ({st})")
292
+ print(f"To sign in, open {d.get('verification_uri_complete') or d['verification_uri']}\nand confirm the code: {d['user_code']}\n", file=sys.stderr)
293
+ if not FLAGS.get("no-browser") and d.get("verification_uri_complete"):
294
+ webbrowser.open(d["verification_uri_complete"])
295
+ wait, end = d.get("interval", 5), time.time() + d.get("expires_in", 600)
296
+ while time.time() < end:
297
+ time.sleep(wait)
298
+ st, j = pj("/api/auth/device/token", {"grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": d["device_code"], "client_id": client_id})
299
+ if st == 200 and j.get("access_token"):
300
+ save_creds({"base": BASE, "access_token": j["access_token"], "device": True})
301
+ return
302
+ if j.get("error") == "slow_down":
303
+ wait += 5
304
+ elif j.get("error") and j["error"] != "authorization_pending":
305
+ die(f"sign-in {j.get('error_description') or j['error']}")
306
+ die("sign-in timed out")
307
+
308
+
309
+ def mcp_bridge():
310
+ session = None
311
+ for line in sys.stdin:
312
+ if not line.strip():
313
+ continue
314
+ try:
315
+ msg = json.loads(line)
316
+ except Exception:
317
+ continue
318
+ headers = {"content-type": "application/json", "accept": "application/json, text/event-stream", "user-agent": f"mocop-cli-py/{VERSION}"}
319
+ t = token()
320
+ if t:
321
+ headers["authorization"] = f"Bearer {t}"
322
+ if session:
323
+ headers["mcp-session-id"] = session
324
+ try:
325
+ r = urllib.request.urlopen(urllib.request.Request(BASE + "/mcp", data=line.encode(), method="POST", headers=headers), timeout=60)
326
+ session = r.headers.get("mcp-session-id") or session
327
+ text = r.read().decode()
328
+ if r.status == 202 or not text.strip():
329
+ continue
330
+ sys.stdout.write(text.strip().replace("\n", "") + "\n"); sys.stdout.flush()
331
+ except urllib.error.HTTPError as e:
332
+ if msg.get("id") is not None:
333
+ m = "Sign in required: run `mocop auth login`" if e.code == 401 else f"HTTP {e.code}"
334
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32001, "message": m}}) + "\n"); sys.stdout.flush()
335
+ except Exception as e:
336
+ if msg.get("id") is not None:
337
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32000, "message": str(e)}}) + "\n"); sys.stdout.flush()
338
+
339
+
340
+ # ---------- dispatch ----------
341
+ def main():
342
+ try:
343
+ run()
344
+ except KeyboardInterrupt:
345
+ sys.exit(130)
346
+ except BrokenPipeError:
347
+ sys.exit(0)
348
+
349
+
350
+ def run():
351
+ if FLAGS.get("version"):
352
+ return out(VERSION)
353
+ if not POS or FLAGS.get("help") or POS[0] == "help":
354
+ return out(HELP)
355
+ cmd, a = POS[0], POS[1:]
356
+ g = FLAGS.get
357
+ if cmd == "search":
358
+ if not a: die("usage: mocop search <query>")
359
+ return printed(api("/api/v1/search" + qs(q=" ".join(a), type=g("type"), limit=g("limit"), offset=g("offset"))), print_results)
360
+ if cmd == "browse":
361
+ def h(x):
362
+ for o in x["items"]:
363
+ out(f"{clip(o['name'], 32):<32} {o['domain']:<28} {(o.get('readiness') or ''):<8} {o['apis']} api {o['mcp_servers']} mcp {o['agents']} agent {o['capability_total']} caps")
364
+ out(f"\n{x['total']} total")
365
+ return printed(api("/api/v1/orgs" + qs(q=g("q"), has=g("has"), sort=g("sort"), limit=g("limit"), offset=g("offset"))), h)
366
+ if cmd == "org":
367
+ if not a: die("usage: mocop org <slug> [kind [item]]")
368
+ def h(x):
369
+ if "items" in x and "name" in x:
370
+ out(f"{x['name']} ({x['domain']}) {x['capability_total']} capabilities\n{clip(x.get('description'), 300)}\n")
371
+ for e in x["items"]:
372
+ out(f" {e['type']:<8} {clip(e['name'], 40):<40} {e.get('path') or ''}")
373
+ else:
374
+ out(x)
375
+ return printed(api("/api/v1/orgs/" + "/".join(enc(s) for s in a)), h)
376
+ if cmd == "entity":
377
+ if not a: die("usage: mocop entity <slug>")
378
+ def h(e):
379
+ out(f"{e['name']} [{e['type']}] {e['domain']}\n{clip(e.get('description'), 400)}\nendpoint: {e.get('endpoint') or '-'} auth: {','.join(e.get('auth') or []) or '-'} verification: {e['verification']} capabilities: {e.get('capability_total')}")
380
+ return printed(api("/api/v1/entities/" + enc(a[0])), h)
381
+ if cmd == "capabilities":
382
+ if not a: die("usage: mocop capabilities <slug>")
383
+ def h(x):
384
+ for c in x["items"]:
385
+ out(f"{(c.get('method') or c.get('kind') or ''):<8} {clip(c.get('name') or c.get('title') or '', 44):<44} {clip(c.get('summary') or c.get('description') or '', 70)}")
386
+ out(f"\n{x['total']} total")
387
+ return printed(api(f"/api/v1/entities/{enc(a[0])}/capabilities" + qs(q=g("q"), group=g("group"), kind=g("kind"), method=g("method"), removed="1" if g("removed") else "", v=g("version"), limit=g("limit"), offset=g("offset"))), h)
388
+ if cmd == "versions":
389
+ if not a: die("usage: mocop versions <slug> [version]")
390
+ return out(api(f"/api/v1/entities/{enc(a[0])}/versions" + (f"/{enc(a[1])}" if len(a) > 1 else "")))
391
+ if cmd == "site":
392
+ if not a: die("usage: mocop site <domain>")
393
+ return out(api("/api/v1/sites/by-domain/" + enc(a[0])))
394
+ if cmd == "guide":
395
+ gd = api("/api/v1/guide")
396
+ return out(gd if JSON_OUT else gd["markdown"])
397
+ if cmd == "analyze":
398
+ if not a: die("usage: mocop analyze <domain>")
399
+ return analyze(a[0])
400
+ if cmd == "whoami":
401
+ return printed(api("/api/v1/me", auth=True), lambda x: out(f"{x['user']['email']} ({len(x['domains'])} domains, {len(x['favorites'])} favorites, {len(x['collections'])} collections)"))
402
+ if cmd == "domains":
403
+ sub, d = (a + ["list"])[0], (a[1] if len(a) > 1 else None)
404
+ if sub == "list":
405
+ def h(x):
406
+ for c in x["items"]:
407
+ out(f"{c['domain']:<32} {c['status']:<9} {str(c['score']) + '/10' if c.get('score') is not None else '-'} {ago(c.get('analyzed_at'))}")
408
+ if not x["items"]: out("No domains yet. Add one: mocop domains add example.com")
409
+ return printed(api("/api/v1/me/domains", auth=True), h)
410
+ if not d: die(f"usage: mocop domains {sub} <domain>")
411
+ if sub == "add":
412
+ r = api("/api/v1/me/domains", "POST", {"domain": d}, auth=True)
413
+ c = next((x for x in r["items"] if x["domain"] == d.lower()), r["items"][0])
414
+ return printed(r, lambda _: out(f"Added {c['domain']}. Publish this TXT record, then run: mocop domains verify {c['domain']}\n name: {c['verify']['dns_txt']['name']}\n value: {c['verify']['dns_txt']['value']}"))
415
+ if sub == "dns":
416
+ def h(x):
417
+ prov = x.get("provider")
418
+ out(f"{x['domain']}: DNS at {prov['name'] if prov else ', '.join(x['nameservers']) or 'unknown'}\n {x['record']['type']} {x['record']['full_name']}\n {x['record']['value']}" + (f"\n {prov['dashboard_url']}" if prov else ""))
419
+ return printed(api(f"/api/v1/me/domains/{enc(d)}/dns", auth=True), h)
420
+ if sub == "verify":
421
+ return printed(api(f"/api/v1/me/domains/{enc(d)}/verify", "POST", {}, auth=True), lambda x: out(f"Verified {d}. It is queued for indexing." if x.get("verified") else x.get("message")))
422
+ if sub in ("remove", "rm"):
423
+ return out(api(f"/api/v1/me/domains/{enc(d)}", "DELETE", auth=True))
424
+ die("usage: mocop domains [list|add|verify|dns|remove]")
425
+ if cmd == "favorites":
426
+ sub, d = (a + ["list"])[0], (a[1] if len(a) > 1 else None)
427
+ if sub == "list":
428
+ def h(x):
429
+ for f in x["items"]:
430
+ out(f"{f['domain']:<32} {f.get('name') or ''} {f.get('capability_total') or ''}")
431
+ if not x["items"]: out("No favorites yet.")
432
+ return printed(api("/api/v1/me/favorites", auth=True), h)
433
+ if not d: die(f"usage: mocop favorites {sub} <domain>")
434
+ if sub == "add": return out(api("/api/v1/me/favorites", "POST", {"domain": d}, auth=True))
435
+ if sub in ("rm", "remove"): return out(api(f"/api/v1/me/favorites/{enc(d)}", "DELETE", auth=True))
436
+ die("usage: mocop favorites [list|add|rm]")
437
+ if cmd == "collections":
438
+ sub, x, y = (a + ["list"])[0], (a[1] if len(a) > 1 else None), (a[2] if len(a) > 2 else None)
439
+ if sub == "list":
440
+ def h(z):
441
+ for c in z["items"]:
442
+ out(f"#{c['id']} {c['name']:<28} {', '.join(d['domain'] for d in c['domains'])}")
443
+ if not z["items"]: out("No collections yet.")
444
+ return printed(api("/api/v1/me/collections", auth=True), h)
445
+ if sub == "create": return out(api("/api/v1/me/collections", "POST", {"name": " ".join(a[1:])}, auth=True))
446
+ if sub == "rm": return out(api(f"/api/v1/me/collections/{enc(x)}", "DELETE", auth=True))
447
+ if sub == "add": return out(api(f"/api/v1/me/collections/{enc(x)}/items", "POST", {"domain": y}, auth=True))
448
+ if sub == "remove": return out(api(f"/api/v1/me/collections/{enc(x)}/items/{enc(y)}", "DELETE", auth=True))
449
+ die("usage: mocop collections [list|create|rm|add|remove]")
450
+ if cmd == "activity":
451
+ def h(x):
452
+ for e in x["items"]:
453
+ out(f"{ago(e['created_at']):<10} {e['kind']} {e.get('domain') or ''} {e.get('detail') or ''}")
454
+ return printed(api("/api/v1/me/activity", auth=True), h)
455
+ if cmd == "auth":
456
+ sub = a[0] if a else "status"
457
+ if sub == "login":
458
+ if g("device") or (not sys.stdout.isatty() and not g("no-browser") and not os.environ.get("DISPLAY") and sys.platform.startswith("linux")):
459
+ login_device()
460
+ else:
461
+ login_browser()
462
+ return out(f"Signed in as {api('/api/v1/me', auth=True)['user']['email']}")
463
+ if sub == "logout":
464
+ if os.path.exists(CRED): os.remove(CRED)
465
+ return out("Signed out.")
466
+ if sub == "token":
467
+ t = token()
468
+ if not t: die("not signed in", 2)
469
+ return out(t)
470
+ if sub == "status":
471
+ t = token()
472
+ if not t: return out("Not signed in. Run: mocop auth login")
473
+ try:
474
+ j = json.load(urllib.request.urlopen(urllib.request.Request(BASE + "/api/v1/me", headers={"authorization": f"Bearer {t}"}), timeout=30))
475
+ return out(f"Signed in as {j['user']['email']} ({BASE})")
476
+ except Exception:
477
+ return out("Credentials present but not accepted. Run: mocop auth login")
478
+ die("usage: mocop auth [login|logout|status|token]")
479
+ if cmd == "mcp":
480
+ return mcp_bridge()
481
+ die(f'unknown command "{cmd}". Run: mocop help')
482
+
483
+
484
+ if __name__ == "__main__":
485
+ main()