python-substack 0.6.0__py3-none-any.whl → 0.7.0__py3-none-any.whl

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-substack
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Write and safely manage Substack drafts from Markdown with Python, CLI, and MCP.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -22,7 +22,7 @@ Classifier: Topic :: Internet :: WWW/HTTP
22
22
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
23
  Provides-Extra: mcp
24
24
  Requires-Dist: PyYAML (>=6.0,<7.0)
25
- Requires-Dist: fastmcp (>=3.1.1,<4.0.0) ; extra == "mcp"
25
+ Requires-Dist: fastmcp (>=3.1.1,<5.0.0) ; extra == "mcp"
26
26
  Requires-Dist: markdown-it-py (>=3,<5)
27
27
  Requires-Dist: mdit-py-plugins (>=0.5,<0.7)
28
28
  Requires-Dist: python-dotenv (>=1.2.1,<2.0.0)
@@ -0,0 +1,14 @@
1
+ substack/__init__.py,sha256=soBT45w3E1XVhTYcV9Y_1D363e35S4_Q0mFrF13pHHM,450
2
+ substack/api.py,sha256=nBEnD2ipxSAWR99iwNgCfGD4-y8YYwKNmilq2y1VP8M,29903
3
+ substack/cli.py,sha256=L-nR45tJDTuvZrinj-dApXzw6-CgXcwaodyX7CpYFm4,25720
4
+ substack/exceptions.py,sha256=Y61XSPyxDxXPbVlioFvKhb94MRY0tpD389F5YdL1rGM,1390
5
+ substack/mdexport.py,sha256=_pSjioPJIA1wuJ6hYpvODZVswPSUROuzEndVoYnv-yU,13541
6
+ substack/mdrender.py,sha256=QGJkdp1isFmhVyTRMogIabAK8OO2xQh9CrjnXZvFTY4,9308
7
+ substack/nodes.py,sha256=fTsGO0-lTztcXiloIjXrHVnJes9EcltGcrX-mEV2ceQ,5004
8
+ substack/post.py,sha256=qDXu-xzO3nRXtahc-yG2EhxKAXB2hG_Z1nLa55UMBGg,19697
9
+ substack_mcp/mcp_server.py,sha256=M5XH3C4iWjzvCw3uOPbY2NFljTQAl8FLt14RKaTzka0,11324
10
+ python_substack-0.7.0.dist-info/METADATA,sha256=-_DF7Ln42oZYd1uPqaFQgAAZHsgka8-FqwP6VfbshVQ,8689
11
+ python_substack-0.7.0.dist-info/WHEEL,sha256=kJCRJT_g0adfAJzTx2GUMmS80rTJIVHRCfG0DQgLq3o,88
12
+ python_substack-0.7.0.dist-info/entry_points.txt,sha256=MKPjaBUd-0PtvxsBviStsVq1c0h8JZ_qUoYEsBK1xJc,236
13
+ python_substack-0.7.0.dist-info/licenses/LICENSE,sha256=L6jk148I5HhhVbfUvkO3EO7eAoU5zToLio4-ApkCkxg,1062
14
+ python_substack-0.7.0.dist-info/RECORD,,
substack/__init__.py CHANGED
@@ -3,7 +3,7 @@
3
3
  __author__ = "Paolo Mazza"
4
4
  __email__ = "mazzapaolo2019@gmail.com"
5
5
  __license__ = "MIT License"
6
- __version__ = "0.6.0"
6
+ __version__ = "0.7.0"
7
7
  __url__ = "https://github.com/ma2za/python-substack"
8
8
  __download_url__ = "https://pypi.python.org/pypi/python-substack"
9
9
  __description__ = (
substack/api.py CHANGED
@@ -464,6 +464,95 @@ class Api:
464
464
  "unsupported_nodes": unsupported_nodes,
465
465
  }
466
466
 
