SocialClaw

Build a Social Media Agent With the Claude Agent SDK (Tutorial)

July 4, 2026 · 6 min read

Claude Agent SDK tutorial for social media: a TypeScript agent that drafts, validates, publishes, and verifies posts via MCP tools, plus a cron trigger.

SocialClaw's CLI, API, and dashboard surfaces — the publishing backend a Claude Agent SDK agent calls through MCP tools.

Prompting Claude in a chat window works for social publishing — but it still needs you to open the window. The next step is an agent that runs without you: a script that wakes up on a schedule, reads your changelog or content queue, drafts platform-specific posts, validates them, publishes, and verifies delivery. That's what the Claude Agent SDK is for.

The Claude Agent SDK gives you the same agent harness that powers Claude Code — the model loop, tool calling, and permission system — as a library you can call from your own code. Add a social publishing MCP server and your agent gets real publishing tools instead of just text generation.

This tutorial builds that agent in TypeScript, end to end: setup, the code, the validate → publish → verify loop that makes it production-safe, and a cron trigger to run it on autopilot. (API shapes below verified against the official Agent SDK reference, July 4, 2026.)

Nardi Braho - July 4, 2026

TL;DR: npm install @anthropic-ai/claude-agent-sdk, point the mcpServers option at SocialClaw's hosted MCP endpoint (https://getsocialclaw.com/mcp with a Bearer key), restrict allowedTools to the publishing tools you trust, and prompt the agent to validate before applying and check run_status after. Then put the script on a cron schedule.

What are you actually building?

An unattended agent with this loop:

StepMCP toolWhat happens
1. Discoverlist_accounts, account_capabilitiesAgent learns which accounts exist and what each supports
2. Draft(model)Claude writes platform-specific posts from your source content
3. Mediaupload_assetUploads images/video once, gets reusable hosted URLs
4. Validatevalidate_scheduleChecks every post against platform rules before anything is queued
5. Publishapply_scheduleSchedules or publishes only what passed validation
6. Verifyrun_status, post_attemptsConfirms actual delivery — platform "accepted" ≠ published

The SDK provides the loop and the model; the MCP server provides the tools. SocialClaw's hosted server exposes 17 tools across 11 platforms (X, LinkedIn, Instagram professional, Facebook Pages, TikTok, Discord, Telegram, YouTube, Reddit, WordPress, Pinterest), all through official platform APIs. If MCP is new to you, start with what a social media MCP server is, and see the hub for the best social media MCP servers.

How do you set up the project?

Prerequisites: Node.js 18+, an Anthropic API key, and a SocialClaw workspace API key (sign up at getsocialclaw.com, connect accounts via OAuth in the dashboard, copy the key — free tier available).

mkdir social-agent && cd social-agent
npm init -y
npm install @anthropic-ai/claude-agent-sdk
export ANTHROPIC_API_KEY=sk-ant-...
export SOCIALCLAW_API_KEY=sc_live_...

Both keys stay in environment variables. Never put API keys in prompts — prompts get logged; env vars don't.

The agent, in one file

// agent.ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { readFileSync } from "fs";

const changelog = readFileSync("./CHANGELOG.md", "utf-8");

const result = query({
  prompt: `Here is our latest changelog:\n\n${changelog}\n\n
1. List my connected social accounts and check capabilities for X and LinkedIn.
2. Draft one X thread (max 4 posts) and one LinkedIn post announcing the top change.
   Different angles for each platform — not copies.
3. Validate the schedule for tomorrow 9:00 AM local time.
4. If validation passes, apply it. If not, fix the issues and validate again.
5. After applying, check run_status and report exactly what was scheduled.`,
  options: {
    model: "claude-opus-4-8",
    maxTurns: 20,
    systemPrompt:
      "You are a social publishing agent for a developer tool. " +
      "Tone: direct, technical, no hype, no hashtag spam. " +
      "Always validate_schedule before apply_schedule. " +
      "Always verify with run_status after applying. " +
      "Never invent product claims not present in the source content.",
    mcpServers: {
      socialclaw: {
        type: "http",
        url: "https://getsocialclaw.com/mcp",
        headers: {
          Authorization: `Bearer ${process.env.SOCIALCLAW_API_KEY}`,
        },
      },
    },
    allowedTools: [
      "mcp__socialclaw__list_accounts",
      "mcp__socialclaw__account_capabilities",
      "mcp__socialclaw__upload_asset",
      "mcp__socialclaw__validate_schedule",
      "mcp__socialclaw__apply_schedule",
      "mcp__socialclaw__run_status",
      "mcp__socialclaw__post_attempts",
    ],
  },
});

for await (const message of result) {
  if (message.type === "result") {
    console.log(message);
  }
}

Run it with npx tsx agent.ts. Three parts do the heavy lifting:

  • mcpServers points at the hosted endpoint over HTTP — no local server process to manage. The SDK also supports stdio servers (type: "stdio" with command/args/env) if you prefer running the socialclaw npm package locally.
  • allowedTools is your blast-radius control. MCP tools are named mcp__<server>__<tool>; listing them explicitly means the agent can publish but cannot, say, call connect_account or anything else you didn't grant. Start narrow.
  • systemPrompt carries your voice and your safety rules. The two rules that matter most: validate before apply, verify after.

