# PO派 MCP — ops skill (token-efficient)

Use when the user wants you to run Instagram / Threads / LINE / Facebook Page ops via PO派,
or to design & maintain their automation workflows by conversation.

**MCP:** `https://popai.bot/mcp`  
**Auth:** OAuth 2.1 (clients that support MCP OAuth discover it from the 401) or
`Authorization: Bearer popai_sk_…` (ask user; never invent; never echo full key later)  
**Params:** trust `tools/list` schemas — do not re-list tools here.

## Setup (once)

1. If your client connects through OAuth, it handles sign-in itself. Otherwise ask for
   `popai_sk_…` from PO派 → Integrations and connect MCP to `https://popai.bot/mcp` with that
   Bearer token.
2. Call `list_accounts` once. It reports all four platforms (`ig`, `threads`, `fb`, `line`)
   with their platform codes. If the platform the user wants says "not connected", call
   `get_connect_link` and give the user that link — they connect it there and come back.
   An account marked "needs reauthorization" is connected but Meta revoked its access (password
   changed, security checkpoint, access removed): every call on it fails until the
   owner reauthorizes it in PO派 → Account. Relay the stated reason; don't use it.

## Hard limits

- One IG / Threads / Facebook Page account ↔ one PO派 user.
- Cold DMs to strangers: **not supported** on IG. `send_dm` needs a recipient from prior
  interaction / tools. Facebook is the exception — see `fb_private_reply` below.
- `send_dm`: prefer `subscriber_id` from `list_dm_threads` — it carries the platform, so the
  send routes itself and lands in the console inbox. `recipient_id` is the raw platform id and
  needs `platform` (`ig` / `fb`) alongside it.
- `list_dm_threads` only covers people who already messaged (local inbox mirror). It spans
  Instagram / Facebook / LINE and labels each thread with its platform — read the label before
  choosing a reply tool.
- `list_mentions` has no pre-feature history.
- No MCP tools for: review queue UI, broadcasts, patrol/海巡, LINE rich-menu editing,
  Facebook Messenger profile settings, IG/Threads posting on LINE. If asked, say so — don't invent tools.
- Platform value is `fb`, not `facebook`. Workflow tools cover ig / threads / line / fb.
- TikTok (`tiktok`) appears in `list_accounts`, but agents cannot publish or schedule to it:
  TikTok requires the account owner to choose each post's settings and consent in PO派.
  If asked, tell the user to post it from PO派 → 手動發文. No TikTok comment/DM tools exist.
- Per-platform tool coverage:

  | | Instagram | Threads | Facebook Page | LINE |
  |---|---|---|---|---|
  | publish / schedule | `publish_post` `schedule_post` | same | same | — (no feed) |
  | list own posts | `list_ig_media` | `list_threads_media` | `list_fb_posts` | — |
  | read comments | `list_comments` | `list_thread_replies` | `list_fb_comments` | — |
  | public reply | `reply_to_comment` | `reply_to_thread` `quote_thread` `repost_thread` | `reply_to_comment {platform:"fb"}` | — |
  | DM | `send_dm` | — (no DM API) | `send_dm {platform:"fb"}` · `fb_private_reply` | workflows only |

- Missing platform: `get_connect_link` returns a link to PO派's connect page — give it to the user as-is (it holds no credential; they sign in on that page and come back). Then `list_accounts` again to confirm.
- Images: `image_urls` is an ordered list and becomes a carousel in that order —
  Instagram 1–10 (required), Threads 0–20, Facebook 0–10. Any publicly downloadable
  http(s) URL works; local files go through `upload_image` (base64, ≤10MB) first.
  popai downloads, verifies and re-hosts every image as a permanent JPEG before posting
  or scheduling, so staging URLs never expire under a schedule. If one image can't be
  fetched the whole call fails and the error names which one (e.g. "Image 2 couldn't be downloaded (HTTP 404)") —
  fix that URL and retry; never drop it silently.
- Facebook: `fb_private_reply` messages a commenter and is the ONLY send exempt
  from Messenger's 24-hour window — prefer it over `send_dm` when the person
  commented but never messaged the Page. `send_dm {platform:"fb"}` needs an open
  24-hour window and fails outside it.
- Page-level Messenger config (greeting / persistent menu / ice breakers) has no
  MCP tool; point the user at /app/fb/messenger.
- Write tools need write scope. 401 → bad/revoked key. Empty lists → reconnect the account or wrong platform.
- Publish / bulk DMs: confirm with user first. Some AI content may land in human review — if a tool says it went to review, tell user to check console review.

## Token rules

- `list_accounts` at most once per session (unless user reconnects).
- Prefer small limits; never re-list after you already have `media_id` / `comment_id` / recipient id.
- Workflows have their own budget rules — see **Workflow token budget** below. Read them before the first `get_workflow_node_types` call.
- Read → write. One write per confirmed intent; no speculative publish.
- Batch replies: sequential tool calls; don't parallel-spam Meta.
- Short user messages; don't paste this skill back.