467
+ def update_draft_from_markdown(
468
+ self,
469
+ draft_id: int,
470
+ markdown: str,
471
+ *,
472
+ subtitle: str = None,
473
+ audience: str = None,
474
+ write_comment_permissions: str = None,
475
+ search_engine_title: str = None,
476
+ search_engine_description: str = None,
477
+ slug: str = None,
478
+ draft_section_id: int = None,
479
+ tags=None,
480
+ dry_run: bool = False,
481
+ ) -> dict:
482
+ """
483
+ Update an existing draft body from Markdown, with optional metadata changes.
484
+ """
485
+ from substack.mdexport import document_to_markdown
486
+ from substack.post import Post
487
+
488
+ draft = self.get_draft(draft_id)
489
+ draft_body = draft.get("draft_body")
490
+ if isinstance(draft_body, str):
491
+ try:
492
+ draft_body = json.loads(draft_body)
493
+ except json.JSONDecodeError as exc:
494
+ raise ValueError(
495
+ "Malformed draft body: draft_body is not valid JSON"
496
+ ) from exc
497
+ if not isinstance(draft_body, dict):
498
+ raise ValueError("Malformed draft body: draft_body must be a JSON object")
499
+
500
+ _, unsupported_nodes = document_to_markdown(draft_body)
501
+ if unsupported_nodes:
502
+ raise ValueError(
503
+ "Refusing to update: remote draft contains unsupported Substack nodes. "
504
+ "Export it first or remove the nodes manually to avoid data loss."
505
+ )
506
+
507
+ post = Post(
508
+ title=draft.get("title", ""),
509
+ subtitle=(
510
+ subtitle if subtitle is not None else (draft.get("subtitle") or "")
511
+ ),
512
+ user_id=self.get_user_id(),
513
+ audience=audience,
514
+ write_comment_permissions=write_comment_permissions,
515
+ )
516
+ post.from_markdown(markdown, api=self)
517
+
518
+ update_payload = {"draft_body": json.dumps(post.draft_body)}
519
+
520
+ if subtitle is not None:
521
+ update_payload["subtitle"] = subtitle
522
+ if audience is not None:
523
+ update_payload["audience"] = audience
524
+ if write_comment_permissions is not None:
525
+ update_payload["write_comment_permissions"] = write_comment_permissions
526
+ if search_engine_title is not None:
527
+ update_payload["search_engine_title"] = search_engine_title
528
+ if search_engine_description is not None:
529
+ update_payload["search_engine_description"] = search_engine_description
530
+ if slug is not None:
531
+ update_payload["slug"] = slug
532
+ if draft_section_id is not None:
533
+ update_payload["draft_section_id"] = draft_section_id
534
+
535
+ tags_result = None
536
+ updated_draft = draft
537
+
538
+ if not dry_run:
539
+ updated_draft = self.put_draft(draft_id, **update_payload)
540
+
541
+ tags_list = Api._normalize_tags(tags)
542
+ if tags_list:
543
+ tags_result = self.add_tags_to_post(draft_id, tags_list)
544
+
545
+ return {
546
+ "action": "update",
547
+ "draft_id": draft_id,
548
+ "dry_run": dry_run,
549
+ "changed": not dry_run,
550
+ "payload": update_payload,
551
+ "draft": updated_draft,
552
+ "tags": tags_result,
553
+ "unsupported_nodes": unsupported_nodes,
554
+ }
555
+
467
556
  def delete_draft(self, draft_id):
