Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Social Publisher v0.1.2 · generic

Archive SHA-256 c9dd6f5e6e9c4f59523536b81d78efcc1a79eeba97feaa1027e027d5be03e6c5 · 49.6 KB · built Nov 27, 2026

tests/social-publisher.test.ts

import { describe, it, expect, vi } from "vitest";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import agentModule, { handleMcpMessage, makeContext, manifest, validateManifest } from "../src/index.js";

const agent: any = agentModule;
const now = () => new Date("2026-11-25T12:00:00Z");
const BRIEF = "We just shipped offline mode for Oakline Notes. Your notes now sync when you reconnect.\n\nNo account needed, and your data stays on your device.";

type FetchCall = { url: string; init: any };
function fakeFetch(responses: Array<() => Response>) {
  const calls: FetchCall[] = [];
  const fetch = async (url: string, init: any) => {
    calls.push({ url: String(url), init });
    const next = responses.shift();
    if (!next) throw new Error(`unexpected request to ${url}`);
    return next();
  };
  return { fetch, calls };
}
const json = (body: unknown, status = 200, headers: Record<string, string> = {}) => () => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });

const approvedX = { platform: "x", account: "@oakline", text: "Offline mode is here. https://oakline.example/notes", approved: true };

describe("social-publisher: manifest and permissions", () => {
  it("passes validateManifest and declares least privilege", () => {
    expect(validateManifest(manifest)).toEqual([]);
    expect(manifest.id).toBe("agentrove.social-publisher");
    expect(manifest.permissions.network).toEqual(["api.x.com", "api.linkedin.com", "graph.facebook.com", "www.googleapis.com"]);
    expect(manifest.permissions.filesystem).toBe("none");
    const writes = manifest.tools.filter((t: any) => t.side_effects !== "none");
    expect(writes.map((t: any) => t.name)).toEqual(["publish"]);
    expect(writes[0]).toMatchObject({ side_effects: "external_write", requires_confirmation: true });
    const names = manifest.tools.map((t: any) => t.name).join(" ");
    expect(names).not.toMatch(/follow|like|comment|account|dm/);
  });

  it("denies hosts outside the official API allowlist and plain http", async () => {
    const fetch = vi.fn();
    const ctx = makeContext(manifest, { fetch });
    await expect(ctx.fetch("https://evil.example/collect")).rejects.toMatchObject({ code: "network_denied" });
    await expect(ctx.fetch("http://api.x.com/2/tweets")).rejects.toMatchObject({ code: "network_denied" });
    await expect(ctx.fetch("https://api.twitter.com.evil.example/2/tweets")).rejects.toMatchObject({ code: "network_denied" });
    expect(fetch).not.toHaveBeenCalled();
  });
});

