AI Marketing t ≈ 22 min

Claude Agent SDK for Marketers: Build AI Agents That Run Your MarTech Stack

Build marketing agents that automate campaign workflows, CRM operations, and reporting. Direct from Anthropic's playbook.

yfx(m)

yfxmarketer

January 5, 2026

Claude Agent SDK gives marketing teams the same AI agent architecture Anthropic uses internally. 15-20 hours saved per week. One operator produced 12 blog posts, 25 email variations, and 50 ad copy tests in a single week using these patterns. The SDK packages campaign automation, CRM integration, and reporting workflows into one framework built on Claude Code.

Marketing automation in 2026 shifts from rigid Zapier workflows to adaptive AI agents. Your agent reads campaign data, decides actions, executes across channels, and verifies tracking fires. The Claude Agent SDK provides the same tools, agent loop, and context management that power Claude Code, now programmable in Python and TypeScript for marketing operations.

TL;DR

Claude Agent SDK enables marketing agents that automate campaign workflows, CRM operations, and cross-channel reporting. Agents use built-in tools for file operations, bash commands, web search, and code execution. The SDK handles tool execution, context management, and error recovery automatically. Prototype in Claude Code first, then deploy production agents using the Python or TypeScript SDK.

Key Takeaways

  • Marketing agents save 10-25 hours weekly on reporting, data transformation, and campaign operations
  • Built-in tools include Read, Edit, Bash, WebSearch, and WebFetch without implementing execution logic
  • Every marketing agent follows three phases: gather data, take action, verify tracking
  • Code generation handles reporting and content creation through Python script generation
  • Sub-agents manage multi-channel campaigns by running channel-specific tasks in parallel
  • MCP servers extend agent capabilities with custom tools for CRM and analytics platforms
  • Hooks provide deterministic verification at specific points in the agent loop

What Is Claude Agent SDK for Marketing Teams?

Claude Agent SDK packages AI agent infrastructure into a reusable marketing automation framework. The SDK includes built-in tools for reading files, running commands, searching the web, and editing code. Marketing ops teams no longer rebuild these components for every project. The agent executes tools directly instead of asking you to implement them.

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Pull our top 10 blog posts by organic traffic from GA4",
        options=ClaudeAgentOptions(
            allowed_tools=["Bash", "WebFetch", "Read"],
            permission_mode="acceptEdits"
        )
    ):
        print(message)

asyncio.run(main())

Marketing agents built on the SDK run with full MarTech stack access. Your agent connects to HubSpot, Salesforce, GA4, and ad platforms simultaneously. The SDK handles orchestration, tool execution, context management, and retries automatically.

Traditional marketing automation breaks on edge cases. Zapier workflows fail when field formats change. Custom scripts crash on unexpected API responses. Claude Agent SDK adapts to variations, handles errors gracefully, and retries with modified approaches.

Action item: Install Claude Code CLI and the Python SDK. Run your first query against your MarTech stack this week.

Why Does Bash Make Marketing Agents 10x More Powerful?

Bash enables composable MarTech operations without building hundreds of custom integrations. The Bash tool in Claude Agent SDK allows agents to run shell commands, chain operations, and process data through standard Unix utilities. One bash command chain replaces dozens of Zapier steps.

Marketing agents using bash save 3-5 hours per reporting cycle. The agent fetches Google Ads data via curl, pipes through jq for transformation, calculates ROAS, and outputs formatted results. The SDK executes bash commands directly without you implementing the execution logic.

Anthropic’s engineering blog explains the power of bash for agents: Claude writes code to download PDFs, convert to text, and search across attachments to find useful information. Marketing agents apply the same pattern to campaign data, CRM exports, and analytics reports.

The file system becomes context engineering for marketing agents. Store previous campaign data in a folder called “Campaigns.” The agent searches these files for context when asked about historical performance. Folder structure determines how efficiently the agent gathers relevant information.

