-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1920 lines (1757 loc) · 80.9 KB
/
Copy pathserver.py
File metadata and controls
1920 lines (1757 loc) · 80.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""tie-substack — local MCP server (stdio) for scheduling Substack posts.
Substack has no official write API, so this server wraps the community
`python-substack` library (Substack's internal endpoints) to create drafts,
pin the post slug (=> the public URL is known BEFORE publication), and
schedule publication. It exists so the tie-social skill can run its Substack
leg from Claude surfaces (Cowork/Desktop) without any credential ever
entering the model context.
Auth is a browser session cookie (`substack.sid`). It lives ONLY in this
server's local config file (mode 0600) — tools never echo it back, and the
refresh_cookie tool (pycookiecheat) pulls it straight from the local Chrome
profile into the config without displaying it. When a publication (or an
`act_as` pin) is configured, refresh_cookie SCANS ALL of the browser's
standard profiles (Default, Profile 1, ...) — the default profile gets no
special trust, since "reaches the publication" is not identity — and
proceeds ONLY when exactly one qualifying login exists; with several it
stores nothing and asks for an explicit `profile` (see list_profiles).
The optional `act_as` config pin restricts which logged-in identity
qualifies anywhere (including get_api's preflight, so every write tool is
gated). A per-client setup instead points `cookie_file` at a dedicated
browser's Cookies DB, which skips the scan entirely (see README
"Multiple clients").
Config file (~/.tie-substack/config.json, override via TIE_SUBSTACK_CONFIG):
{ "publication_url": "https://<pub>.substack.com",
"cookie_file": "~/TIE-Browsers/<client>/Default/Cookies", # optional
"act_as": "<substack handle>", # optional identity pin
"cookies": { "substack.sid": "...", ... } }
Multi-client: register one server entry PER CLIENT in claude_desktop_config
(e.g. "tie-substack-acme"), each with its own TIE_SUBSTACK_CONFIG +
SUBSTACK_PUBLICATION_URL, and a cookie_file pointing into that client's
dedicated browser. Sessions never mix across clients or Chrome profiles.
Env overrides:
SUBSTACK_PUBLICATION_URL publication URL (wins over config)
SUBSTACK_SESSION_TOKEN substack.sid value (wins over config cookies)
Protocol: MCP over stdio, newline-delimited JSON-RPC 2.0 (same plumbing as
wearevolt/tie-imagegen). Requires: python-substack; pycookiecheat optional
(only refresh_cookie needs it).
"""
import json
import os
import re
import stat
import sys
import threading
import time
import traceback
from datetime import datetime, timezone
SERVER_NAME = "tie-substack"
SERVER_VERSION = "0.4.2"
# Substack's Publish-dialog settings. Every one of these gets a value whether or
# not the caller picks it, so the tools always send them explicitly — see
# AUDIENCE/COMMENT notes in create_draft.
AUDIENCE_VALUES = ("everyone", "only_free", "only_paid", "founding")
COMMENT_VALUES = ("none", "only_paid", "everyone") # "none" == comments disabled
# Meaningless (and rejected by the UI) unless the publication sells subscriptions.
PAID_AUDIENCE_VALUES = ("only_free", "only_paid", "founding")
FALLBACK_PROTOCOL = "2025-06-18"
CONFIG_PATH = os.path.expanduser(
os.environ.get("TIE_SUBSTACK_CONFIG", "~/.tie-substack/config.json")
)
_write_lock = threading.Lock()
_api_lock = threading.Lock()
_api_cache = {"api": None}
def log(msg):
sys.stderr.write("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg))
sys.stderr.flush()
def send(obj):
line = json.dumps(obj, separators=(",", ":"))
with _write_lock:
sys.stdout.write(line + "\n")
sys.stdout.flush()
def reply(req_id, result):
send({"jsonrpc": "2.0", "id": req_id, "result": result})
def reply_error(req_id, code, message):
send({"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}})
# ---------------------------------------------------------------- config
def load_config():
try:
with open(CONFIG_PATH) as f:
return json.load(f)
except FileNotFoundError:
return {}
except Exception as e: # noqa: BLE001
raise RuntimeError("config file %s is unreadable: %s" % (CONFIG_PATH, e))
def save_config(cfg):
d = os.path.dirname(CONFIG_PATH)
os.makedirs(d, exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(cfg, f, indent=2)
os.chmod(CONFIG_PATH, stat.S_IRUSR | stat.S_IWUSR) # 0600 — it holds a session cookie
def normalize_publication_url(url):
"""Force the https://<name>.substack.com form python-substack's resolver requires.
Its Api.__init__ extracts the subdomain with a regex containing a literal
'https://', so a bare host or an http:// URL silently resolves to no
publication and later blows up as 'NoneType' is not subscriptable.
"""
u = (url or "").strip().rstrip("/")
if not u:
return ""
if u.lower().startswith("http://"):
u = "https://" + u[len("http://"):]
elif not u.lower().startswith("https://"):
u = "https://" + u
return u
def raw_publication_url():
return os.environ.get("SUBSTACK_PUBLICATION_URL") or load_config().get(
"publication_url"
) or ""
def publication_url():
url = normalize_publication_url(raw_publication_url())
if not url:
raise RuntimeError(
"publication_url is not configured — set SUBSTACK_PUBLICATION_URL or add "
'"publication_url" to %s (e.g. via install.command)' % CONFIG_PATH
)
return url
SUBDOMAIN_RE = re.compile(r"^https://([^./]+)\.substack\.com$", re.I)
def configured_subdomain():
"""The publication subdomain, or None if the URL isn't a *.substack.com one."""
m = SUBDOMAIN_RE.match(publication_url())
return m.group(1).lower() if m else None
def current_cookies():
"""Cookie dict from env override or config. Values NEVER leave this process."""
token = os.environ.get("SUBSTACK_SESSION_TOKEN")
if token:
return {"substack.sid": token}
return load_config().get("cookies") or {}
def cookies_string(cookies):
return "; ".join("%s=%s" % (k, v) for k, v in cookies.items())
def resolve_cookie_file(arg_value):
"""Cookie-DB path for refresh_cookie: explicit arg > config 'cookie_file' > None
(None = the browser's default profile). The multi-client setup stores a per-client
path (a dedicated browser's <user-data-dir>/Default/Cookies) in each client config."""
raw = arg_value or load_config().get("cookie_file")
return os.path.expanduser(raw) if raw else None
CHROME_FAMILY_DATA_DIRS = {
"chrome": "~/Library/Application Support/Google/Chrome",
"chromium": "~/Library/Application Support/Chromium",
"brave": "~/Library/Application Support/BraveSoftware/Brave-Browser",
}
def chrome_profile_cookie_files(browser, root=None):
"""(profile_name, cookie_file) for every profile of the browser's STANDARD data dir
(Default, Profile 1, ...). Dedicated --user-data-dir browsers live elsewhere and are
not discoverable — those are addressed explicitly via cookie_file (the multi-client
model). macOS paths — this server's install story is macOS-only."""
base = root or CHROME_FAMILY_DATA_DIRS.get(browser)
if not base:
return []
base = os.path.expanduser(base)
if not os.path.isdir(base):
return []
out = []
for name in sorted(os.listdir(base)):
if name == "Default" or name.startswith("Profile "):
cf = os.path.join(base, name, "Cookies")
if os.path.isfile(cf):
out.append((name, cf))
return out
def standard_install_browser(path):
"""Which browser family's STANDARD install contains this cookie path — or
None for a dedicated --user-data-dir browser. Distinguishes scan/profile-
persisted pins from the multi-client model's dedicated paths (only the
former can silently hold a wrong login), and names the family so a legacy
re-validation scans the browser that actually produced the path."""
if not path:
return None
p = os.path.expanduser(path)
for b, root in CHROME_FAMILY_DATA_DIRS.items():
if p.startswith(os.path.expanduser(root) + os.sep):
return b
return None
def in_standard_install(path):
return standard_install_browser(path) is not None
def legacy_unpinned(cfg):
"""Pre-0.4.0 state: a standard-install cookie_file with no identity pin.
Every 0.4.0 success path that persists a standard-install path also pins
act_as (explicit profile AND scan-validated matches), so this combination
can only be inherited — and the stored session may be the wrong login (the
old scan took the first match). Every tool that talks to Substack (reads
included — get_api serves both) refuses in this state until a refresh
re-validates it; one no-arg refresh_cookie heals it. An explicit
SUBSTACK_SESSION_TOKEN is exempt: it overrides config cookies entirely
(current_cookies), and that session is probed and identity-gated on its
own — stale local config must not block a CI/env-driven setup."""
if os.environ.get("SUBSTACK_SESSION_TOKEN"):
return False
return (not (cfg.get("act_as") or "").strip()
and in_standard_install(cfg.get("cookie_file")))
def local_state_path(browser, root=None):
"""Path to the browser's plaintext 'Local State' JSON, or None for an
unknown browser. The file maps profile dirs to display names/emails."""
base = root or CHROME_FAMILY_DATA_DIRS.get(browser)
if not base:
return None
return os.path.join(os.path.expanduser(base), "Local State")
def local_state_profiles(browser, root=None):
"""[{dir, name, email}] for every profile in the browser's 'Local State'
(profile.info_cache). Names/emails only — never touches the Cookies DB or
the Keychain. `root=` addresses a dedicated --user-data-dir browser (and
is the test seam). Missing file -> [] so callers can degrade gracefully."""
path = local_state_path(browser, root)
if not path or not os.path.isfile(path):
return []
try:
with open(path) as f:
data = json.load(f)
except Exception as e: # noqa: BLE001
raise RuntimeError("could not parse %s: %s" % (path, e))
info = (data.get("profile") or {}).get("info_cache") or {}
out = []
for d in sorted(info):
meta = info[d] or {}
out.append({
"dir": d,
"name": meta.get("name") or meta.get("gaia_name") or "",
"email": meta.get("user_name") or "",
})
return out
def resolve_profile_selector(selector, browser, root=None):
"""The one profile a human-friendly selector means. Matched case-insensitively
against directory name, display name, and email — exact first, substring only
when nothing matches exactly (so 'Person 1' is not ambiguous with 'Person 10').
Anything but exactly one hit is an error listing what IS available."""
profiles = local_state_profiles(browser, root)
if not profiles:
raise RuntimeError(
'no browser profiles found — no "Local State" file under %s '
"(is %s installed?)"
% (root or CHROME_FAMILY_DATA_DIRS.get(browser), browser)
)
sel = (selector or "").strip().lower()
if not sel:
raise ValueError("profile selector is empty")
def fields(p):
return (p["dir"].lower(), p["name"].lower(), p["email"].lower())
cands = [p for p in profiles if sel in fields(p)]
if not cands:
cands = [p for p in profiles if any(sel in f for f in fields(p) if f)]
if len(cands) == 1:
return cands[0]
if not cands:
raise ValueError(
"profile %r does not match any %s profile — available: %s "
"(see list_profiles)" % (selector, browser, profiles)
)
raise ValueError(
"profile %r matches %d profiles: %s — use the exact directory name, "
"display name, or email (see list_profiles)" % (selector, len(cands), cands)
)
def read_browser_cookies(pycookiecheat, browser, cookie_file, errors):
"""One profile's substack.com cookies, or None. pycookiecheat's API moved between
versions — try the new form, then the old."""
url = "https://substack.com"
try:
bt = pycookiecheat.BrowserType(browser)
return pycookiecheat.chrome_cookies(url, browser=bt, cookie_file=cookie_file) \
if browser != "firefox" else pycookiecheat.firefox_cookies(url)
except Exception as e: # noqa: BLE001
errors.append(str(e))
try:
return pycookiecheat.chrome_cookies(url, cookie_file=cookie_file)
except Exception as e2: # noqa: BLE001
errors.append(str(e2))
return None
def publication_accessible(probe, target):
"""Can this session act on publication `target`? The SINGLE access predicate —
cookie selection (session_reaches), get_api's preflight, and substack_status must
all agree, or refresh_cookie can pick a session that later fails api_ready.
`primary` counts: a primary-only profile (primaryPublication set but absent from
publicationUsers) is still an account of that publication. Case-insensitive —
probe_session lowercases subdomains but not primary, and targets are lowercased."""
if not target:
return True
t = target.lower()
subs = [s.lower() for s in (probe.get("subdomains") or [])]
prim = (probe.get("primary") or "").lower()
return t in subs or t == prim
def accessible_publications(probe):
"""For error messages: everything the session can act on, primary included."""
out = [s.lower() for s in (probe.get("subdomains") or [])]
prim = (probe.get("primary") or "").lower()
if prim and prim not in out:
out.append(prim)
return sorted(out)
def identity_matches(probe, act_as):
"""Does the probed session belong to the pinned identity? act_as matches the
Substack handle (what the server itself persists) or, as a hand-typed
convenience, the account email when the profile API reports one. Unset pin
-> everything qualifies. Kept separate from session_reaches so callers can
tell 'wrong publication' from 'wrong identity' in error messages."""
if not act_as:
return True
a = act_as.strip().lower()
return (
((probe or {}).get("handle") or "").strip().lower() == a
or ((probe or {}).get("email") or "").strip().lower() == a
)
def session_reaches(cookies, target):
"""(matches, probe): the session is valid AND can access publication `target`
(any valid session counts when target is None)."""
if not cookies or "substack.sid" not in cookies:
return False, None
try:
ok, probe = probe_session(cookies)
except Exception: # noqa: BLE001
return False, None
if not ok:
return False, probe
if not publication_accessible(probe, target):
return False, probe
return True, probe
def probe_session(cookies):
"""Check the session WITHOUT depending on publication resolution.
Returns (ok, info). Keeps 'session expired' distinguishable from
'this account has no access to the configured publication' — the two
failures look identical once python-substack's Api.__init__ is involved.
"""
import requests # noqa: PLC0415 (a python-substack dependency)
r = requests.get(
"https://substack.com/api/v1/user/profile/self", cookies=cookies, timeout=30
)
if r.status_code in (401, 403):
return False, {"reason": "session_invalid", "status": r.status_code}
r.raise_for_status()
data = r.json() or {}
subdomains = []
for pu in data.get("publicationUsers") or []:
pub = pu.get("publication") or {}
if pub.get("subdomain"):
subdomains.append(pub["subdomain"].lower())
return True, {
"handle": data.get("handle") or data.get("name"),
"email": data.get("email"),
"user_id": data.get("id"),
"subdomains": subdomains,
"primary": (data.get("primaryPublication") or {}).get("subdomain"),
}
def get_api(fresh=False):
"""python-substack Api, cached (its __init__ does network round-trips)."""
with _api_lock:
if _api_cache["api"] is not None and not fresh:
# The act_as pin must hold for CACHED clients too — the config can
# change under a warm cache (hand-edit, another tool), and a cache
# hit must never hand back a client the pin no longer trusts. On
# mismatch (or a legacy-unpinned config), drop the cache and fall
# through to the full preflight, which raises the canonical error.
cfg_now = load_config()
if not legacy_unpinned(cfg_now) and identity_matches(
{"handle": _api_cache.get("handle"), "email": _api_cache.get("email")},
(cfg_now.get("act_as") or "").strip(),
):
return _api_cache["api"]
_api_cache["api"] = None
cookies = current_cookies()
if not cookies.get("substack.sid"):
raise RuntimeError(
"no substack.sid cookie configured. Run the refresh_cookie tool (pulls it "
"from your local Chrome via pycookiecheat), or paste it manually into %s as "
'{"cookies": {"substack.sid": "<value>"}}. Never paste the cookie into chat.'
% CONFIG_PATH
)
url = publication_url()
sub = configured_subdomain()
if not sub:
raise RuntimeError(
"publication_url %r is not a https://<name>.substack.com URL. The underlying "
"python-substack library resolves the publication by exactly that form, so a "
"custom domain cannot be used here — configure the canonical Substack URL in "
"%s." % (url, CONFIG_PATH)
)
# Pre-flight so failures name their real cause instead of surfacing as
# "'NoneType' object is not subscriptable" from inside change_publication().
ok, probe = probe_session(cookies)
if not ok:
raise RuntimeError(
"Substack session is invalid or expired (HTTP %s) — run refresh_cookie"
% probe.get("status")
)
if not publication_accessible(probe, sub):
raise RuntimeError(
"the logged-in account (%s) has no access to publication %r. Publications "
"available to this session: %s. Either fix publication_url in %s, or refresh "
"the cookie from a browser logged in as a user of %r."
% (probe["handle"], sub, accessible_publications(probe) or "(none)",
CONFIG_PATH, sub)
)
cfg_now = load_config()
act_as = (cfg_now.get("act_as") or "").strip()
if legacy_unpinned(cfg_now):
# A wrong-but-valid session inherited from ≤0.3.0 must not reach
# any Substack-facing tool (reads included — acting as the wrong
# identity is misleading either way) before refresh_cookie runs.
raise RuntimeError(
"this config has a pre-0.4.0 standard-install cookie_file with no "
"identity pin — the stored session (currently logged in as %r) may "
"be the wrong login. Run refresh_cookie (it re-validates via the "
'profile scan) or refresh_cookie with profile: "<login>" before '
"reading or writing as this account. Config: %s"
% (probe.get("handle"), CONFIG_PATH)
)
if not identity_matches(probe, act_as):
# The pin gates every write tool here, not just refresh_cookie — a
# stale, hand-pasted, or env-injected cookie must not act as the
# wrong account just because it can reach the publication.
raise RuntimeError(
"the session is logged in as %r, not the pinned act_as=%r — run "
"refresh_cookie (optionally with profile:, see list_profiles), or "
"change/remove act_as in %s." % (probe["handle"], act_as, CONFIG_PATH)
)
from substack import Api # noqa: PLC0415
if not hasattr(Api, "create_draft_from_markdown"):
raise RuntimeError(
"the installed python-substack library is too old for this server "
"(no Api.create_draft_from_markdown — typically a venv built on "
"Python < 3.10, where pip silently resolves the 2023-era library). "
"Fix: re-run the installer, which now requires Python 3.10+ and a "
"pinned library: bash -c \"$(curl -fsSL https://raw.github"
"usercontent.com/wearevolt/tie-substack/main/install.command)\""
)
api = Api(cookies_string=cookies_string(cookies), publication_url=url)
_api_cache["api"] = api
# Remember whose session this client wraps, so cache hits can re-check
# the act_as pin without a network probe.
_api_cache["handle"] = probe.get("handle")
_api_cache["email"] = probe.get("email")
return api
def reset_api():
with _api_lock:
_api_cache["api"] = None
_api_cache["handle"] = None
_api_cache["email"] = None
# ---------------------------------------------------------------- helpers
def publication_capabilities(api):
"""What this publication can actually do — so choices offered are real ones.
Verified against a live personal-mode publication: `payments_state` is the
paid-subscription signal, and get_sections() raises APIError(400) when the
publication has none rather than returning an empty list.
"""
pub = api.get_user_primary_publication() or {}
state = pub.get("payments_state")
caps = {
"publication": pub.get("subdomain"),
"name": pub.get("name"),
"publication_url": pub.get("publication_url"),
"payments_state": state,
"paid_enabled": bool(state) and state != "disabled",
"pledges_enabled": pub.get("pledges_enabled"),
"personal_mode": pub.get("is_personal_mode"),
}
try:
sections = api.get_sections() or []
caps["sections"] = [
{"id": s.get("id"), "name": s.get("name")}
for s in sections
if isinstance(s, dict)
]
except Exception as e: # noqa: BLE001
caps["sections"] = []
caps["sections_note"] = "no sections on this publication (%s)" % str(e)[:120]
try:
tags = api.get_publication_post_tags() or []
caps["existing_tags"] = [
{"id": t.get("id"), "name": t.get("name")} for t in tags if isinstance(t, dict)
]
except Exception as e: # noqa: BLE001
caps["existing_tags"] = []
caps["tags_note"] = "could not list tags: %s" % str(e)[:120]
if not caps["paid_enabled"]:
caps["unavailable"] = {
"audience": list(PAID_AUDIENCE_VALUES),
"comment_permissions": ["only_paid"],
"reason": "publication has no paid subscriptions (payments_state=%r)" % state,
}
# Substack's publication payload carries no timezone, so every scheduling
# call must pass an explicit UTC offset (the tools enforce that).
caps["timezone"] = None
return caps
def validate_settings(audience, comments, caps):
if audience not in AUDIENCE_VALUES:
raise ValueError(
"audience %r is invalid — choose one of %s" % (audience, list(AUDIENCE_VALUES))
)
if comments not in COMMENT_VALUES:
raise ValueError(
"comment_permissions %r is invalid — choose one of %s ('none' disables comments)"
% (comments, list(COMMENT_VALUES))
)
if not caps.get("paid_enabled"):
if audience in PAID_AUDIENCE_VALUES:
raise ValueError(
"audience %r needs paid subscriptions, which this publication does not have "
"(payments_state=%r) — use 'everyone'"
% (audience, caps.get("payments_state"))
)
if comments == "only_paid":
raise ValueError(
"comment_permissions 'only_paid' needs paid subscriptions, which this "
"publication does not have — use 'everyone' or 'none'"
)
def resolve_tags(api, wanted, caps=None):
"""Split requested tags into existing vs new. Tags are PUBLICATION-level
objects: applying an unknown one creates it permanently, so the caller must
opt in to that."""
existing = {
(t.get("name") or "").strip().lower(): t
for t in ((caps or {}).get("existing_tags") or [])
}
if caps is None:
try:
existing = {
(t.get("name") or "").strip().lower(): t
for t in (api.get_publication_post_tags() or [])
if isinstance(t, dict)
}
except Exception: # noqa: BLE001
existing = {}
norm, seen = [], set()
for raw in wanted or []:
t = re.sub(r"[^a-z0-9]+", "-", (raw or "").strip().lower()).strip("-")
if t and t not in seen:
seen.add(t)
norm.append(t)
return {
"normalized": norm,
"existing": [t for t in norm if t in existing],
"new": [t for t in norm if t not in existing],
}
def read_post_tags(api, post_id):
"""Tags actually attached, read from the association endpoint.
The draft payload has NO postTags field (verified: the key is absent, not
null), so a request echo would be the only alternative — and this is the last
place where that would still be the case. `GET post/<id>/tag` returns
association rows carrying post_tag_id (a UUID string), which we map to names
via the publication's tag list.
"""
rows = api.call("post/%s/tag" % post_id, "GET") or []
if not isinstance(rows, list):
return {"names": [], "note": "unexpected response shape from post/<id>/tag"}
names_by_id = {}
try:
for t in api.get_publication_post_tags() or []:
if isinstance(t, dict):
names_by_id[str(t.get("id"))] = t.get("name")
except Exception: # noqa: BLE001
pass
names = []
for r in rows:
if not isinstance(r, dict):
continue
tid = str(r.get("post_tag_id") or r.get("id") or "")
names.append(names_by_id.get(tid) or ("tag:%s" % tid))
return {"names": names}
def post_url_for_slug(slug):
if not slug:
return None
try:
return "%s/p/%s" % (publication_url(), slug)
except RuntimeError:
return None
def unwrap_items(raw, *keys):
"""Substack wraps collections in an object (e.g. {"posts": [...]}) — unwrap it."""
if isinstance(raw, dict):
for k in keys:
v = raw.get(k)
if isinstance(v, list):
return v
return []
return raw or []
def draft_summary(draft):
"""Public, cookie-free summary of a draft dict returned by the API."""
if not isinstance(draft, dict):
return {"warning": "unexpected draft payload shape", "raw": str(draft)[:200]}
slug = draft.get("slug") or draft.get("draft_slug")
published = draft.get("is_published")
if published is None:
published = bool(draft.get("post_date"))
draft_id = draft.get("id")
summary = {
"draft_id": draft_id,
# Unpublished drafts keep the working title in draft_title and leave title null.
"title": draft.get("draft_title") or draft.get("title") or "(untitled draft)",
"slug": slug,
"post_url": post_url_for_slug(slug),
"is_published": bool(published),
"updated_at": draft.get("draft_updated_at") or draft.get("updated_at"),
# Settings as STORED by Substack (never as requested) — the caller shows
# these to the user, so an echo of our own payload would be misleading.
"audience": draft.get("audience"),
"comment_permissions": draft.get("write_comment_permissions"),
"send_email": draft.get("should_send_email"),
}
# The list payload is a narrower projection than get_draft: subtitle, SEO,
# section and free-preview keys are ABSENT there (not null). Reporting null
# for an absent key would read as "empty", so only report what the payload
# actually carries.
if "draft_subtitle" in draft or "subtitle" in draft:
summary["subtitle"] = draft.get("draft_subtitle") or draft.get("subtitle")
else:
summary["subtitle_note"] = "not in this payload — call get_draft to read it"
for key, field in (
("send_free_preview", "should_send_free_preview"),
("section_id", "draft_section_id"),
("seo_title", "search_engine_title"),
("seo_description", "search_engine_description"),
):
if field in draft:
summary[key] = draft.get(field)
if draft.get("email_sent_at"):
summary["email_already_sent_at"] = draft["email_sent_at"]
# trigger_at lives in postSchedules, and ONLY on the single-draft payload —
# the list payload omits the key entirely, so absence != "not scheduled".
if "postSchedules" in draft:
schedules = draft.get("postSchedules") or []
trigger = None
for s in schedules:
if isinstance(s, dict) and s.get("trigger_at"):
trigger = s["trigger_at"]
break
summary["scheduled_for"] = trigger
else:
summary["scheduled_for_note"] = "not in this payload — call get_draft to read it"
try:
summary["editor_url"] = "%s/publish/post/%s" % (publication_url(), draft_id)
except RuntimeError:
pass
if not slug:
summary["post_url_note"] = (
"no slug set on this draft yet — call set_slug to pin the public URL"
)
return summary
def parse_iso_aware(value):
"""Parse an ISO 8601 timestamp and REQUIRE timezone info (naive = silent UTC bug)."""
v = (value or "").strip()
if v.endswith("Z"):
v = v[:-1] + "+00:00"
try:
dt = datetime.fromisoformat(v)
except ValueError:
raise ValueError("invalid ISO 8601 datetime: %r" % value)
if dt.tzinfo is None:
raise ValueError(
"datetime %r has no timezone — pass an offset (e.g. 2026-08-03T09:00:00-04:00) "
"so the schedule can't silently shift" % value
)
return dt
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
def validate_slug(slug):
if not SLUG_RE.match(slug or ""):
raise ValueError(
"slug %r is invalid — use lowercase words separated by single hyphens, "
"e.g. 'program-management-another-year-another-obituary'" % slug
)
return slug
def text_result(payload):
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}]}
# ---------------------------------------------------------------- tools
TOOLS = [
{
"name": "substack_status",
"description": (
"Health check: is a session cookie configured and still valid, which user and "
"publication it maps to, python-substack/pycookiecheat availability. Run this "
"first; if the cookie is dead it says so and points at refresh_cookie."
),
"inputSchema": {"type": "object", "properties": {}},
},
{
"name": "refresh_cookie",
"description": (
"Pull the current substack.com session cookies from the LOCAL browser profile "
"(via pycookiecheat; macOS will prompt for Keychain access) and store them in "
"the server's 0600 config file. When a publication is configured (and no "
"cookie_file is set), ALL of the browser's standard profiles are scanned — "
"the default profile gets no special trust; when EXACTLY ONE login reaches "
"the publication it is chosen, persisted, and pinned as act_as, and with "
"several distinct logins nothing is stored and the error lists the "
"candidates so you re-run with `profile`. An `act_as` config pin restricts which logged-in identity "
"qualifies at all. The cookie value is never returned or shown — the result "
"only lists cookie NAMES, profile names/handles, and the validation outcome. "
"Requires the user to be logged in to Substack in that browser. Run only when "
"the user asks to refresh/repair Substack auth."
),
"inputSchema": {
"type": "object",
"properties": {
"browser": {
"type": "string",
"enum": ["chrome", "chromium", "brave", "firefox"],
"default": "chrome",
"description": "Which local browser profile to read the cookie from.",
},
"cookie_file": {
"type": "string",
"description": (
"Absolute path to a specific Chrome-family 'Cookies' SQLite file "
"to read INSTEAD of the browser's default profile — the "
"multi-client setup points this at a dedicated per-client "
"browser, e.g. ~/TIE-Browsers/<client>/Default/Cookies. Omit to "
"use this server config's stored 'cookie_file' (if any), else "
"the default profile. Not supported with browser=firefox."
),
},
"profile": {
"type": "string",
"description": (
"Pick ONE profile of the standard browser install by directory "
"name ('Profile 2'), display name, or signed-in email — "
"case-insensitive, exact or unique substring (run list_profiles "
"first). Use when several logins reach the same publication. "
"Mutually exclusive with cookie_file; not supported with "
"browser=firefox."
),
},
"confirm_switch": {
"type": "boolean",
"description": (
"Required true to SWITCH the pinned identity: when `profile` "
"resolves to a login different from the configured act_as, the "
"call refuses unless this is set, and on success the pin is "
"rewritten to the new login. Only meaningful together with "
"`profile`. Pass it ONLY when the user explicitly asked to act "
"as a different account — never on your own initiative."
),
},
},
},
},
{
"name": "list_profiles",
"description": (
"List the local Chrome-family browser's profiles (directory, display name, "
"signed-in email) by parsing the browser's plaintext 'Local State' file. "
"Reads NO cookie data and triggers NO Keychain prompt — use it to pick the "
"`profile` argument for refresh_cookie when several Substack logins reach "
"the same publication."
),
"inputSchema": {
"type": "object",
"properties": {
"browser": {
"type": "string",
"enum": ["chrome", "chromium", "brave"],
"default": "chrome",
"description": "Which browser's profiles to list.",
},
"root": {
"type": "string",
"description": (
"Override the browser user-data directory (e.g. a dedicated "
"per-client browser like ~/TIE-Browsers/<client>). Default: "
"the standard install location for `browser`."
),
},
},
},
},
{
"name": "get_publication_settings",
"description": (
"Read what the publication can actually do, so you only offer valid choices: "
"paid subscriptions enabled?, available sections, existing publication tags, "
"and which audience/comment values are therefore unavailable. Call this BEFORE "
"assembling a settings proposal for the user."
),
"inputSchema": {"type": "object", "properties": {}},
},
{
"name": "create_draft",
"description": (
"Create a Substack draft from Markdown with the slug pinned, so the public URL "
"(<publication>/p/<slug>) is known before publication. Returns draft_id, slug, "
"post_url, editor_url and the settings AS STORED by Substack. Body images "
"referenced as local paths/URLs are uploaded by the library. Does NOT publish "
"or schedule.\n\n"
"Every Publish-dialog setting gets a value whether or not you pass one, so the "
"defaults here are explicit and visible. Show them to the user before "
"scheduling. Note: comment_permissions is ALWAYS sent explicitly, because the "
"underlying library silently copies `audience` into it when omitted (so an "
"only_paid audience would quietly make comments paid-only). Validate choices "
"against get_publication_settings first — paid-only values fail on a "
"publication without paid subscriptions."
),
"inputSchema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"subtitle": {"type": "string", "default": ""},
"body_markdown": {
"type": "string",
"description": (
"Full post body as Markdown. Can be a short placeholder — the team "
"usually pastes/polishes the real text in the Substack editor; the "
"point of creating the draft here is pinning the slug + schedule."
),
},
"slug": {
"type": "string",
"description": "The post URL slug to pin (lowercase-hyphenated).",
},
"audience": {
"type": "string",
"enum": list(AUDIENCE_VALUES),
"default": "everyone",
"description": "Who can read it. Non-'everyone' values need paid subs.",
},
"comment_permissions": {
"type": "string",
"enum": list(COMMENT_VALUES),
"default": "everyone",
"description": "Who may comment; 'none' disables comments.",
},
"send_email": {
"type": "boolean",
"default": True,
"description": (
"Whether publishing emails subscribers. Sending is IRREVERSIBLE; "
"schedule_draft/publish_draft additionally require an explicit "
"confirm_send_email when this is true."
),
},
"tags": {
"type": "array",
"items": {"type": "string"},
"description": (
"Publication-level tags. Applying an unknown tag CREATES it "
"permanently, so new tags are refused unless allow_new_tags is true."
),
},
"allow_new_tags": {"type": "boolean", "default": False},
"section_id": {
"type": ["integer", "string", "null"],
"description": "Publication section id (see get_publication_settings).",
},
"seo_title": {"type": "string", "description": "Defaults to title."},
"seo_description": {
"type": "string",
"description": "Defaults to subtitle.",
},
},
"required": ["title", "body_markdown", "slug"],
},
},
{
"name": "update_post_settings",
"description": (
"Change settings on an existing draft without recreating it: audience, "
"comment_permissions, send_email, send_free_preview, section_id, seo_title, "
"seo_description, title, subtitle. Returns the settings as stored afterwards."
),
"inputSchema": {
"type": "object",
"properties": {
"draft_id": {"type": ["integer", "string"]},
"audience": {"type": "string", "enum": list(AUDIENCE_VALUES)},
"comment_permissions": {"type": "string", "enum": list(COMMENT_VALUES)},
"send_email": {"type": "boolean"},
"send_free_preview": {"type": "boolean"},
"section_id": {"type": ["integer", "string", "null"]},
"seo_title": {"type": "string"},
"seo_description": {"type": "string"},
"title": {"type": "string"},
"subtitle": {"type": "string"},
},
"required": ["draft_id"],
},
},
{
"name": "apply_tags",
"description": (
"Attach publication tags to a draft. Tags are publication-level objects: an "
"unknown tag is CREATED permanently and typos are durable, so this reports "
"which tags are existing vs new and refuses to create new ones unless "
"allow_new is true. Call it as its own confirmed step, not silently."
),
"inputSchema": {
"type": "object",
"properties": {
"draft_id": {"type": ["integer", "string"]},
"tags": {"type": "array", "items": {"type": "string"}},
"allow_new": {"type": "boolean", "default": False},
},
"required": ["draft_id", "tags"],
},
},
{
"name": "set_slug",
"description": (
"Set/replace the URL slug of an existing draft. Returns the updated slug and "
"post_url. Fails on already-published posts."
),
"inputSchema": {
"type": "object",