describe("social-publisher: draft_posts", () => {
  it("drafts one variant per platform with UTM-tagged links and hashtags (happy path)", async () => {
    const out = await agent.call(
      "draft_posts",
      { brief: BRIEF, link: "https://oakline.example/notes?ref=a#top", utm: { campaign: "Launch Week" }, hashtags: ["#Productivity", "notes app", "2026", "productivity"], cta: "Try it free." },
      { now },
    );
    expect(out.posts.map((p: any) => p.platform)).toEqual(["x", "linkedin", "instagram", "tiktok", "youtube", "facebook"]);
    const by = Object.fromEntries(out.posts.map((p: any) => [p.platform, p]));
    const x = new URL(by.x.link);
    expect(x.searchParams.get("utm_source")).toBe("x");
    expect(x.searchParams.get("utm_medium")).toBe("social");
    expect(x.searchParams.get("utm_campaign")).toBe("launch_week");
    expect(x.searchParams.get("ref")).toBe("a");
    expect(x.hash).toBe("#top");
    expect(new URL(by.linkedin.link).searchParams.get("utm_source")).toBe("linkedin");
    expect(by.x.text).toContain(by.x.link);
    expect(by.x.hashtags).toEqual(["Productivity", "notesapp"]);
    expect(by.x.text.endsWith("#Productivity #notesapp")).toBe(true);
    // Links are not clickable in Instagram/TikTok captions: kept out of the text, returned separately.
    expect(by.instagram.link_in_text).toBe(false);
    expect(by.instagram.text).not.toContain("https://");
    expect(by.tiktok.notes.join(" ")).toMatch(/not clickable/);
    expect(by.youtube.title).toBe("We just shipped offline mode for Oakline Notes.");
    expect(by.youtube.length_method).toBe("utf8_bytes");
    expect(out.posts.every((p: any) => p.within_limit && !p.truncated)).toBe(true);
    expect(out.warnings.join(" ")).toMatch(/notesapp/);
    expect(out.warnings.join(" ")).toMatch(/Ignored hashtag "2026"/);
    expect(out.generated_at).toBe("2026-11-25T12:00:00Z");
    // "Try it free." does not refer to a link, so no CTA warning.
    expect(out.warnings.join(" ")).not.toMatch(/call to action mentions a link/);
  });

  it("warns when the call to action points at a link that Instagram/TikTok captions do not carry", async () => {
    const out = await agent.call("draft_posts", { brief: BRIEF, link: "https://oakline.example/notes", cta: "Download it from the link below." }, { now });
    expect(out.warnings.join(" ")).toMatch(/call to action mentions a link, but instagram and tiktok captions do not include it/);
    const xOnly = await agent.call("draft_posts", { brief: BRIEF, platforms: ["x"], link: "https://oakline.example/notes", cta: "Link below." }, { now });
    expect(xOnly.warnings.join(" ")).not.toMatch(/call to action mentions a link/);
  });

  it("counts X length with twitter-text weighting (URL = 23, CJK = 2) and truncates at a word boundary", async () => {
    const long = "Offline sync explained. ".repeat(20).trim();
    const out = await agent.call("draft_posts", { brief: long, platforms: ["x"], link: "https://oakline.example/" + "a".repeat(200), hashtags: ["sync", "offline", "notes"] });
    const p = out.posts[0];
    expect(p.limit).toBe(280);
    expect(p.length).toBeLessThanOrEqual(280);
    expect(p.truncated).toBe(true);
    // The cut lands on a complete sentence, so no ellipsis is needed.
    expect(p.text.split("\n\n")[0]).toMatch(/explained\.$/);
    expect(p.text).not.toMatch(/\u2026/);
    expect(p.text).toContain("https://oakline.example/aaaa"); // the long URL is kept whole and weighs 23
    expect(p.hashtags.length).toBeLessThanOrEqual(2);
    // With no sentence end in reach, the body is cut at a word boundary and ends with an ellipsis.
    const run = await agent.call("draft_posts", { brief: "offline sync keeps working ".repeat(20).trim(), platforms: ["x"] });
    expect(run.posts[0].text).toMatch(/working\u2026$|sync\u2026$|keeps\u2026$|offline\u2026$/);
    expect(run.posts[0].length).toBeLessThanOrEqual(280);
    // A sentence end that would keep less than half of the room is not used.
    const early = await agent.call("draft_posts", { brief: `Short intro. ${"then a very long sentence without any stop ".repeat(10).trim()}`, platforms: ["x"] });
    expect(early.posts[0].text).toMatch(/\u2026$/);
    expect(early.posts[0].text.length).toBeGreaterThan(200);
    const cjk = await agent.call("draft_posts", { brief: "\u65e5\u672c\u8a9e\u306e\u30c6\u30b9\u30c8", platforms: ["x"] });
    expect(cjk.posts[0].length).toBe(14);
    expect(cjk.posts[0].notes.join(" ")).toMatch(/CJK/);
  });

  it("respects LinkedIn 3000, Facebook 5000 and YouTube title 100 / no angle brackets", async () => {
    const huge = Array.from({ length: 520 }, (_, i) => `Sentence ${i} about offline notes.`).join(" ");
    const out = await agent.call("draft_posts", { brief: huge, title: "<b>" + "Offline mode deep dive ".repeat(8) + "</b>", platforms: ["linkedin", "facebook", "youtube", "instagram"] });
    const by = Object.fromEntries(out.posts.map((p: any) => [p.platform, p]));
    expect([...by.linkedin.text].length).toBeLessThanOrEqual(3000);
    expect([...by.facebook.text].length).toBeLessThanOrEqual(5000);
    expect([...by.instagram.text].length).toBeLessThanOrEqual(2200);
    expect(Buffer.byteLength(by.youtube.text, "utf8")).toBeLessThanOrEqual(5000);
    expect(by.youtube.title.length).toBeLessThanOrEqual(100);
    expect(by.youtube.title).not.toMatch(/[<>]/);
    expect(by.youtube.notes.join(" ")).toMatch(/Title shortened/);
    expect(out.posts.every((p: any) => p.within_limit && p.truncated)).toBe(true);
  });

  it("uses script segments as paragraphs and the script title", async () => {
    const script = { title: "Offline mode in 30 seconds", segments: [{ text: "Lost signal?", kind: "hook" }, { text: "Notes still save.", kind: "body" }, { text: "Try it today.", kind: "cta" }] };
    const out = await agent.call("draft_posts", { script, platforms: ["linkedin", "youtube"], accounts: { linkedin: "urn:li:person:abc123" } });
    expect(out.posts[0].text).toBe("Lost signal?\n\nNotes still save.\n\nTry it today.");
    expect(out.posts[0].account).toBe("urn:li:person:abc123");
    expect(out.posts[1].title).toBe("Offline mode in 30 seconds");
  });

  it("builds a self-contained X post from whole, best-supported points when the script is too long, without promising cut content", async () => {
    const script = {
      title: "Heat pump rebates for renters",
      segments: [
        { kind: "hook", text: "What do the sources say about Heat pump rebates for renters? Here are 5 points." },
        { kind: "body", text: "According to example.com: Heat pump rebates now cover renters in the fixture city." },
        { kind: "body", text: "According to example.com and energy.example.org: Landlords must approve installation before the rebate is paid, and the rebate covers up to 40 percent of the installed cost." },
        { kind: "body", text: "According to news.example.net: Applications open in March and close when the yearly budget is spent, so early applicants are more likely to be funded." },
        { kind: "body", text: "According to example.com: Portable heat pumps do not qualify." },
        { kind: "body", text: "According to energy.example.org: Income-tested top-ups are available for households below the threshold." },
        { kind: "cta", text: "Check the linked sources before you share this." },
      ],
      claims: [
        { text: "Heat pump rebates now cover renters in the fixture city.", source_url: "https://example.com/rebates", sources: ["https://example.com/rebates"] },
        { text: "Landlords must approve installation before the rebate is paid, and the rebate covers up to 40 percent of the installed cost.", source_url: "https://example.com/landlords", sources: ["https://example.com/landlords", "https://energy.example.org/guide"] },
      ],
    };
    const out = await agent.call("draft_posts", { script, platforms: ["x", "linkedin"] });
    const [x, li] = out.posts;
    expect(x).toMatchObject({ truncated: false, within_limit: true });
    expect(x.text).not.toMatch(/Here are|5 points|What do the sources say|…/);
    // Leads with the point backed by two sources, keeps its attribution, and links its source.
    expect(x.text.startsWith("According to example.com and energy.example.org: Landlords must approve")).toBe(true);
    expect(x.text).toContain("https://example.com/landlords");
    expect(x.notes.join(" ")).toMatch(/uses \d of 5 point\(s\) \(best supported first\).*leaves out the introduction/);
    // Every sentence in the X post is a whole sentence from the script.
    for (const sentence of x.text.split("\n\n")[0].split(/(?<=\.)\s+/)) expect(script.segments.some((s) => s.text.includes(sentence)), sentence).toBe(true);
    // Platforms with room keep the full script, hook included.
    expect(li.text.startsWith("What do the sources say")).toBe(true);
    expect(li.truncated).toBe(false);
    // A given link wins over the source link.
    const linked = await agent.call("draft_posts", { script, platforms: ["x"], link: "https://oakline.example/rebates" });
    expect(linked.posts[0].text).toContain("https://oakline.example/rebates");
    expect(linked.posts[0].text).not.toContain("https://example.com/landlords");
  });

  it("drops announcing sentences from long briefs and keeps whole paragraphs in the author's order", async () => {
    const brief = [
      "Here are three tips for keeping notes offline.",
      "Turn on offline mode before you travel so every notebook is stored on the device.",
      "Conflicts are merged line by line when you reconnect, so edits made on two devices are both kept.",
      "Export a backup each month to a folder you control, because local storage can fail too.",
    ].join("\n\n");
    const out = await agent.call("draft_posts", { brief, platforms: ["x"] });
    const p = out.posts[0];
    expect(p).toMatchObject({ truncated: false, within_limit: true });
    expect(p.text).not.toMatch(/Here are|three tips/);
    expect(p.text.startsWith("Turn on offline mode before you travel")).toBe(true);
    expect(p.text).toContain("Conflicts are merged line by line");
    // A single over-long paragraph still falls back to shortening (and never keeps the announcement).
    const one = await agent.call("draft_posts", { brief: `Here are 5 points. ${"Offline sync keeps every note safe while you travel. ".repeat(8).trim()}`, platforms: ["x"] });
    expect(one.posts[0].truncated).toBe(true);
    expect(one.posts[0].text).not.toMatch(/Here are 5 points/);
  });

  it("rejects invalid input", async () => {
    await expect(agent.call("draft_posts", {})).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("draft_posts", { brief: "a", script: { segments: [{ text: "b" }] } })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("draft_posts", { brief: "a", link: "javascript:alert(1)" })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("draft_posts", { brief: "a", link: "https://user:pw@example.com/" })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("draft_posts", { brief: "a", platforms: ["myspace"] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("draft_posts", { brief: "\u0000\u0001  " })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("social-publisher: schedule_queue", () => {
  const base = { timezone: "America/New_York", slots: { start_date: "2026-12-01", times: ["09:00", "17:30"] } };

  it("dedupes by content hash per account and refuses identical X posts across accounts", async () => {
    const posts = [
      { platform: "x", account: "@oak", text: "Hello world" },
      { platform: "x", account: "@OAK", text: "Hello   world" },
      { platform: "x", account: "@oak2", text: "Hello world" },
      { platform: "linkedin", account: "urn:li:person:a", text: "Hello world" },
      { platform: "linkedin", account: "urn:li:person:b", text: "Hello world" },
      { platform: "x", account: "@oak", text: "Second post" },
    ];
    const out = await agent.call("schedule_queue", { ...base, posts }, { now });
    expect(out.added).toBe(4);
    expect(out.skipped.map((s: any) => s.index)).toEqual([1, 2]);
    expect(out.skipped[0].duplicate_of).toBe(out.queue.items.find((i: any) => i.text === "Hello world" && i.platform === "x").id);
    expect(out.skipped[1].reason).toMatch(/another X account/);
    expect(out.warnings.join(" ")).toMatch(/more than one account/);
    // The same visible X text for another account is refused even when only one copy carries link metadata
    // or the casing differs (found in a CLI scenario: a draft with `link` plus a hand-written copy without it).
    const withLink = await agent.call("schedule_queue", { ...base, posts: [
      { platform: "x", account: "@oak", text: "Big news https://oakline.example/a", link: "https://oakline.example/a" },
      { platform: "x", account: "@oak_team", text: "big NEWS   https://oakline.example/a" },
    ] }, { now });
    expect(withLink.added).toBe(1);
    expect(withLink.skipped[0]).toMatchObject({ index: 1 });
    expect(withLink.skipped[0].reason).toMatch(/another X account/);
    expect(out.queue.items.every((i: any) => i.status === "pending_approval" && i.approved === false)).toBe(true);
    expect(out.queue.format).toBe("agentrove.social-queue/1");
    const x = out.queue.items.filter((i: any) => i.platform === "x");
    expect(x.map((i: any) => i.publish_at_local)).toEqual(["2026-12-01T09:00-05:00", "2026-12-01T17:30-05:00"]);
    expect(x[0].idempotency_key).toMatch(/^[a-f0-9]{32}$/);
  });

  it("schedules local times correctly across the US DST change and caps posts per day", async () => {
    const posts = Array.from({ length: 4 }, (_, i) => ({ platform: "facebook", account: "123", text: `Post ${i}` }));
    const out = await agent.call(
      "schedule_queue",
      { timezone: "America/New_York", posts, slots: { start_date: "2027-03-13", times: ["09:00"] }, max_per_account_per_day: 1 },
      { now },
    );
    // 09:00 EST = 14:00Z on Mar 13; after the Mar 14 change 09:00 EDT = 13:00Z.
    expect(out.queue.items.map((i: any) => i.publish_at)).toEqual(["2027-03-13T14:00:00Z", "2027-03-14T13:00:00Z", "2027-03-15T13:00:00Z", "2027-03-16T13:00:00Z"]);
  });

  it("dedupes against an existing queue file and keeps its items", async () => {
    const first = await agent.call("schedule_queue", { ...base, posts: [{ platform: "x", account: "@oak", text: "Launch day" }] }, { now });
    const second = await agent.call(
      "schedule_queue",
      { ...base, posts: [{ platform: "x", account: "@oak", text: "Launch  day" }, { platform: "x", account: "@oak", text: "Day two" }], existing_queue: first.queue },
      { now },
    );
    expect(second.added).toBe(1);
    expect(second.skipped[0].duplicate_of).toBe(first.queue.items[0].id);
    expect(second.queue.items).toHaveLength(2);
    // The new post avoids the existing item's slot.
    expect(second.queue.items[1].publish_at).not.toBe(first.queue.items[0].publish_at);
  });

  it("honours explicit times, skips past or over-limit posts, and validates input", async () => {
    const out = await agent.call(
      "schedule_queue",
      {
        timezone: "Europe/London",
        posts: [
          { platform: "x", account: "@oak", text: "Explicit", publish_at: "2026-12-02T10:15" },
          { platform: "x", account: "@oak", text: "Past", publish_at: "2026-01-01T10:00:00Z" },
          { platform: "x", account: "@oak", text: "x".repeat(300) },
          { platform: "youtube", account: "chan", text: "No title" },
        ],
      },
      { now },
    );
    expect(out.queue.items).toHaveLength(1);
    expect(out.queue.items[0].publish_at).toBe("2026-12-02T10:15:00Z");
    expect(out.skipped.map((s: any) => s.index)).toEqual([1, 2, 3]);
    expect(out.skipped[0].reason).toMatch(/in the past/);
    expect(out.skipped[1].reason).toMatch(/allows 280/);
    await expect(agent.call("schedule_queue", { timezone: "Mars/Base", posts: [{ platform: "x", account: "a", text: "b" }] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("schedule_queue", { timezone: "UTC", posts: [{ platform: "x", account: "a", text: "b" }] }, { now })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("social-publisher: publish (external_write, fake fetch only)", () => {
  const env = { X_USER_ACCESS_TOKEN: "test-x-token", LINKEDIN_ACCESS_TOKEN: "test-li-token", FACEBOOK_PAGE_ACCESS_TOKEN: "test-fb-token", YOUTUBE_ACCESS_TOKEN: "test-yt-token" };

  it("requires confirmation and never touches the network without it", async () => {
    const fetch = vi.fn();
    await expect(agent.call("publish", { item: approvedX }, { fetch, env, now })).rejects.toMatchObject({ code: "confirmation_required" });
    await expect(agent.call("publish", { item: approvedX, confirm: false }, { fetch, env, now })).rejects.toMatchObject({ code: "confirmation_required" });
    expect(fetch).not.toHaveBeenCalled();
  });

  it("requires owner approval, the credential, a due time and a supported platform", async () => {
    const fetch = vi.fn();
    await expect(agent.call("publish", { item: { ...approvedX, approved: false }, confirm: true }, { fetch, env, now })).rejects.toMatchObject({ code: "not_approved" });
    await expect(agent.call("publish", { item: approvedX, confirm: true }, { fetch, env: {}, now })).rejects.toMatchObject({ code: "missing_credential" });
    await expect(agent.call("publish", { item: { ...approvedX, publish_at: "2026-12-01T10:00:00Z" }, confirm: true }, { fetch, env, now })).rejects.toMatchObject({ code: "not_due" });
    await expect(agent.call("publish", { item: { ...approvedX, platform: "instagram" }, confirm: true }, { fetch, env, now })).rejects.toMatchObject({ code: "unsupported_platform" });
    await expect(agent.call("publish", { item: { ...approvedX, text: "x".repeat(281) }, confirm: true }, { fetch, env, now })).rejects.toMatchObject({ code: "too_long" });
    expect(fetch).not.toHaveBeenCalled();
  });

  it("posts to X API v2 with a Bearer token and a deterministic idempotency key", async () => {
    const { fetch, calls } = fakeFetch([json({ data: { id: "1888", text: approvedX.text } }, 201)]);
    const out = await agent.call("publish", { item: approvedX, confirm: true }, { fetch, env, now });
    expect(out).toMatchObject({ platform: "x", status: "published", published: true, remote_id: "1888", url: "https://x.com/i/web/status/1888", attempts: 1 });
    expect(calls[0].url).toBe("https://api.x.com/2/tweets");
    expect(calls[0].init.method).toBe("POST");
    expect(calls[0].init.headers.authorization).toBe("Bearer test-x-token");
    expect(JSON.parse(calls[0].init.body)).toEqual({ text: approvedX.text });
    expect(JSON.stringify(out)).not.toContain("test-x-token");
    const again = await agent.call("publish", { item: { ...approvedX, text: "Offline mode is here.   https://oakline.example/notes" }, published_keys: [out.idempotency_key], confirm: true }, { fetch: vi.fn(), env, now });
    expect(again).toMatchObject({ status: "already_published", already_published: true, attempts: 0 });
  });

  it("maps X duplicate-content 403 to already_published and other 403s to auth errors", async () => {
    const dup = fakeFetch([json({ detail: "You are not allowed to create a Tweet with duplicate content.", status: 403 }, 403)]);
    expect(await agent.call("publish", { item: approvedX, confirm: true }, { fetch: dup.fetch, env, now })).toMatchObject({ status: "already_published", published: false });
    const denied = fakeFetch([json({ detail: "Forbidden" }, 403)]);
    await expect(agent.call("publish", { item: approvedX, confirm: true }, { fetch: denied.fetch, env, now })).rejects.toMatchObject({ code: "auth_error" });
    // X problem-details shape for an app whose plan has no write access: the reason is passed on.
    const plan = fakeFetch([json({ title: "Client Forbidden", detail: "When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project.", reason: "client-not-enrolled", type: "https://api.twitter.com/2/problems/client-forbidden" }, 403)]);
    const err = await agent.call("publish", { item: approvedX, confirm: true }, { fetch: plan.fetch, env, now }).catch((e: any) => e);
    expect(err.code).toBe("auth_error");
    expect(err.message).toMatch(/HTTP 403\): client-not-enrolled: When authenticating/);
    expect(err.message).not.toContain("test-x-token");
  });

  it("retries only on HTTP 429 and reports 5xx as an unknown outcome without retrying", async () => {
    const limited = fakeFetch([() => new Response("", { status: 429, headers: { "retry-after": "0" } }), json({ data: { id: "2" } }, 201)]);
    expect(await agent.call("publish", { item: approvedX, confirm: true }, { fetch: limited.fetch, env, now })).toMatchObject({ status: "published", attempts: 2 });
    const slow = fakeFetch([() => new Response("", { status: 429, headers: { "retry-after": "3600" } })]);
    await expect(agent.call("publish", { item: approvedX, confirm: true }, { fetch: slow.fetch, env, now })).rejects.toMatchObject({ code: "rate_limited" });
    const broken = fakeFetch([json({}, 503)]);
    await expect(agent.call("publish", { item: approvedX, confirm: true }, { fetch: broken.fetch, env, now })).rejects.toMatchObject({ code: "outcome_unknown" });
    expect(broken.calls).toHaveLength(1);
  });

  it("posts to LinkedIn /rest/posts with version headers and little-text escaping", async () => {
    const item = { platform: "linkedin", account: "urn:li:organization:42", text: "Offline mode (beta) is live! #Productivity tips_and_tricks", approved: true };
    const { fetch, calls } = fakeFetch([() => new Response(null, { status: 201, headers: { "x-restli-id": "urn:li:share:777" } })]);
    const out = await agent.call("publish", { item, confirm: true }, { fetch, env, now });
    expect(out).toMatchObject({ status: "published", remote_id: "urn:li:share:777", url: "https://www.linkedin.com/feed/update/urn:li:share:777/" });
    expect(calls[0].url).toBe("https://api.linkedin.com/rest/posts");
    expect(calls[0].init.headers["linkedin-version"]).toBe("202610");
    expect(calls[0].init.headers["x-restli-protocol-version"]).toBe("2.0.0");
    const body = JSON.parse(calls[0].init.body);
    expect(body).toMatchObject({ author: "urn:li:organization:42", visibility: "PUBLIC", lifecycleState: "PUBLISHED" });
    expect(body.commentary).toBe("Offline mode \\(beta\\) is live! {hashtag|\\#|Productivity} tips\\_and\\_tricks");
    await expect(agent.call("publish", { item: { ...item, account: "not-a-urn" }, confirm: true }, { fetch: vi.fn(), env, now })).rejects.toMatchObject({ code: "invalid_input" });
  });

  it("posts to a Facebook Page feed with the token in the body, never in the URL or output", async () => {
    const item = { platform: "facebook", account: "1234567890", text: "Offline mode is live.", link: "https://oakline.example/?utm_source=facebook", approved: true };
    const { fetch, calls } = fakeFetch([json({ id: "1234567890_55" })]);
    const out = await agent.call("publish", { item, confirm: true }, { fetch, env, now });
    expect(out).toMatchObject({ status: "published", remote_id: "1234567890_55" });
    expect(calls[0].url).toBe("https://graph.facebook.com/v23.0/1234567890/feed");
    expect(calls[0].url).not.toContain("test-fb-token");
    expect(calls[0].init.headers.authorization).toBeUndefined();
    const form = new URLSearchParams(calls[0].init.body);
    expect(form.get("message")).toBe("Offline mode is live.");
    expect(form.get("link")).toBe(item.link);
    expect(form.get("access_token")).toBe("test-fb-token");
    expect(JSON.stringify(out)).not.toContain("test-fb-token");
  });

  it("starts a YouTube videos.insert resumable session with metadata only (private by default)", async () => {
    const item = { platform: "youtube", account: "my-channel", title: "Offline mode in 30 seconds", text: "How offline sync works.", approved: true };
    const session = "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&upload_id=xyz";
    const { fetch, calls } = fakeFetch([() => new Response(null, { status: 200, headers: { location: session } })]);
    const yt = { video_size_bytes: 1048576, video_mime_type: "video/mp4", made_for_kids: false };
    const out = await agent.call("publish", { item, youtube: yt, confirm: true }, { fetch, env, now });
    expect(out).toMatchObject({ status: "upload_session_created", published: false, upload_url: session });
    const u = new URL(calls[0].url);
    expect(u.hostname).toBe("www.googleapis.com");
    expect(u.pathname).toBe("/upload/youtube/v3/videos");
    expect(u.searchParams.get("uploadType")).toBe("resumable");
    expect(calls[0].init.headers["x-upload-content-length"]).toBe("1048576");
    const body = JSON.parse(calls[0].init.body);
    expect(body).toEqual({ snippet: { title: item.title, description: item.text, categoryId: "22" }, status: { privacyStatus: "private", selfDeclaredMadeForKids: false } });
    expect(out.notes.join(" ")).toMatch(/upload the file bytes/);
    await expect(agent.call("publish", { item, confirm: true }, { fetch: vi.fn(), env, now })).rejects.toMatchObject({ code: "invalid_input" });
    const evil = fakeFetch([() => new Response(null, { status: 200, headers: { location: "https://evil.example/upload" } })]);
    await expect(agent.call("publish", { item, youtube: yt, confirm: true }, { fetch: evil.fetch, env, now })).rejects.toMatchObject({ code: "platform_error" });
  });
});

describe("social-publisher: MCP", () => {
  it("lists tools and calls them over JSON-RPC, surfacing the confirmation gate", async () => {
    const list = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 1, method: "tools/list" });
    expect(list.result.tools.map((t: any) => t.name)).toEqual(["draft_posts", "schedule_queue", "publish"]);
    const call = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "draft_posts", arguments: { brief: "Hello", platforms: ["x"] } } });
    expect(call.result.isError).toBe(false);
    expect(call.result.structuredContent.posts[0].text).toBe("Hello");
    const blocked = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "publish", arguments: { item: approvedX } } });
    expect(blocked.result.isError).toBe(true);
    expect(blocked.result.content[0].text).toMatch(/^confirmation_required: /);
  });
});

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).