Action item: Create a working directory with your MarTech API credentials and sample data exports. Test bash queries through Claude Code CLI.

What Are the Three Phases of Marketing Agent Workflows?

Every marketing agent follows gather, act, verify phases. Gathering means querying CRMs, analytics platforms, and content systems for relevant data. Acting means executing across email, ads, social, and web channels. Verifying means confirming tracking fires and data syncs correctly.

How Do Marketing Agents Gather Campaign Data?

Marketing agents gather data using built-in tools like Read, Glob, Grep, and WebFetch. The agent searches Salesforce exports for recent opportunities. It pulls GA4 data through the WebFetch tool. It reads local CSV files containing campaign performance metrics.

Data gathering through file operations reduces context window usage by 60-80%. The agent stores API responses in files rather than holding raw JSON in memory. Large datasets become queryable through grep and iterative file reading.

The SDK supports agentic search where Claude decides which files to load into context. Semantic search requires chunking, embedding, and vector queries. Agentic search lets the agent use bash scripts like grep and tail to find relevant information dynamically.

How Do Marketing Agents Take Action Across Channels?

Marketing agents take action through code generation and tool execution. The agent writes Python scripts to update CRM properties. It generates reports in Google Sheets format. It creates email templates following brand guidelines stored in skill files.

Code generation excels for marketing automation tasks. Anthropic’s file creation feature in Claude.ai relies entirely on code generation. Claude writes Python scripts to create Excel spreadsheets, PowerPoint presentations, and Word documents. Marketing agents apply the same pattern to reports and content.

The SDK executes generated code automatically through the Bash tool. No manual intervention required for script execution. The agent writes code, runs it, observes results, and iterates until the task completes.

How Do Marketing Agents Verify Campaign Results?

Marketing agents verify results through rules-based feedback and deterministic checks. Tracking verification confirms GA4 page_view events fire. CRM verification validates contact records contain required fields. Creative verification checks email templates pass spam score thresholds.

Hooks provide deterministic verification at specific points in the agent loop. The PreToolUse hook validates commands before execution. The PostToolUse hook checks results after tool completion. Hooks execute custom validation logic without modifying the agent’s core behavior.

from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

async def validate_crm_update(input_data, tool_use_id, context):
    """Validate CRM updates contain required fields."""
    if input_data['tool_name'] == 'Bash':
        command = input_data['tool_input'].get('command', '')
        if 'hubspot' in command and 'email' not in command:
            return {
                'hookSpecificOutput': {
                    'hookEventName': 'PreToolUse',
                    'permissionDecision': 'deny',
                    'permissionDecisionReason': 'CRM update missing email field'
                }
            }
    return {}

options = ClaudeAgentOptions(
    hooks={
        'PreToolUse': [
            HookMatcher(matcher='Bash', hooks=[validate_crm_update])
        ]
    }
)

Verification rules for marketing agent workflows include these checks:

  • GA4 page_view fires within 2 seconds of page load
  • Form submission event includes form_name parameter
  • UTM parameters captured in CRM hidden fields
  • Conversion pixel fires to Google Ads on thank you page
  • Contact record appears in CRM within 5 minutes

Action item: Implement a PreToolUse hook that validates CRM updates in your marketing agent.

How Does Code Generation Automate Non-Technical Marketing Tasks?

Code generation transforms marketing requests into executable Python scripts. Your agent writes a script to query HubSpot contacts, filter by lead score, pull enrichment data from APIs, and update contact properties. The script runs repeatedly without modification.

The Claude Agent SDK excels at code generation because code is precise, composable, and reusable. When building marketing agents, consider which tasks would benefit from being expressed as code. Reporting, data transformation, and content templating all translate well to generated scripts.

Marketing content production scales 5x through generated workflows. The agent writes scripts to fetch trending topics, analyze competitor content gaps, generate article outlines, and queue drafts. One operator produced 12 blog posts weekly using this pattern.