Why is the validate → publish → verify loop non-negotiable?

Because every platform has rules the model can't reliably guess, and every platform can fail after accepting a post:

  • Validation catches shape errors early. Character limits, media requirements (Instagram requires media on every post), format rules. validate_schedule fails fast with a reason the agent can fix — instead of a half-published campaign.
  • TikTok's PNG trap. TikTok photo posts reject PNG uploads (file_format_check_failed — JPEG/WebP only). SocialClaw auto-converts hosted images via ?format=jpeg, but this is exactly the class of platform quirk that makes preflight validation worth it.
  • Accepted ≠ published. A platform can accept a post and drop it during processing. run_status and post_attempts give the agent (and you) the actual delivery state. An unattended agent that doesn't verify will happily report success on posts that never went live.

This pattern is the difference between a demo and something you trust on a schedule.

How do you run it on a cron trigger?

The simplest production shape — a weekly batch, Monday 8am:

# crontab -e
0 8 * * 1 cd /home/you/social-agent && /usr/bin/npx tsx agent.ts >> agent.log 2>&1

For a changelog-driven version, trigger from CI instead: run the script in a GitHub Actions job on release tags, with both keys stored as repository secrets. Same agent, different trigger.

Two operational tips: log the full message stream (the tool calls are your audit trail), and add a notification step — have the agent's final report land in Slack or Telegram so a human sees what shipped, even when nobody triggered it.

When should you use the SDK vs simpler options?

ApproachBest forTrade-off
Claude Code + MCPInteractive use, human in the loopManual trigger; see Claude Code automation
Agent SDK (this tutorial)Unattended agents, custom pipelines, your own productYou own hosting, logging, and failure handling
Direct REST APIDeterministic pipelines with no model in the loopNo drafting intelligence; see best social media APIs for developers

Rule of thumb: if a human triggers every run, use Claude Code. If nothing triggers it but time or CI, use the SDK. If there's no LLM decision-making at all, call the API directly.

FAQs

What is the Claude Agent SDK?

It's Anthropic's library for building custom agents on the same harness that powers Claude Code — model loop, tool calling, MCP support, and permissions — available for TypeScript (@anthropic-ai/claude-agent-sdk on npm) with a Python variant also documented by Anthropic.

Can the agent post to Instagram and TikTok too?

Yes, with platform caveats: Instagram requires a professional (business/creator) account — a Meta rule, not a tool limit — and every Instagram post needs media. TikTok photos must be JPEG/WebP. account_capabilities tells the agent these constraints at runtime, which beats hardcoding them.

How much does it cost to run?

Two meters: Anthropic API usage per run (a weekly batch run is typically a few cents to tens of cents depending on model and content volume) and your SocialClaw plan (free tier available). Cron itself is free.

How do I stop the agent from publishing something bad?

Three layers: allowedTools limits what it can do; the system prompt's validate-before-apply rule limits what gets queued; and for higher stakes you can split the flow — one run drafts and validates, a human approves, a second run applies. publish_draft exists for exactly that handoff.

Do I have to use SocialClaw's MCP server?

No — the SDK works with any MCP server. Postiz (self-hosted) and Ayrshare (agency-oriented API) both have MCP servers too; the trade-offs are ranked in the hub guide. This tutorial uses SocialClaw because the hosted HTTP endpoint means zero server management.

Where does the agent's "memory" of accounts live?

In your SocialClaw workspace, not the agent. Accounts connect once via OAuth; every run rediscovers them with list_accounts. The agent stays stateless — which is exactly what you want for cron.

Related product pages

Core SocialClaw pages for the workflows discussed in the blog.

Integration hub Instagram operators
Instagram integrations Browse SocialClaw Instagram integrations for Slack approval workflows, API scheduling, AI captions, media validation, and professional account publishing.
Open page
Scheduling API Developers and SaaS teams
Scheduler API Use SocialClaw as a scheduler API for connected social accounts, media uploads, validation, timed delivery, and post inspection.
Open page
API comparison API buyers
Social media scheduler API comparison Compare social media scheduler APIs by account connection, media handling, validation, scheduling, idempotency, and post-state inspection.
Open page

More from the blog

An AI agent choosing between MCP tools, a REST API, and workflow automation to publish social media posts.
Article 37 7 min read
MCP vs API vs Zapier: 3 Ways to Let an AI Agent Post for You

MCP vs API vs Zapier for AI agent social posting: a decision framework with a comparison table covering latency, flexibility, skill needed, and cost.

July 4, 2026 Read article
Claude scheduling an X post through the SocialClaw connector, with a Telegram bot confirming the scheduled queue.
Article 35 6 min read
Claude Desktop Connectors: Add Social Publishing in 3 Minutes

Add social media publishing to Claude Desktop connectors in 3 minutes: the exact JSON config, prompts that work, and a review-before-publish habit.

July 4, 2026 Read article
SocialClaw's CLI, API, and dashboard surfaces — the same workspace Cursor's MCP tools publish through.
Article 34 6 min read
How to Post to Social Media From Cursor

Cursor MCP social media setup: the exact mcp.json config, example prompts, and a ship-then-announce workflow so devs post without leaving the editor.

July 4, 2026 Read article