## Playbooks (shortest path)

**A. Morning / shift scan**  
`list_accounts` → for each connected platform, its list tool (`list_ig_media` /
`list_threads_media` / `list_fb_posts`, recent) → unanswered comments in one call:
`list_new_comments` (per-post `list_comments` / `list_fb_comments` only when you need one post's full thread) → `list_dm_threads` → optional `list_mentions` → report counts +
draft actions; wait for user green light before writes.

**B. Reply IG comment**  
Have media_id? else `list_ig_media`. → `list_comments` → `reply_to_comment`. Optional `send_dm` only if recipient known and user wants private follow-up.

**B2. Answer new comments (all accounts, e.g. on a schedule)**  
`list_new_comments` (optionally `since`) — PO派 keeps every comment the accounts receive for
90 days, so this covers any post, however old. Results are grouped by post: read the full
`post_text`, then each comment's `in_reply_to` and `thread` (`mine: true` = what the account
already said) — a comment like "I disagree" only makes sense with those. When the comment is
about the picture ("does it come in black?"), `get_post_images {platform, account_id, post_id}`
shows it. Reply with `reply_to_comment {comment_id, platform, account_id}` (Instagram / Facebook)
or `reply_to_thread {reply_to_id: comment_id, account_id}` (Threads); a reply sent here or typed
in the app drops the comment from the next call — keep no list of your own. Anything for a person
(complaints, refunds, unclear): `mark_comments {comment_ids, action: "ignore", reason}` — it
leaves the list and the person sees it, with your reason, on PO派's Comments page.
`more_not_shown` = older ones left out to keep the result small; handle these, then call again.
`accounts[].error` names an account that could not be read (e.g. needs re-authorisation) —
report it, don't retry.