Reporting automation eliminates 3-5 hours of manual data pulling per report. The agent generates a Python script to query GA4, pull HubSpot data, fetch ad spend, calculate blended CAC, and output formatted results. Changes require updating one script, not rebuilding workflows.

SYSTEM: You are a marketing automation architect for {{COMPANY_NAME}}.

<context>
Reporting goal: {{REPORTING_GOAL}}
Data sources: HubSpot CRM, GA4, Google Ads, Meta Ads
Output format: CSV with summary statistics
Frequency: {{CADENCE}}
</context>

Generate a Python script that:

1. Queries each data source via API with authentication
2. Transforms data into unified format
3. Calculates derived metrics (CAC, ROAS, conversion rates)
4. Handles rate limits with exponential backoff
5. Outputs results to specified file path

MUST include error handling for API failures.
MUST include logging for debugging.
MUST be executable via bash command.

Output: Complete Python script with inline comments.

Action item: Identify one manual report consuming 2+ hours monthly. Generate a Python script to automate it.

How Do Sub-Agents Handle Multi-Channel Campaign Orchestration?

Sub-agents run specialized tasks autonomously and return results to the main agent. The Claude Agent SDK supports the Agent tool for launching sub-agents with specific prompts and types. Each sub-agent operates in isolated context without polluting the main agent’s reasoning.

Campaign launches demonstrate sub-agent orchestration patterns. The main agent receives a campaign brief. It launches sub-agents for email creative, ad creative, landing page copy, and audience segmentation. Each completes independently. The main agent reviews outputs and coordinates launch.

Define specialized sub-agents in your project’s .claude/agents directory using Markdown with YAML frontmatter. Each sub-agent has its own allowed tools, system prompt, and permission configuration. The SDK loads these definitions automatically when setting_sources includes “project.”

from claude_agent_sdk import query, ClaudeAgentOptions

async def run_campaign_agent():
    async for message in query(
        prompt="Launch Q1 campaign: create email sequence, ad creative, and landing page",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Bash", "Agent"],
            setting_sources=["project"],
            permission_mode="acceptEdits"
        )
    ):
        print(message)

Sub-agents enable adversarial QA for campaign quality assurance. Launch a review sub-agent with instructions to critique work against brand guidelines. The QA sub-agent catches issues the creative sub-agent missed because it evaluates without bias from the creation process.

Marketing sub-agent patterns by function:

  • Channel sub-agents: Email, paid media, social, web execution
  • Research sub-agents: Competitive analysis, trend identification
  • QA sub-agents: Creative review, compliance checking
  • Reporting sub-agents: Data aggregation, visualization
  • Enrichment sub-agents: Contact data, company data

Action item: Create a .claude/agents directory with sub-agent definitions for your primary marketing channels.

How Do MCP Servers Extend Marketing Agent Capabilities?

MCP servers connect custom tools, databases, and APIs to your marketing agent. The Model Context Protocol enables external servers or fast in-process tools via create_sdk_mcp_server(). Common extensions include CRM lookups, analytics queries, and content management operations.

from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions

@tool("search_contacts", "Search HubSpot contacts", {"query": str, "limit": int})
async def search_contacts(args):
    # Your HubSpot API logic here
    results = await hubspot_api.search(args['query'], args['limit'])
    return {
        "content": [{
            "type": "text",
            "text": f"Found {len(results)} contacts matching '{args['query']}'"
        }]
    }

@tool("get_campaign_metrics", "Get campaign performance", {"campaign_id": str})
async def get_campaign_metrics(args):
    metrics = await analytics_api.get_metrics(args['campaign_id'])
    return {
        "content": [{
            "type": "text",
            "text": f"Campaign {args['campaign_id']}: {metrics['conversions']} conversions"
        }]
    }

marketing_tools = create_sdk_mcp_server(
    name="marketing",
    version="1.0.0",
    tools=[search_contacts, get_campaign_metrics]
)

