> ## Documentation Index
> Fetch the complete documentation index at: https://docs.paddockai.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Marketing campaigns with approvals

> A Next.js app where an agent researches and plans a marketing campaign, with search visibility data from DataForSEO, prepares HubSpot lists and email drafts, proposes X posts to an approval queue, and writes follow-ups for contacts a HubSpot workflow sends to a connector.

This example builds `gtm`: you give an agent a campaign brief, and it researches the market with Exa and Firecrawl, and optionally search visibility with DataForSEO, reads your HubSpot CRM, and writes a campaign plan: segments, channels, messaging per segment, a content calendar, and metrics. Asked to execute, it creates HubSpot segments and marketing email drafts and proposes X posts and threads. Nothing goes out without a person: every X post waits in the app's review queue until someone approves, edits, or rejects it, and emails stay drafts that a person sends from HubSpot. When a contact joins the campaign's list, a HubSpot workflow webhook reaches a [connector](https://docs.paddockai.dev/guides/connectors.md), and the agent drafts a personal follow-up email into the same queue.

It is a Next.js app on `@paddockai/server` and `@paddockai/react`, in [`examples/gtm`](https://github.com/wenfengwang/paddock/tree/main/examples/gtm) of the paddock repository, with a Dockerfile, Kubernetes manifests, and a script that sets up the connector.

```mermaid theme={null}
sequenceDiagram
  participant You
  participant App as gtm app
  participant P as paddock
  participant Agent
  You->>App: campaign brief
  App->>P: agent.sessions.create, then send the brief
  P->>Agent: the brief
  Agent->>App: /mcp/hubspot (forwarded with your HubSpot token)
  Agent->>App: /mcp/gtm save_plan, /mcp/x propose_post
  You->>App: approve the post
  App->>App: publish it with your X token
```

## How it fits on paddock

| Need | paddock |
| - | - |
| The agent | One agent from the template `gtm`: Claude Code with a complete system prompt, which replaces Claude Code's own |
| Exa, Firecrawl, Notion | MCP entries on the agent, with their keys; the template carries none |
| HubSpot and X | MCP entries pointing at the app, with a key of the app's; the app holds the OAuth tokens and refreshes them, so they never enter the sandbox |
| DataForSEO | An MCP entry pointing at the app, which forwards to DataForSEO's MCP server with the account's login and enforces an endpoint allowlist and a spending budget per campaign |
| A campaign | A session with the campaign in its metadata and a session system prompt that names it; the brief is its first message |
| The campaign's conversation, its replies streaming with their tool calls inline | `useSession` with a session token the app mints |
| Each campaign's live status in the campaign list | One list of the project's sessions, filtered by the campaign metadata |
| Follow-ups | A connector whose inbound function sends the contact's details to the agent, in one session per contact |

The app creates the template and the agent when it starts, and gives the agent its MCP servers. Credentials go on the agent, not the template:

```ts theme={null}
const template = await paddock.templates.create({
  apiVersion: "paddock.build/v1",
  kind: "Template",
  metadata: { name: "gtm" },
  spec: {
    harness: "claude-code",
    model: "claude-opus",
    systemPrompt: "You are a go-to-market strategist and campaign operator ...",
  },
});
const gtmAgent = await paddock.agents.create({
  template: `${template.name}@${template.version}`,
  metadata: { app: "gtm" },
});
await gtmAgent.mcp.add({
  name: "exa",
  url: "https://mcp.exa.ai/mcp?tools=web_search_exa,web_search_advanced_exa,web_fetch_exa",
  headers: { "x-api-key": process.env.EXA_API_KEY ?? "" },
});
await gtmAgent.mcp.add({
  name: "hubspot",
  url: "https://gtm.example.com/mcp/hubspot", // the app's proxy
  headers: { Authorization: `Bearer ${process.env.GTM_APP_KEY}` },
});
```

Remote MCP servers need an https URL, so in development the app runs behind a tunnel, such as `ngrok http 3000`, whose URL the app puts in the entries.

An agent never changes template, so a new model or system prompt gives the app a new agent. The app keeps accepting the replaced agent's app key, so campaigns started on it keep working; run `pnpm setup-connector` again to route the follow-up connector to the new agent.

## Search data with a budget

DataForSEO's MCP server has one generic tool, `api_request`, that can call any of its paid endpoints, and nothing in the server limits which. So the agent's `dataforseo` entry points at the app, and the app applies the rules before it forwards a call: only the endpoints a campaign needs (domain traffic estimates, ranked keywords, search competitors, keyword gaps, backlink summaries, Google results, and keyword volumes), one task per call, a cap on `limit`, and a spending budget per campaign. The app adds a required `campaign` argument to the tool, charges each call's cost to that campaign, and answers a call past the budget with a tool error the agent reads. DataForSEO models search traffic only; it has no traffic-source breakdown or total visits, and the system prompt tells the agent so.

DataForSEO's server accepts any credentials until a tool runs, so the app checks its login and balance with DataForSEO's free `user_data` call when it starts and when you ask, and shows the result on its Connections page. Each campaign's Activity tab lists its calls and what each cost.

## The approval queue

The agent's X server is the app's own. Its `propose_post` tool stores a draft and publishes nothing; `search_recent` and `get_mentions` read X with your token. When you approve a draft, the app publishes it with the X API, a thread post by post, each a reply to the one before. A follow-up email from the connector lands in the same queue; approving it marks it ready, and a person sends it from HubSpot.

## The app's pages

The campaign page puts the conversation beside the plan, the campaign's drafts, and its research spending. Everything in the conversation is derived from `useSession`'s state, so a reload rebuilds it from the session's events: consecutive tool calls collapse into one row that names the running step, a saved plan and queued drafts appear as cards that open them, the agent's `AskUserQuestion` options become buttons, and a completed reply lists the pages its research read. The header shows what the agent does and for how long, and a **Session** popover shows the session's MCP servers and context use from the harness status.

In the review queue, X drafts look like posts with a counter per post, and nothing is published until you confirm in a dialog that names the account. A Connections page shows HubSpot and X, including a sign-in that expired, and a banner on every page says when either is not connected.

## Follow-ups from HubSpot

The example's `pnpm setup-connector` creates the connector. Its inbound function checks a header HubSpot sends with its **API key** authentication against the connector's `default` secret, deduplicates on the contact and the list or form, and routes each contact to a session of its own; the `hubspot-v2` or `hubspot-v3` preset could verify HubSpot's signature instead:

```ts theme={null}
const followUps = await paddock.connectors.create({
  name: "gtm-hubspot-followups",
  inbound: {},
  secret: process.env.GTM_WEBHOOK_KEY,
});
await followUps.functions.set("inbound", {
  runtime: "nodejs24.x",
  code: `export default async function handle(req, ctx) {
  if (req.headers["x-gtm-webhook-key"] !== ctx.secret) return { accept: false, reason: "wrong key" };
  const b = JSON.parse(req.body.toString("utf8"));
  return {
    accept: true,
    dedupeKey: b.contactId + "/" + b.listId,
    deliver: [{
      agent: ctx.params.agent,
      sessionKey: "hubspot-contact-" + b.contactId,
      message: "[gtm follow-up] A HubSpot contact " + b.event + ". Contact ID: " + b.contactId + ", email: " + b.email,
      settings: { cwd: "followups", metadata: { app: "gtm", kind: "followup" } },
    }],
  };
}`,
  params: { agent: agent.id },
});
console.log(followUps.inbound?.url); // the URL for HubSpot's "Send a webhook" action
```

In HubSpot, a contact-based workflow enrolls contacts that join the campaign's list or submit its form, and its **Send a webhook** action posts a custom body with the contact's ID, email, name, company, and the list or form. Workflow webhooks need Data Hub Professional or Enterprise, and marketing email drafts need Marketing Hub Professional or Enterprise.

## Run it

1. In HubSpot, create an **MCP auth app** with the redirect URL `http://localhost:3000/api/hubspot/callback`. In the X developer console, set your app to **Read and write**, **Web App**, with the callback `http://localhost:3000/api/x/callback`.

2. Build the SDK and install the example:

   ```sh theme={null}
   cd examples/gtm
   pnpm sdk && pnpm install
   ```

3. Copy `.env.example` to `.env` and set the HubSpot, X, Exa, and Firecrawl credentials (and optionally DataForSEO's API login and password), `PADDOCK_API_KEY`, `GTM_ENCRYPTION_KEY`, and `GTM_PUBLIC_URL`, your tunnel's https URL.

4. `pnpm dev`, open `http://localhost:3000`, connect HubSpot and X on the Connections page, and start a campaign. Creating it opens its conversation: the agent's reply streams in as it is written, with its tool calls grouped into rows you can expand to each call's arguments and result.

To look at the pages without real accounts, `pnpm review` runs the app against a local paddock stack with fake HubSpot, X, and DataForSEO servers and a scripted stand-in for the agent; the README describes it.

The example's README covers the HubSpot workflow, the image, and its deployment as one replica with a volume for its SQLite file.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.