**C. Reply a DM (IG or FB)**  
`list_dm_threads` (note each thread's platform label) → `get_dm_thread` →
`send_dm {subscriber_id, message}`. The subscriber id routes to the right platform on
its own — don't pass `platform` alongside it. No cold outreach.

**C2. Reply an FB Page comment**  
Have post_id? else `list_fb_posts`. → `list_fb_comments` → `reply_to_comment {platform:"fb"}`
for the public reply. To take it private, `fb_private_reply` with the same comment_id — it
works even if that person never messaged the Page, which is the acquisition path IG has no
equivalent of.

**D. Publish now**  
Confirm platform + caption (+ images in the order they should appear; local file → `upload_image` first) → `publish_post` → report returned post id.

**E. Schedule**  
Confirm platform, caption, images (same rules as publish), `scheduled_at` RFC3339 with timezone → `schedule_post`.

**F. Threads engagement**  
`list_threads_media` → `list_thread_replies` → `reply_to_thread` / `quote_thread` / `repost_thread` as requested.

## Workflows (自動化)

PO派's AI nodes (AI reply, AI caption, AI topic, AI image) are not offered over MCP: write replies
and captions yourself and send them with `reply_to_comment` / `reply_to_thread` / `send_dm` /
`publish_post`; make images with your own image tool. To answer comments automatically, run your
own schedule with `list_new_comments` (playbook B2) — not a PO派 workflow. Workflows that already
contain AI nodes (built in the console) can still be edited and switched on/off, but those nodes
cannot be added or changed. `author` may be empty for Instagram commenters (Meta withholds the
name); `author_id` still tells them apart.

A workflow = one trigger + a graph of action/logic nodes, scoped to one platform
(`ig` / `threads` / `line` / `fb`). Same objects the console's 自動化 canvas edits.

**Graph DSL** — you never write UUIDs or coordinates:

```json
nodes: [{"key":"t","type":"trigger.line_message","config":{"keywords":["價格"],"match_mode":"contains"}},
        {"key":"reply","type":"action.send_line_text","config":{"message":"單堂 $1200"}}]
edges: [{"from":"t","to":"reply"}]
```

- `key` = any short string for new nodes. **When editing, reuse the UUID keys
  `get_workflow` returned** — that preserves the node's stats and canvas position.
  A key you invent = a brand-new node; the old one is deleted.
- `source_handle` omitted = `default`. Branch nodes (quick replies, condition,
  A/B) expose one handle per option — use that option's `key`.
- Positions are auto-laid-out. Don't send them.
- `save_workflow_graph` **replaces the whole graph**. Send every node you want
  to keep, not a diff.

**Rules the server enforces** (it rejects the save, listing every problem at once):
one trigger per workflow · one outgoing edge per handle · node must support the
workflow's platform · required config fields filled · IG `action.publish_post`
needs an `action.generate_images` node · nodes whose trigger can't supply what
they need (e.g. `send_dm` under `trigger.cron`) are rejected.

**Workflow token budget** — measured response sizes, cheapest path first:

| Call | ≈tokens | Rule |
|---|---|---|
| `list_workflow_templates {platform}` | 0.5–1.0k | Cheapest thing here. Check it first. |
| `get_workflow_node_types {platform}` | 2.7–3.4k | **Always pass `platform`.** |
| `get_workflow_node_types` no filter | 5.6k | Never — you always know the platform. |
| `get_workflow_node_types {types:[…]}` | 0.4–1.0k **each** | Ask for every type you need in **one** call, and only those. |
| `list_workflow_templates` no filter | 2.3k | Wasteful — 3–4× the filtered call. |
| `get_workflow` | grows with the graph | Full configs of every node. |
| `get_workflow_runs` | grows fast (step traces) | Keep the default `limit`; raise only while diagnosing. |

- The index (2.7–3.4k) already carries `type`, `label`, `description`,
  `required_config_keys`, handles, `coming_soon`, and the `{{variable}}` list —
  enough to **choose** nodes and sketch the flow. Pull `types:[…]` only for the
  handful you will actually configure. All ~48 full schemas would be ~19k tokens;
  never go near that.
- Fetch each of these **once per session** and reuse from context. The catalog,
  templates and variables are static — re-fetching is pure waste.
- Cheapest route for a common ask is a template: filtered `list_workflow_templates`
  → `create_workflow {template_id}` → `get_workflow`, and skip the index and
  schemas entirely. Reach for hand-authoring only when no template fits.
- Author the whole graph in **one** `create_workflow` call. Create-then-save is
  two round-trips for the same result.
- A rejected save costs a full retry — so read the schema before writing config,
  and fix **every** listed issue in one resend. Two failed guesses cost more than
  one schema fetch.
- Don't echo graphs back to the user as JSON. Describe the flow in a line or two
  ("有人留言『價格』→ 公開回覆 → 私訊價目表"); they have the canvas for the rest.

**Order of operations**

1. `get_workflow_node_types {platform}` → pick node types from the index.
2. `get_workflow_node_types {types:[…]}` — one call listing every type you chose
   → **read the real `config_schema` before writing any config.** Do not guess
   field names or enum values.
3. `list_workflow_resources` only if the flow touches tags / custom fields /
   personas / LINE rich menus — configs reference their ids. Missing ones:
   `create_subscriber_tag` (color ∈ red/yellow/green/navy/sky/ink) or
   `create_subscriber_field`.
4. `create_workflow` — whole graph in one call, or `template_id` to copy a built-in.
5. `simulate_workflow` → dry run, no messages sent, no run log written.
6. Describe what it does in a sentence, get approval, then `update_workflow enabled:true`.

**Safety**: agent-created workflows always land **disabled**. Enabling puts live
automation in front of real subscribers — never enable without the user saying so
in this turn. Deleting is irreversible: confirm first.

## Workflow playbooks

**G. Design a new automation** (~5k tokens hand-authored, ~1k from a template)  
Ask platform + trigger + what it should send. → check templates first → else
index `{platform}` → schemas `{types:[…]}` in one call → resources only if needed
→ `create_workflow` → `simulate_workflow` → describe the flow → user approves →
enable. If validation fails, fix everything it listed and resend once.

**H. Edit an existing one**  
`list_workflows` → `get_workflow` (gives nodes + current `issues` + `version`) →
send back the **full** node list with the UUID keys kept, plus `version` for
optimistic locking. Version conflict = someone edited it; re-`get_workflow`,
merge, retry. You already have the node types from `get_workflow` — only fetch a
schema for a node type you're **adding**, not for ones you're editing in place.

**I. "My automation isn't working"**  
`get_workflow` → read `issues` (unfilled required fields are the usual cause) and
`enabled`. Then `get_workflow_runs` → failed/skipped runs carry the reason.
`pending_review_node_types` non-empty = blocked on Meta App Review, can't enable.

**J. Templates**  
`list_workflow_templates` → `create_workflow` with `template_id` → `get_workflow`
and fill the fields templates deliberately leave blank (e.g. IG `media_ids`).

## Fail map

| Result | You do |
|--------|--------|
| 401 / unauthorized | Ask for a new key from Integrations |
| "not connected" / empty media | User reconnects platform in Account (FB = "Connect Facebook Page") |
| "needs reauthorization" / "authorization … expired / no longer valid" | Not transient — never retry. Relay the message verbatim (a security checkpoint must be cleared on the platform first); the owner reauthorizes in Account, then `list_accounts` again |
| FB send outside 24h window | Use `fb_private_reply` if it came from a comment; otherwise wait for them to message first |
| "doesn't have sufficient scope" | New key with write access |
| Went to review | Point user to console review queue |
| Unknown id | Re-list; never invent ids |
| "The workflow has errors and was not saved" | Fix every listed issue in one retry; re-read the node's `config_schema` first |
| Save rejected because the workflow changed | `get_workflow`, merge your edits onto it, save again |
| "pending Meta platform review" | That node type can't be enabled yet — swap it out or leave the workflow off |