options = ClaudeAgentOptions(
    mcp_servers={"marketing": marketing_tools},
    allowed_tools=["mcp__marketing__search_contacts", "mcp__marketing__get_campaign_metrics"]
)

The SDK supports both in-process SDK servers and external subprocess servers. Use in-process servers for fast, lightweight tools. Use external servers for complex integrations requiring separate processes or different languages.

MCP servers for marketing automation commonly include:

  • CRM servers: Contact search, deal updates, property modifications
  • Analytics servers: GA4 queries, attribution data, funnel metrics
  • Content servers: Asset management, template retrieval, publishing
  • Ad platform servers: Campaign data, bid adjustments, audience sync

Action item: Create an MCP server with tools for your primary CRM operations.

What Should Be Tools vs Bash vs Code Generation?

Tools handle atomic operations requiring explicit user approval. Sending email campaigns needs permission_mode configuration. Publishing content needs approval gates. The SDK’s permission system controls which tools execute automatically versus requiring confirmation.

Bash handles composable operations with moderate complexity. Searching CRM exports works through grep. Transforming JSON uses jq. Processing CSVs uses csvkit or Python scripts. The Bash tool chains these operations based on task requirements.

Code generation handles dynamic logic requiring custom calculations. Attribution modeling needs scripts for touchpoint weighting. Lead scoring requires threshold logic specific to your funnel. The agent writes Python scripts and executes them through the Bash tool.

Permission modes in Claude Agent SDK:

  • default: Prompts for potentially dangerous operations
  • acceptEdits: Auto-approves file changes
  • bypassPermissions: Skips all permission checks (requires explicit flag)

Decision framework for marketing operations:

  • Sending campaigns: Use tool with default permission mode
  • Querying data: Use Bash or WebFetch with acceptEdits
  • Transforming data: Use code generation with acceptEdits
  • Generating reports: Use code generation with acceptEdits
  • Modifying CRM records: Use custom MCP tool with validation hooks

Action item: Configure permission_mode=“acceptEdits” for read-only marketing workflows.

How Do You Design Search Interfaces for Marketing Data?

Search interfaces determine how effectively agents find relevant campaign data. The SDK provides Glob for file pattern matching, Grep for content search, and Read for file access. Design your file system structure to enable efficient agent navigation.

The CLAUDE.md file maintains project context across sessions. Store your marketing data schema, API documentation, and common query patterns in CLAUDE.md. The agent references this context when gathering campaign data.

Progressive disclosure reduces context usage for large marketing datasets. The agent searches for files matching criteria first. It receives file paths. It reads specific files based on initial results. A 100,000-contact export becomes queryable through iterative file operations.

Skills provide specialized capabilities defined in Markdown files. Create a skill for campaign analysis that documents your metrics definitions, attribution model, and reporting standards. Store skills in .claude/skills/SKILL.md files within your project.

SYSTEM: You are a marketing data architect designing agent search interfaces.

<context>
Data source: {{PLATFORM_NAME}}
File format: {{EXPORT_FORMAT}}
Common queries: {{TYPICAL_SEARCHES}}
Volume: {{RECORD_COUNT}} records
</context>

Design a file system structure that enables:

1. Fast filtering by date range and segment
2. Efficient grep patterns for common searches
3. Clear naming conventions for campaign data
4. Separation of raw exports and processed results

MUST specify directory structure with example paths.
MUST include CLAUDE.md content for agent context.
MUST document file naming conventions.

Output: File system specification with examples.

Action item: Create a CLAUDE.md file documenting your MarTech stack and common query patterns.

What Verification Rules Work for Marketing Agent QA?

Hooks execute at specific points in the agent loop for deterministic verification. PreToolUse hooks validate before execution. PostToolUse hooks check after completion. The SDK supports hooks for UserPromptSubmit, Stop, SubagentStop, and PreCompact events.

Rules-based feedback provides the most reliable verification. Code linting catches syntax errors. Schema validation confirms data structure. Field presence checks verify required values exist. The more specific the feedback, the better the agent self-corrects.