468
557
  """
469
558
 
substack/cli.py CHANGED
@@ -309,6 +309,53 @@ def _drafts_create(api, args):
309
309
  print(f"Created draft {draft.get('id')}: {title}")
310
310
 
311
311
 
312
+ def _drafts_update(api, args):
313
+ if not args.yes and (args.json_output or not sys.stdin.isatty()):
314
+ raise CLIUsageError("--yes is required in non-interactive or JSON mode")
315
+
316
+ markdown_file = Path(args.markdown_file)
317
+ if not markdown_file.exists():
318
+ raise CLIUsageError(f"File not found: {markdown_file}")
319
+
320
+ if not args.yes:
321
+ action = "update" if not args.dry_run else "dry-run update"
322
+ print(f"Ready to {action} draft {args.draft_id} from {markdown_file}")
323
+ print("Substack nodes that are not supported by Markdown export/import")
324
+ print("will cause the update to be refused to prevent data loss.")
325
+ print()
326
+ try:
327
+ response = input(f"Confirm {action}? [y/N]: ")
328
+ if response.lower() not in ["y", "yes"]:
329
+ print("Aborted.")
330
+ return
331
+ except EOFError as exc:
332
+ raise CLIUsageError(
333
+ f"Confirm {action} requires confirmation or --yes"
334
+ ) from exc
335
+
336
+ markdown = markdown_file.read_text(encoding="utf-8")
337
+
338
+ result = api.update_draft_from_markdown(
339
+ args.draft_id,
340
+ markdown,
341
+ subtitle=args.subtitle,
342
+ audience=args.audience,
343
+ write_comment_permissions=args.write_comment_permissions,
344
+ search_engine_title=args.search_engine_title,
345
+ search_engine_description=args.search_engine_description,
346
+ slug=args.slug,
347
+ draft_section_id=args.draft_section_id,
348
+ tags=args.tags,
349
+ dry_run=args.dry_run,
350
+ )
351
+
352
+ if args.json_output:
353
+ _print_json(result)
354
+ else:
355
+ status = "Dry-run updated" if args.dry_run else "Updated"
356
+ print(f"{status} draft {args.draft_id}")
357
+
358
+
312
359
  def _drafts_export(api, args):
313
360
  output_path = Path(args.output) if args.output else None
314
361
  if output_path is not None and output_path.exists() and not args.force:
@@ -447,6 +494,23 @@ def _build_parser():
447
494
  drafts_create.add_argument("--tag", action="append", dest="tags", metavar="TAG")
448
495
  drafts_create.set_defaults(handler=_drafts_create)
449
496
 
497
+ drafts_update = draft_commands.add_parser(
498
+ "update", help="Update a draft from a Markdown file."
499
+ )
500
+ drafts_update.add_argument("draft_id", type=int)
501
+ drafts_update.add_argument("markdown_file", metavar="MARKDOWN_FILE")
502
+ drafts_update.add_argument("--subtitle")
503
+ drafts_update.add_argument("--audience")
504
+ drafts_update.add_argument("--write-comment-permissions")
505
+ drafts_update.add_argument("--search-engine-title")
506
+ drafts_update.add_argument("--search-engine-description")
507
+ drafts_update.add_argument("--slug")
508
+ drafts_update.add_argument("--draft-section-id", type=int)
509
+ drafts_update.add_argument("--tag", action="append", dest="tags", metavar="TAG")
510
+ drafts_update.add_argument("--dry-run", action="store_true")
511
+ drafts_update.add_argument("--yes", action="store_true")
512
+ drafts_update.set_defaults(handler=_drafts_update)
513
+
450
514
  drafts_export = draft_commands.add_parser(
451
515
  "export", help="Export a draft to Markdown without modifying it."
452
516
  )
@@ -1,386 +1,386 @@
1
- from __future__ import annotations
2
-
3
- import os
4
- from typing import Any, Dict, List, Optional
5
-
6
- try:
7
- from dotenv import load_dotenv
8
- except ImportError:
9
- load_dotenv = None
10
-
11
- from mcp.server.fastmcp import FastMCP
12
-
13
- from substack.api import Api
14
- from substack.post import Post
15
-
16
- if load_dotenv is not None:
17
- load_dotenv()
18
-
19
-
20
- def get_api() -> Api:
21
- email = os.getenv("EMAIL")
22
- password = os.getenv("PASSWORD")
23
- cookies_path = os.getenv("COOKIES_PATH")
24
- cookies_string = os.getenv("COOKIES_STRING")
25
- publication_url = os.getenv("PUBLICATION_URL")
26
-
27
- if cookies_path or cookies_string:
28
- return Api(
29
- cookies_path=cookies_path,
30
- cookies_string=cookies_string,
31
- publication_url=publication_url,
32
- )
33
-
34
- if email and password:
35
- return Api(
36
- email=email,
37
- password=password,
38
- publication_url=publication_url,
39
- )
40
-
41
- raise ValueError(
42
- "Missing Substack auth configuration: set EMAIL/PASSWORD or COOKIES_PATH/COOKIES_STRING"
43
- )
44
-
45
-
46
- def _normalize_tags(tags: Optional[Any]) -> List[str]:
47
- if tags is None:
48
- return []
49
- if isinstance(tags, str):
50
- return [tags]
51
- if isinstance(tags, list):
52
- return [str(tag) for tag in tags]
53
- raise ValueError("tags must be a string or a list of strings")
54
-
55
-
56
- mcp = FastMCP("substack")
57
-
58
-
59
- @mcp.tool()
60
- async def post_draft_from_markdown(
61
- title: str,
62
- markdown: str,
63
- subtitle: Optional[str] = "",
64
- audience: str = "everyone",
65
- write_comment_permissions: str = "everyone",
66
- search_engine_title: Optional[str] = None,
67
- search_engine_description: Optional[str] = None,
68
- slug: Optional[str] = None,
69
- draft_section_id: Optional[int] = None,
70
- tags: Optional[Any] = None,
71
- prepublish: bool = False,
72
- publish: bool = False,
73
- send: bool = True,
74
- share_automatically: bool = False,
75
- ) -> Dict[str, Any]:
76
- """Create or update a Substack draft from Markdown.
77
-
78
- This tool builds a Substack `Post` from markdown content and posts a draft.
79
- It supports optional tag assignment, prepublish (setup check), and publishing.
80
-
81
- Args:
82
- title: Draft title.
83
- markdown: Markdown body content.
84
- subtitle: Optional subtitle text.
85
- audience: One of `everyone`, `only_paid`, `founding`, `only_free`.
86
- write_comment_permissions: One of `none`, `only_paid`, `everyone`.
87
- search_engine_title: Optional title for search engine optimization.
88
- search_engine_description: Optional description for search engine optimization.
89
- slug: Optional URL slug for the post.
90
- draft_section_id: Optional section ID for the draft.
91
- tags: Tag or list of tags to attach to the post.
92
- prepublish: If true, calls `prepublish_draft` after creation.
93
- publish: If true, calls `publish_draft` after creation (and optionally prepublish).
94
- send: Passed to `publish_draft` for newsletter delivery.
95
- share_automatically: Passed to `publish_draft`.
96
-
97
- Returns:
98
- dict containing drafted post (`draft`), optional `tags`, `prepublish`, `publish` results.
99
-
100
- Examples:
101
- With the YAML structure from the README, a caller can map fields like:
102
-
103
- ```yaml
104
- title: "My Post Title"
105
- subtitle: "My Post Subtitle"
106
- audience: "everyone"
107
- write_comment_permissions: "everyone"
108
- markdown: |
109
- # Hello
110
-
111
- This is the body.
112
-
113
- tags:
114
- - python
115
- - substack
116
- prepublish: true
117
- publish: true
118
- send: false
119
- share_automatically: true
120
- ```
121
-
122
- Then invoke via MCP directly:
123
-
124
- ```python
125
- from substack_mcp.mcp_server import post_draft_from_markdown
126
-
127
- result = await post_draft_from_markdown(
128
- title='My Post Title',
129
- markdown='# Hello\n\nThis is the body.',
130
- subtitle='My Post Subtitle',
131
- audience='everyone',
132
- write_comment_permissions='everyone',
133
- tags=['python', 'substack'],
134
- prepublish=True,
135
- publish=False, # set true when ready
136
- )
137
- print(result)
138
- ```
139
-
140
- A longer process with manual prepublish/publish calls:
141
-
142
- ```python
143
- from substack_mcp.mcp_server import (
144
- post_draft_from_markdown,
145
- prepublish_draft,
146
- publish_draft,
147
- add_tags,
148
- )
149
-
150
- d = await post_draft_from_markdown(
151
- title='Long flow',
152
- markdown='Content',
153
- tags=['a','b'],
154
- publish=False,
155
- )
156
- draft_id = d['draft']['id']
157
-
158
- await add_tags(draft_id, ['post-tag', 'news'])
159
- await prepublish_draft(draft_id)
160
- await publish_draft(draft_id, send=True, share_automatically=True)
161
- ```
162
-
163
- This docstring example is meant to mirror the YAML-driven workflow and show how to decompose the same operations into explicit tool calls.
164
- """
165
- client = get_api()
166
-
167
- return client.create_draft_from_markdown(
168
- title=title,
169
- markdown=markdown,
170
- subtitle=subtitle,
171
- audience=audience,
172
- write_comment_permissions=write_comment_permissions,
173
- search_engine_title=search_engine_title,
174
- search_engine_description=search_engine_description,
175
- slug=slug,
176
- draft_section_id=draft_section_id,
177
- tags=tags,
178
- prepublish=prepublish,
179
- publish=publish,
180
- send=send,
181
- share_automatically=share_automatically,
182
- )
183
-
184
-
185
- @mcp.tool()
186
- async def put_draft(
187
- draft_id: int,
188
- update_payload: Dict[str, Any],
189
- ) -> Dict[str, Any]:
190
- """Update an existing draft by draft ID.
191
-
192
- Args:
193
- draft_id: target draft identifier.
194
- update_payload: dict of fields supported by Substack `put_draft` (e.g. `slug`, `draft_section_id`).
195
-
196
- Returns:
197
- API response dict for the updated draft.
198
- """
199
- client = get_api()
200
- return client.put_draft(draft_id, **update_payload)
201
-
202
-
203
- @mcp.tool()
204
- async def add_tags(draft_id: int, tags: Any) -> Dict[str, Any]:
205
- """Add tags to a specific draft/post.
206
-
207
- Args:
208
- draft_id: target draft identifier.
209
- tags: string or list of tag names (e.g. `"tech"` or `["tech", "python"]`).
210
-
211
- Returns:
212
- Response from `add_tags_to_post` (tag IDs + names).
213
- """
214
- client = get_api()
215
- tags_list = _normalize_tags(tags)
216
- if not tags_list:
217
- raise ValueError("tags is required and cannot be empty")
218
- return client.add_tags_to_post(draft_id, tags_list)
219
-
220
-
221
- @mcp.tool()
222
- async def prepublish_draft(draft_id: int) -> Dict[str, Any]:
223
- """Invoke prepublish checks for a draft.
224
-
225
- Args:
226
- draft_id: target draft identifier.
227
-
228
- Returns:
229
- Prepublish response dict from Substack API.
230
- """
231
- client = get_api()
232
- return client.prepublish_draft(draft_id)
233
-
234
-
235
- @mcp.tool()
236
- async def publish_draft(
237
- draft_id: int,
238
- send: bool = True,
239
- share_automatically: bool = False,
240
- ) -> Dict[str, Any]:
241
- """Publish a draft to live post state. (Legacy compatibility interface).
242
-
243
- This tool remains for backward compatibility. It is recommended to use
244
- `publish_draft_checked` instead, which provides a safer publishing path
245
- with explicit confirmation and prepublish validation.
246
-
247
- Args:
248
- draft_id: target draft identifier.
249
- send: if False then do not send email to subscribers.
250
- share_automatically: whether to auto-share (e.g. social propagation).
251
-
252
- Returns:
253
- Response from Substack `publish_draft`.
254
- """
255
- client = get_api()
256
- return client.publish_draft(
257
- draft_id, send=send, share_automatically=share_automatically
258
- )
259
-
260
-
261
- @mcp.tool()
262
- async def publish_draft_checked(
263
- draft_id: int,
264
- confirm: bool = False,
265
- send: bool = False,
266
- share_automatically: bool = False,
267
- ) -> Dict[str, Any]:
268
- """A safer publishing path that requires confirmation and runs prepublish checks.
269
-
270
- Args:
271
- draft_id: target draft identifier.
272
- confirm: Must be True to proceed with publication.
273
- send: if False then do not send email to subscribers. Defaults to False.
274
- share_automatically: whether to auto-share.
275
-
276
- Returns:
277
- Response from Substack `publish_draft`.
278
- """
279
- if not confirm:
280
- raise ValueError("Publishing rejected: confirm parameter must be True.")
281
-
282
- client = get_api()
283
- client.prepublish_draft(draft_id)
284
- return client.publish_draft(
285
- draft_id, send=send, share_automatically=share_automatically
286
- )
287
-
288
-
289
- @mcp.tool()
290
- async def get_status() -> Dict[str, Any]:
291
- """Get the authentication status and basic user information.
292
-
293
- Returns:
294
- A dictionary containing user profile and primary publication details.
295
- """
296
- client = get_api()
297
- profile = client.get_user_profile()
298
- primary_pub = client.get_user_primary_publication()
299
- return {"profile": profile, "primary_publication": primary_pub}
300
-
301
-
302
- @mcp.tool()
303
- async def list_publications() -> List[Dict[str, Any]]:
304
- """List all publications available to the authenticated user.
305
-
306
- Returns:
307
- A list of publications.
308
- """
309
- client = get_api()
310
- return client.get_user_publications()
311
-
312
-
313
- @mcp.tool()
314
- async def list_drafts(
315
- filter: str = "draft", offset: int = 0, limit: int = 25
316
- ) -> List[Dict[str, Any]]:
317
- """List drafts for the current publication.
318
-
319
- Args:
320
- filter: Filter string, defaults to "draft".
321
- offset: Pagination offset.
322
- limit: Max number of drafts to return.
323
-
324
- Returns:
325
- A list of drafts.
326
- """
327
- client = get_api()
328
- return client.get_drafts(filter=filter, offset=offset, limit=limit)
329
-
330
-
331
- @mcp.tool()
332
- async def get_draft(draft_id: int) -> Dict[str, Any]:
333
- """Get a specific draft by its ID.
334
-
335
- Args:
336
- draft_id: The identifier of the draft.
337
-
338
- Returns:
339
- The draft details.
340
- """
341
- client = get_api()
342
- return client.get_draft(draft_id)
343
-
344
-
345
- @mcp.tool()
346
- async def schedule_draft(draft_id: int, at: str) -> Dict[str, Any]:
347
- """Schedule a draft for release.
348
-
349
- Args:
350
- draft_id: target draft identifier.
351
- at: ISO 8601 formatted datetime string (e.g., "2024-01-01T12:00:00Z").
352
-
353
- Returns:
354
- API response dict for the scheduled draft.
355
- """
356
- from datetime import datetime
357
-
358
- try:
359
- draft_datetime = datetime.fromisoformat(at.replace("Z", "+00:00"))
360
- except ValueError as e:
361
- raise ValueError(f"Invalid ISO datetime string for 'at': {e}")
362
-
363
- client = get_api()
364
- return client.schedule_draft(draft_id, draft_datetime)
365
-
366
-
367
- @mcp.tool()
368
- async def unschedule_draft(draft_id: int) -> Dict[str, Any]:
369
- """Unschedule a previously scheduled draft.
370
-
371
- Args:
372
- draft_id: target draft identifier.
373
-
374
- Returns:
375
- API response dict for unscheduling.
376
- """
377
- client = get_api()
378
- return client.unschedule_draft(draft_id)
379
-
380
-
381
- def main() -> None:
382
- mcp.run(transport="stdio")
383
-
384
-
385
- if __name__ == "__main__":
386
- main()
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ try:
7
+ from dotenv import load_dotenv
8
+ except ImportError:
9
+ load_dotenv = None
10
+
11
+ from fastmcp import FastMCP
12
+
13
+ from substack.api import Api
14
+ from substack.post import Post
15
+
16
+ if load_dotenv is not None:
17
+ load_dotenv()
18
+
19
+
20
+ def get_api() -> Api:
21
+ email = os.getenv("EMAIL")
22
+ password = os.getenv("PASSWORD")
23
+ cookies_path = os.getenv("COOKIES_PATH")
24
+ cookies_string = os.getenv("COOKIES_STRING")
25
+ publication_url = os.getenv("PUBLICATION_URL")
26
+
27
+ if cookies_path or cookies_string:
28
+ return Api(
29
+ cookies_path=cookies_path,
30
+ cookies_string=cookies_string,
31
+ publication_url=publication_url,
32
+ )
33
+
34
+ if email and password:
35
+ return Api(
36
+ email=email,
37
+ password=password,
38
+ publication_url=publication_url,
39
+ )
40
+
41
+ raise ValueError(
42
+ "Missing Substack auth configuration: set EMAIL/PASSWORD or COOKIES_PATH/COOKIES_STRING"
43
+ )
44
+
45
+
46
+ def _normalize_tags(tags: Optional[Any]) -> List[str]:
47
+ if tags is None:
48
+ return []
49
+ if isinstance(tags, str):
50
+ return [tags]
51
+ if isinstance(tags, list):
52
+ return [str(tag) for tag in tags]
53
+ raise ValueError("tags must be a string or a list of strings")
54
+
55
+
56
+ mcp = FastMCP("substack")
57
+
58
+
59
+ @mcp.tool()
60
+ async def post_draft_from_markdown(
61
+ title: str,
62
+ markdown: str,
63
+ subtitle: Optional[str] = "",
64
+ audience: str = "everyone",
65
+ write_comment_permissions: str = "everyone",
66
+ search_engine_title: Optional[str] = None,
67
+ search_engine_description: Optional[str] = None,
68
+ slug: Optional[str] = None,
69
+ draft_section_id: Optional[int] = None,
70
+ tags: Optional[Any] = None,
71
+ prepublish: bool = False,
72
+ publish: bool = False,
73
+ send: bool = True,
74
+ share_automatically: bool = False,
75
+ ) -> Dict[str, Any]:
76
+ """Create or update a Substack draft from Markdown.
77
+
78
+ This tool builds a Substack `Post` from markdown content and posts a draft.
79
+ It supports optional tag assignment, prepublish (setup check), and publishing.
80
+
81
+ Args:
82
+ title: Draft title.
83
+ markdown: Markdown body content.
84
+ subtitle: Optional subtitle text.
85
+ audience: One of `everyone`, `only_paid`, `founding`, `only_free`.
86
+ write_comment_permissions: One of `none`, `only_paid`, `everyone`.
87
+ search_engine_title: Optional title for search engine optimization.
88
+ search_engine_description: Optional description for search engine optimization.
89
+ slug: Optional URL slug for the post.
90
+ draft_section_id: Optional section ID for the draft.
91
+ tags: Tag or list of tags to attach to the post.
92
+ prepublish: If true, calls `prepublish_draft` after creation.
93
+ publish: If true, calls `publish_draft` after creation (and optionally prepublish).
94
+ send: Passed to `publish_draft` for newsletter delivery.
95
+ share_automatically: Passed to `publish_draft`.
96
+
97
+ Returns:
98
+ dict containing drafted post (`draft`), optional `tags`, `prepublish`, `publish` results.
99
+
100
+ Examples:
101
+ With the YAML structure from the README, a caller can map fields like:
102
+
103
+ ```yaml
104
+ title: "My Post Title"
105
+ subtitle: "My Post Subtitle"
106
+ audience: "everyone"
107
+ write_comment_permissions: "everyone"
108
+ markdown: |
109
+ # Hello
110
+
111
+ This is the body.
112
+
113
+ tags:
114
+ - python
115
+ - substack
116
+ prepublish: true
117
+ publish: true
118
+ send: false
119
+ share_automatically: true
120
+ ```
121
+
122
+ Then invoke via MCP directly:
123
+
124
+ ```python
125
+ from substack_mcp.mcp_server import post_draft_from_markdown
126
+
127
+ result = await post_draft_from_markdown(
128
+ title='My Post Title',
129
+ markdown='# Hello\n\nThis is the body.',
130
+ subtitle='My Post Subtitle',
131
+ audience='everyone',
132
+ write_comment_permissions='everyone',
133
+ tags=['python', 'substack'],
134
+ prepublish=True,
135
+ publish=False, # set true when ready
136
+ )
137
+ print(result)
138
+ ```
139
+
140
+ A longer process with manual prepublish/publish calls:
141
+
142
+ ```python
143
+ from substack_mcp.mcp_server import (
144
+ post_draft_from_markdown,
145
+ prepublish_draft,
146
+ publish_draft,
147
+ add_tags,
148
+ )
149
+
150
+ d = await post_draft_from_markdown(
151
+ title='Long flow',
152
+ markdown='Content',
153
+ tags=['a','b'],
154
+ publish=False,
155
+ )
156
+ draft_id = d['draft']['id']
157
+
158
+ await add_tags(draft_id, ['post-tag', 'news'])
159
+ await prepublish_draft(draft_id)
160
+ await publish_draft(draft_id, send=True, share_automatically=True)
161
+ ```
162
+
163
+ This docstring example is meant to mirror the YAML-driven workflow and show how to decompose the same operations into explicit tool calls.
164
+ """
165
+ client = get_api()
166
+
167
+ return client.create_draft_from_markdown(
168
+ title=title,
169
+ markdown=markdown,
170
+ subtitle=subtitle,
171
+ audience=audience,
172
+ write_comment_permissions=write_comment_permissions,
173
+ search_engine_title=search_engine_title,
174
+ search_engine_description=search_engine_description,
175
+ slug=slug,
176
+ draft_section_id=draft_section_id,
177
+ tags=tags,
178
+ prepublish=prepublish,
179
+ publish=publish,
180
+ send=send,
181
+ share_automatically=share_automatically,
182
+ )
183
+
184
+
185
+ @mcp.tool()
186
+ async def put_draft(
187
+ draft_id: int,
188
+ update_payload: Dict[str, Any],
189
+ ) -> Dict[str, Any]:
190
+ """Update an existing draft by draft ID.
191
+
192
+ Args:
193
+ draft_id: target draft identifier.
194
+ update_payload: dict of fields supported by Substack `put_draft` (e.g. `slug`, `draft_section_id`).
195
+
196
+ Returns:
197
+ API response dict for the updated draft.
198
+ """
199
+ client = get_api()
200
+ return client.put_draft(draft_id, **update_payload)
201
+
202
+
203
+ @mcp.tool()
204
+ async def add_tags(draft_id: int, tags: Any) -> Dict[str, Any]:
205
+ """Add tags to a specific draft/post.
206
+
207
+ Args:
208
+ draft_id: target draft identifier.
209
+ tags: string or list of tag names (e.g. `"tech"` or `["tech", "python"]`).
210
+
211
+ Returns:
212
+ Response from `add_tags_to_post` (tag IDs + names).
213
+ """
214
+ client = get_api()
215
+ tags_list = _normalize_tags(tags)
216
+ if not tags_list:
217
+ raise ValueError("tags is required and cannot be empty")
218
+ return client.add_tags_to_post(draft_id, tags_list)
219
+
220
+
221
+ @mcp.tool()
222
+ async def prepublish_draft(draft_id: int) -> Dict[str, Any]:
223
+ """Invoke prepublish checks for a draft.
224
+
225
+ Args:
226
+ draft_id: target draft identifier.
227
+
228
+ Returns:
229
+ Prepublish response dict from Substack API.
230
+ """
231
+ client = get_api()
232
+ return client.prepublish_draft(draft_id)
233
+
234
+
235
+ @mcp.tool()
236
+ async def publish_draft(
237
+ draft_id: int,
238
+ send: bool = True,
239
+ share_automatically: bool = False,
240
+ ) -> Dict[str, Any]:
241
+ """Publish a draft to live post state. (Legacy compatibility interface).
242
+
243
+ This tool remains for backward compatibility. It is recommended to use
244
+ `publish_draft_checked` instead, which provides a safer publishing path
245
+ with explicit confirmation and prepublish validation.
246
+
247
+ Args:
248
+ draft_id: target draft identifier.
249
+ send: if False then do not send email to subscribers.
250
+ share_automatically: whether to auto-share (e.g. social propagation).
251
+
252
+ Returns:
253
+ Response from Substack `publish_draft`.
254
+ """
255
+ client = get_api()
256
+ return client.publish_draft(
257
+ draft_id, send=send, share_automatically=share_automatically
258
+ )
259
+
260
+
261
+ @mcp.tool()
262
+ async def publish_draft_checked(
263
+ draft_id: int,
264
+ confirm: bool = False,
265
+ send: bool = False,
266
+ share_automatically: bool = False,
267
+ ) -> Dict[str, Any]:
268
+ """A safer publishing path that requires confirmation and runs prepublish checks.
269
+
270
+ Args:
271
+ draft_id: target draft identifier.
272
+ confirm: Must be True to proceed with publication.
273
+ send: if False then do not send email to subscribers. Defaults to False.
274
+ share_automatically: whether to auto-share.
275
+
276
+ Returns:
277
+ Response from Substack `publish_draft`.
278
+ """
279
+ if not confirm:
280
+ raise ValueError("Publishing rejected: confirm parameter must be True.")
281
+
282
+ client = get_api()
283
+ client.prepublish_draft(draft_id)
284
+ return client.publish_draft(
285
+ draft_id, send=send, share_automatically=share_automatically
286
+ )
287
+
288
+
289
+ @mcp.tool()
290
+ async def get_status() -> Dict[str, Any]:
291
+ """Get the authentication status and basic user information.
292
+
293
+ Returns:
294
+ A dictionary containing user profile and primary publication details.
295
+ """
296
+ client = get_api()
297
+ profile = client.get_user_profile()
298
+ primary_pub = client.get_user_primary_publication()
299
+ return {"profile": profile, "primary_publication": primary_pub}
300
+
301
+
302
+ @mcp.tool()
303
+ async def list_publications() -> List[Dict[str, Any]]:
304
+ """List all publications available to the authenticated user.
305
+
306
+ Returns:
307
+ A list of publications.
308
+ """
309
+ client = get_api()
310
+ return client.get_user_publications()
311
+
312
+
313
+ @mcp.tool()
314
+ async def list_drafts(
315
+ filter: str = "draft", offset: int = 0, limit: int = 25
316
+ ) -> List[Dict[str, Any]]:
317
+ """List drafts for the current publication.
318
+
319
+ Args:
320
+ filter: Filter string, defaults to "draft".
321
+ offset: Pagination offset.
322
+ limit: Max number of drafts to return.
323
+
324
+ Returns:
325
+ A list of drafts.
326
+ """
327
+ client = get_api()
328
+ return client.get_drafts(filter=filter, offset=offset, limit=limit)
329
+
330
+
331
+ @mcp.tool()
332
+ async def get_draft(draft_id: int) -> Dict[str, Any]:
333
+ """Get a specific draft by its ID.
334
+
335
+ Args:
336
+ draft_id: The identifier of the draft.
337
+
338
+ Returns:
339
+ The draft details.
340
+ """
341
+ client = get_api()
342
+ return client.get_draft(draft_id)
343
+
344
+
345
+ @mcp.tool()
346
+ async def schedule_draft(draft_id: int, at: str) -> Dict[str, Any]:
347
+ """Schedule a draft for release.
348
+
349
+ Args:
350
+ draft_id: target draft identifier.
351
+ at: ISO 8601 formatted datetime string (e.g., "2024-01-01T12:00:00Z").
352
+
353
+ Returns:
354
+ API response dict for the scheduled draft.
355
+ """
356
+ from datetime import datetime
357
+
358
+ try:
359
+ draft_datetime = datetime.fromisoformat(at.replace("Z", "+00:00"))
360
+ except ValueError as e:
361
+ raise ValueError(f"Invalid ISO datetime string for 'at': {e}")
362
+
363
+ client = get_api()
364
+ return client.schedule_draft(draft_id, draft_datetime)
365
+
366
+
367
+ @mcp.tool()
368
+ async def unschedule_draft(draft_id: int) -> Dict[str, Any]:
369
+ """Unschedule a previously scheduled draft.
370
+
371
+ Args:
372
+ draft_id: target draft identifier.
373
+
374
+ Returns:
375
+ API response dict for unscheduling.
376
+ """
377
+ client = get_api()
378
+ return client.unschedule_draft(draft_id)
379
+
380
+
381
+ def main() -> None:
382
+ mcp.run(transport="stdio")
383
+
384
+
385
+ if __name__ == "__main__":
386
+ main()
@@ -1,14 +0,0 @@
1
- substack/__init__.py,sha256=AOBZry1Ww9TjPAvZmD6jBifVD5vjDGYo9_6Pay1wNPY,449
2
- substack/api.py,sha256=9YYLi4410zSUiNd84ZNCHA-gSo08R4pS5JdpXFHUXiQ,26550
3
- substack/cli.py,sha256=-3HI99ewA6IFNluiKr_LMW4J-rAzxDzW6b1E3ar8cJU,23125
4
- substack/exceptions.py,sha256=Y61XSPyxDxXPbVlioFvKhb94MRY0tpD389F5YdL1rGM,1390
5
- substack/mdexport.py,sha256=_pSjioPJIA1wuJ6hYpvODZVswPSUROuzEndVoYnv-yU,13541
6
- substack/mdrender.py,sha256=QGJkdp1isFmhVyTRMogIabAK8OO2xQh9CrjnXZvFTY4,9308
7
- substack/nodes.py,sha256=fTsGO0-lTztcXiloIjXrHVnJes9EcltGcrX-mEV2ceQ,5004
8
- substack/post.py,sha256=qDXu-xzO3nRXtahc-yG2EhxKAXB2hG_Z1nLa55UMBGg,19697
9
- substack_mcp/mcp_server.py,sha256=3VTSSsiAmr4btImWpfoEl7irpTgqI-FH4q5r9r3u3w8,10949
10
- python_substack-0.6.0.dist-info/METADATA,sha256=krTBh9COgQai1eRfZbWNSriJt51OfEu3iDwEgnRrYPA,8689
11
- python_substack-0.6.0.dist-info/WHEEL,sha256=kJCRJT_g0adfAJzTx2GUMmS80rTJIVHRCfG0DQgLq3o,88
12
- python_substack-0.6.0.dist-info/entry_points.txt,sha256=MKPjaBUd-0PtvxsBviStsVq1c0h8JZ_qUoYEsBK1xJc,236
13
- python_substack-0.6.0.dist-info/licenses/LICENSE,sha256=L6jk148I5HhhVbfUvkO3EO7eAoU5zToLio4-ApkCkxg,1062
14
- python_substack-0.6.0.dist-info/RECORD,,