from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

async def verify_tracking_implementation(input_data, tool_use_id, context):
    """Verify tracking code before deployment."""
    if input_data['tool_name'] == 'Edit':
        content = input_data['tool_input'].get('content', '')
        required_tracking = ['gtag', 'fbq', 'lintrk']
        missing = [t for t in required_tracking if t not in content]
        if missing and 'landing' in input_data['tool_input'].get('path', ''):
            return {
                'hookSpecificOutput': {
                    'hookEventName': 'PreToolUse',
                    'permissionDecision': 'deny',
                    'permissionDecisionReason': f'Missing tracking: {missing}'
                }
            }
    return {}

async def log_all_tool_usage(input_data, tool_use_id, context):
    """Audit log for all tool executions."""
    print(f"Tool: {input_data.get('tool_name')} | ID: {tool_use_id}")
    return {}

options = ClaudeAgentOptions(
    hooks={
        'PreToolUse': [
            HookMatcher(matcher='Edit', hooks=[verify_tracking_implementation]),
            HookMatcher(hooks=[log_all_tool_usage])
        ]
    }
)

Marketing verification automation stack:

  • PreToolUse hooks: Validate commands before execution
  • PostToolUse hooks: Check results after completion
  • Playwright: Tracking pixel verification
  • Schema validation: CRM data completeness checks
  • Custom scripts: Platform-specific verification logic

Pre-launch tracking checklist for marketing agents:

  • GA4 page_view event fires on load
  • Form submission event includes form_name
  • UTM parameters captured in hidden fields
  • Google Ads conversion fires on thank you page
  • Meta Pixel Lead event fires on submission
  • Data appears in CRM within 5 minutes

Action item: Implement PostToolUse hooks that log all CRM modifications for audit trails.

How Do You Prototype Marketing Agents in Claude Code?

Claude Code CLI provides the fastest path to prototype marketing agents. Install Claude Code, authenticate, and run queries against your MarTech data. Watch how the agent gathers context, executes tools, and verifies results. Iterate on your CLAUDE.md until task completion rates exceed 90%.

# Install Claude Code
curl -fsSL https://claude.ai/install.sh | bash

# Verify installation
claude doctor

# Run a marketing query
claude "Pull our top performing blog posts from GA4 and identify common topics"

The CLAUDE.md file defines your marketing agent capabilities. Include API endpoints for HubSpot, GA4, and ad platforms. Add example queries. Specify output formats. Document verification rules. Keep focused on what the agent needs for marketing operations.

Slash commands provide shortcuts for common marketing tasks. Define commands as Markdown files in .claude/commands/ directory. Create /report for performance summaries, /campaign for launch workflows, /analyze for competitive research.

Transcript review reveals how agents approach marketing tasks. If the agent struggles finding HubSpot endpoints, improve API documentation in CLAUDE.md. If GA4 queries return wrong data, add example queries. Each friction point becomes an improvement to your agent configuration.

Action item: Install Claude Code CLI and run 10 test queries against your MarTech stack.

How Do You Calculate ROI for Marketing Agent Investment?

Time savings quantify immediate agent value. Track hours spent on repetitive tasks before deployment. Measure hours after. Calculate savings using team compensation rates. Marketing teams save 10-25 hours weekly on reporting, transformation, and campaign operations.

Output multiplication measures productivity beyond time savings. Count content pieces before and after deployment. Measure campaign variations tested. Track reports generated. One operator producing 50 ad variations weekly versus 10 represents 5x multiplication.

Marketing agent ROI calculation:

  • Weekly time savings: (hours before - hours after) × hourly cost = $X
  • Output multiplication: (outputs after ÷ outputs before) × value per output = $Y
  • Error reduction: errors prevented × average cost per error = $Z
  • Total weekly ROI: $X + $Y + $Z

Example calculation for mid-market marketing team:

  • Time savings: 15 hours × $75/hour = $1,125/week
  • Output multiplication: 3x content output × $200/piece = $1,200/week
  • Error reduction: 2 errors prevented × $500/error = $1,000/week
  • Total weekly ROI: $3,325/week = $172,900/year

Action item: Track time on manual marketing tasks this week. Calculate savings from 50% automation.

How Do You Deploy Production Marketing Agents?

Production deployment uses the Python or TypeScript SDK with your chosen hosting provider. The SDK requires Claude Code as its runtime. Set your ANTHROPIC_API_KEY environment variable or configure authentication through Amazon Bedrock, Google Vertex AI, or Microsoft Foundry.

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def run_marketing_agent(prompt: str, working_dir: str):
    async for message in query(
        prompt=prompt,
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Bash", "WebFetch", "Glob", "Grep"],
            permission_mode="acceptEdits",
            cwd=working_dir,
            setting_sources=["project"],
            system_prompt="You are a senior marketing analyst. Follow brand guidelines in CLAUDE.md."
        )
    ):
        if hasattr(message, "result"):
            return message.result

# Run daily reporting
asyncio.run(run_marketing_agent(
    prompt="Generate daily performance report for all active campaigns",
    working_dir="/app/marketing-data"
))

Authentication options for production deployment:

  • ANTHROPIC_API_KEY: Direct API access
  • CLAUDE_CODE_USE_BEDROCK=1: Amazon Bedrock with AWS credentials
  • CLAUDE_CODE_USE_VERTEX=1: Google Vertex AI with GCP credentials
  • CLAUDE_CODE_USE_FOUNDRY=1: Microsoft Foundry with Azure credentials

Production deployment checklist:

  • Claude Code CLI installed in deployment environment
  • API credentials configured as environment variables
  • Working directory contains CLAUDE.md and data files
  • Hooks configured for validation and logging
  • Permission mode set appropriately for automation level
  • Error handling wraps query() calls

Action item: Deploy a test agent to your staging environment with read-only permissions.

Which Marketing Workflows Should You Automate First?

Reporting automation delivers immediate measurable value with low risk. Weekly performance reports consume 3-5 hours of manual data pulling. The agent queries all sources, transforms metrics, and outputs formatted reports. Time savings start immediately.

Content production scales without proportional headcount growth. Blog research, outline generation, and draft creation become agent tasks. Human review focuses on strategic editing. Output increases 3-5x while maintaining quality through skill-based guidelines.

Campaign operations reduce launch friction and error rates. The agent handles asset coordination, tracking verification, and QA checklisting. Humans focus on strategy and creative direction. Campaigns launch faster with 60-80% fewer errors.

Marketing workflows ranked by automation ROI:

  1. Weekly performance reporting: 3-5 hours saved, $225-375/week
  2. Content research and outlining: 2-3 hours saved per piece
  3. Campaign launch QA: 1-2 hours saved per campaign
  4. Contact enrichment: 30 minutes saved per 100 contacts
  5. Competitive monitoring: 2-3 hours saved weekly

Action item: Select one workflow from this list. Prototype agent automation in Claude Code this week.

Final Takeaways

Claude Agent SDK enables marketing teams to build AI agents saving 10-25 hours weekly on campaign workflows, CRM operations, and cross-channel reporting.

Built-in tools like Read, Edit, Bash, WebFetch, and Grep let marketing agents execute operations directly without implementing tool execution logic.

Hooks provide deterministic verification at PreToolUse and PostToolUse events for tracking validation, CRM checks, and creative QA.

MCP servers extend agent capabilities with custom tools for HubSpot, Salesforce, GA4, and ad platform integrations.

Production deployment requires Claude Code CLI, API credentials, and properly configured CLAUDE.md with your MarTech stack documentation.

yfx(m)

yfxmarketer

AI Marketing Operator

Writing about AI marketing, growth, and the systems behind successful campaigns.

read_next(related)