---
title: "Connect LinkedIn to AI Agents: Manage Creatives and DMP Audiences"
slug: connect-linkedin-to-ai-agents-manage-creatives-and-dmp-audiences
date: 2026-11-19
author: Sidharth Verma
categories: ["AI & Agents"]
excerpt: "Learn how to connect LinkedIn to AI agents using Truto's /tools endpoint. Fetch tools, bind them to your LLM, and build autonomous advertising workflows."
tldr: "Programmatically connect LinkedIn to your AI agent framework to autonomously manage DMP audiences, ad creatives, and campaign analytics without building custom API wrappers."
canonical: https://truto.one/blog/connect-linkedin-to-ai-agents-manage-creatives-and-dmp-audiences/
---

# Connect LinkedIn to AI Agents: Manage Creatives and DMP Audiences


You want to connect LinkedIn to an AI agent so your system can autonomously construct Matched Audience (DMP) segments, provision ad creatives, rotate campaigns, and execute highly targeted revenue operations. Here is exactly how to do it using Truto's `/tools` endpoint and SDK, bypassing the need to build and maintain a custom LinkedIn integration from scratch.

Giving a Large Language Model (LLM) read and write access to your LinkedIn Ads instance is an engineering headache. You either spend weeks building, hosting, and managing a custom connector, dealing with Rest.li idiosyncrasies, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on [connecting LinkedIn to ChatGPT](https://truto.one/connect-linkedin-to-chatgpt-manage-ad-campaigns-and-audience-data/), or if you are building on Anthropic's models, read our guide on [connecting LinkedIn to Claude](https://truto.one/connect-linkedin-to-claude-automate-content-and-lead-generation/). For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for LinkedIn, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex B2B advertising workflows. For a deeper look at the architecture behind this approach, refer to our research on [architecting AI agents and the SaaS integration bottleneck](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/).

## The Engineering Reality of the LinkedIn API

Giving an LLM access to external data sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an `@tool` decorator. In production against complex ad-tech systems, this approach collapses.

LinkedIn's API introduces several highly specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning capabilities.

### The URN (Uniform Resource Name) Trap

LinkedIn does not use simple integer or UUID identifiers for its resources. Everything in the LinkedIn ecosystem is identified by a URN. An ad account might be `urn:li:sponsoredAccount:123456`, a person might be `urn:li:person:abcXYZ`, and a creative might be `urn:li:sponsoredCreative:987654`. 

When making API requests, these URNs must be strictly URL-encoded in the path. `urn:li:sponsoredAccount:123456` becomes `urn%3Ali%3AsponsoredAccount%3A123456`. Standard LLMs struggle with URL encoding rules, often hallucinating plain text URNs into paths, which results in immediate 400 Bad Request errors. Expecting an agent to reliably remember which parameters need URL encoding across 100+ endpoints is a recipe for failure.

### The Rest.li Protocol and Partial Updates

LinkedIn's API is built on Rest.li, an open-source REST framework that uses a highly specific syntax for partial updates. Standard REST assumes you send a `PATCH` request with the fields you want to change.

LinkedIn requires a `POST` request to the resource endpoint, accompanied by an `X-RestLi-Method: PARTIAL_UPDATE` header. The payload itself cannot just be the updated fields. It must be a specifically formatted patch object using `$set` operators.

For example, to pause a campaign, an LLM might intuitively try to send `{"status": "PAUSED"}`. LinkedIn will reject this. The required payload is `{"patch": {"$set": {"status": "PAUSED"}}}`. Pushing these framework-specific structural quirks into your LLM's context window eats up tokens and vastly increases the surface area for hallucinations.

### Complex Compound Keys

Certain LinkedIn endpoints require compound keys rather than simple IDs. For example, to manage an ad account user, the ID is a compound key comprising both the account URN and the user URN, formatted as `(account:urn%3Ali%3AsponsoredAccount%3A123,user:urn%3Ali%3Aperson%3Aabc)`. The LLM must construct this string perfectly, ensuring the internal URNs are URL-encoded before inserting them into the compound structure. 

By routing calls through Truto's Proxy APIs, these complexities are abstracted. Truto handles the schema translations, URL encoding requirements, and header injection. The agent simply receives clean, standard JSON schemas defining exactly what inputs are required.

## Hero Tools for LinkedIn Agents

Truto provides a comprehensive set of [AI-ready tools](https://truto.one/best-unified-api-for-llm-function-calling-ai-agent-tools-2026/) by exposing the Proxy APIs available on the LinkedIn integration. When you query the `/tools` endpoint for a connected LinkedIn account, you receive strict JSON schemas defining the operations the agent can perform. 

Here are the highest-leverage tools you can bind to your agent to automate LinkedIn ad operations.

### Create a Matched Audience (DMP Segment)

**Tool name:** `create_a_linked_in_dmp_segment`

Matched Audiences (DMP Segments) are the foundation of targeted B2B advertising on LinkedIn. This tool allows the agent to programmatically provision a new segment container into which it can later batch-upload user or company records.

Contextual usage notes: The agent must specify the segment name, the ad account URN, the segment type (such as `USER` or `COMPANY`), and the destination. Truto handles the structural formatting required by LinkedIn.

> "We have a new list of target accounts from the Q3 webinar. Create a new Matched Audience segment named 'Q3 Webinar Attendees' in our primary ad account."

### Batch Add Users to a DMP Segment

**Tool name:** `create_a_linked_in_dmp_segments_user`

Once a segment is created, this tool enables the agent to populate it by adding users in batches. This bypasses the need for marketers to manually upload CSV files into the Campaign Manager UI.

Contextual usage notes: The tool requires the `dmp_segment_id`. The payload accepts an array of elements specifying the action (`ADD` or `REMOVE`) and the hashed user identifiers (typically SHA-256 hashed email addresses). The agent can automatically process a list of emails, instruct a code execution tool to hash them, and pass them to this tool.

> "Take the list of 500 emails from the webinar export, ensure they are hashed correctly, and batch add them to the 'Q3 Webinar Attendees' segment."

### Create an Ad Campaign

**Tool name:** `create_a_linked_in_ad_campaign`

This tool allows the agent to spin up net-new advertising campaigns. It handles the complex payload requirements for defining campaign constraints, budgets, and targeting criteria.

Contextual usage notes: The agent must provide the parent ad account, the campaign group URN, the name, type, cost type (e.g., CPC or CPM), daily or total budget, and targeting criteria. Because Truto normalizes the schema, the agent does not need to memorize Rest.li structures - it just fills out the JSON schema provided by the `/tools` endpoint.

> "Launch a new CPC campaign under the 'Q4 Promos' group targeting the 'Q3 Webinar Attendees' segment. Set the daily budget to $50 and the status to active."

### Create an Ad Creative

**Tool name:** `create_a_linked_in_creative`

Creating creatives programmatically allows agents to automate A/B testing and rapidly deploy ad variations. This tool binds an existing piece of content (like a company update or a direct sponsored post) to a specific campaign.

Contextual usage notes: The agent needs the campaign URN, the content reference (the post URN), and the intended status. If the agent needs to generate the post first, it can call the `create_a_linked_in_image_ad` or `create_a_linked_in_video_ad` tool prior to this step.

> "Sponsor the latest company update we posted yesterday. Create a new creative for it in the 'Q4 Promos' campaign and set it to ACTIVE."

### Update an Ad Campaign

**Tool name:** `update_a_linked_in_ad_campaign_by_id`

Agents need the ability to optimize inflight campaigns. This tool allows the agent to pause poor performers, increase budgets on winners, or adjust targeting criteria on the fly.

Contextual usage notes: This tool abstracts LinkedIn's `X-RestLi-Method PARTIAL_UPDATE` complexity. The agent simply provides the `id` of the campaign, the `ad_account_id`, and the logical update payload (e.g., `{"status": "PAUSED"}`). Truto translates this into the heavily nested `$set` patch structure LinkedIn requires under the hood.

> "Check the performance of the 'Q4 Promos' campaign. If the CPC is above $15, pause the campaign immediately to stop spend."

### Fetch Ad Analytics

**Tool name:** `list_all_linked_in_ad_analytics`

An autonomous marketing agent is useless without a feedback loop. This tool retrieves account, campaign, or creative-level statistics, including spend, clicks, impressions, and conversions.

Contextual usage notes: The agent must define the `pivot` (e.g., `CAMPAIGN` or `CREATIVE`), the `timeGranularity` (e.g., `DAILY`), and the `dateRange`. The agent can use this data to inform future tool calls, creating a self-optimizing loop.

> "Pull the daily analytics for all active campaigns over the last 7 days. Summarize the total spend, CTR, and average CPC per campaign."

To see the complete tool inventory and schema details, visit the [LinkedIn integration page](https://truto.one/integrations/detail/linkedin).

## Workflows in Action

Connecting these tools to an LLM unlocks autonomous workflows that normally require hours of manual work in the LinkedIn Campaign Manager UI. Here are two concrete scenarios showing how an agent chains these operations together.

### Scenario 1: Autonomous Audience Onboarding and Campaign Launch

Marketing teams often struggle with the latency between acquiring new leads (e.g., from a webinar) and targeting them with ads. An AI agent can compress this to seconds.

> "We just finished the enterprise security webinar. Here is an array of 200 attendee email hashes. Create a new DMP segment for them, add the users, and launch a $100/day retargeting campaign using our existing 'Security Ebook' creative."

1. **`create_a_linked_in_dmp_segment`**: The agent creates the container, naming it "Enterprise Security Webinar Attendees" and receives the new segment URN.
2. **`create_a_linked_in_dmp_segments_user`**: The agent issues a batch create operation, mapping the provided hashes to the `ADD` action for the new segment URN.
3. **`create_a_linked_in_ad_campaign`**: The agent provisions the campaign, applying the new segment URN to the targeting criteria and setting the budget.
4. **`create_a_linked_in_creative`**: The agent attaches the specified 'Security Ebook' post reference to the newly created campaign.

The user receives a confirmation that the audience is syncing and the retargeting campaign is live, with zero manual data entry.

```mermaid
sequenceDiagram
    participant User as User Prompt
    participant Agent as AI Agent
    participant Truto as Truto Tools API
    participant Upstream as LinkedIn API

    User->>Agent: "Create segment, add users, launch campaign"
    Agent->>Truto: Call create_a_linked_in_dmp_segment
    Truto->>Upstream: POST /rest/dmpSegments
    Upstream-->>Truto: Return segment URN
    Truto-->>Agent: Return segment URN
    
    Agent->>Truto: Call create_a_linked_in_dmp_segments_user
    Truto->>Upstream: POST /rest/dmpSegments/{id}/users (BATCH_CREATE)
    Upstream-->>Truto: Return 200 OK
    Truto-->>Agent: Return success status
    
    Agent->>Truto: Call create_a_linked_in_ad_campaign
    Truto->>Upstream: POST /rest/adCampaigns
    Upstream-->>Truto: Return campaign URN
    Truto-->>Agent: Return campaign URN
    
    Agent->>User: "Campaign launched successfully."
```

### Scenario 2: Performance Monitoring and Creative Rotation

Ad fatigue destroys ROI. Agents can monitor campaigns on a schedule and proactively rotate creatives based on statistical thresholds.

> "Analyze our active creatives in the 'Q4 Enterprise' campaign. If any creative has a CTR below 0.5% after 10,000 impressions, pause it and alert me."

1. **`list_all_linked_in_ad_analytics`**: The agent fetches the analytics with a pivot on `CREATIVE` for the specified campaign.
2. **Reasoning Loop**: The agent parses the JSON response, filtering for creatives matching the condition (CTR < 0.005 AND impressions > 10000).
3. **`update_a_linked_in_creative_by_id`**: For each underperforming creative, the agent calls the update tool. Truto translates this into the necessary `X-RestLi-Method PARTIAL_UPDATE` patch payload to set the status to `PAUSED`.

The user gets an automated report detailing exactly which creatives were killed to save budget.

```mermaid
flowchart TD
    A["Fetch Ad Analytics<br>(pivot: CREATIVE)"] --> B{"Evaluate CTR<br>and Impressions"}
    B -->|CTR < 0.5%| C["Call update_creative<br>status: PAUSED"]
    B -->|CTR >= 0.5%| D["Take no action"]
    C --> E["Return execution summary<br>to user"]
```

## Building Multi-Step Workflows

To build these multi-step workflows, you need to retrieve the tool schemas from Truto and bind them to your agent. Truto's architecture is framework-agnostic. We provide an endpoint (`GET /integrated-account/<id>/tools`) that returns the Proxy APIs as LLM-ready tool definitions. 

If you are using LangChain, our [truto-langchainjs-toolset](https://github.com/trutohq/truto-langchainjs-toolset) package handles the boilerplate of fetching these schemas and converting them into LangChain's native `StructuredTool` format.

### Handling Rate Limits

A critical architectural note for autonomous agents: standardizing schemas is only half the battle. AI agents work incredibly fast and can easily trigger rate limits on the upstream LinkedIn API.

**Factual note on rate limits:** Truto does not retry, throttle, or apply backoff on rate limit errors. When an upstream API returns HTTP 429, Truto passes that error directly to the caller. Truto normalizes the upstream rate limit info into standardized headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) per the IETF spec. 

The caller (your agent framework or interceptor layer) is strictly responsible for inspecting these headers and implementing [retry/backoff logic](https://truto.one/how-to-handle-third-party-api-rate-limits-when-an-ai-agent-is-scraping-data/). Do not expect Truto to absorb or automatically retry rate limit errors.

Here is how you orchestrate the agent loop in TypeScript, assuming your execution layer handles the 429 backoff:

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";

async function runLinkedInAdAgent() {
  // 1. Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });

  // 2. Fetch LinkedIn tools for this specific account
  const truto = new TrutoToolManager(process.env.TRUTO_API_KEY!);
  const linkedInTools = await truto.getTools(
    process.env.LINKEDIN_INTEGRATED_ACCOUNT_ID!
  );

  // 3. Define the agent prompt
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are a B2B advertising agent. You manage LinkedIn campaigns, DMP segments, and creatives. Ensure URNs are passed accurately to your tools. If a tool fails, report the error."],
    ["human", "{input}"],
    new MessagesPlaceholder("agent_scratchpad"),
  ]);

  // 4. Bind tools to the agent
  const agent = await createOpenAIToolsAgent({
    llm,
    tools: linkedInTools,
    prompt,
  });

  const executor = new AgentExecutor({
    agent,
    tools: linkedInTools,
    maxIterations: 5,
  });

  // 5. Execute a complex workflow
  const result = await executor.invoke({
    input: "Check our active creatives. If any creative has a CTR below 0.5% after 10,000 impressions, pause it immediately.",
  });

  console.log(result.output);
}

runLinkedInAdAgent().catch(console.error);
```

In this execution, the agent evaluates the prompt, selects the `list_all_linked_in_ad_analytics` tool, inspects the returned payload, and subsequently calls `update_a_linked_in_creative_by_id` if the conditions are met. All URL encoding, schema normalization, and Rest.li patch generation are handled silently by Truto's API proxy layer.

> Ready to give your AI agents reliable access to LinkedIn, Salesforce, HubSpot, and 100+ other SaaS APIs?
>
> [Talk to us](https://truto.one/book-a-demo/)

## Next Steps for Agentic Integrations

Building an AI agent requires extreme reliability from the [underlying infrastructure](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/). Standard point-to-point integrations force your LLM to deal with provider-specific quirks, unpredictable schemas, and undocumented rate limit behaviors. By routing your agent's interactions through a [unified tool layer](https://truto.one/best-unified-api-for-llm-function-calling-ai-agent-tools-2026/), you drastically reduce hallucinations and prevent the agent from getting stuck resolving API errors.

Stop writing defensive integration code and start focusing on your agent's core reasoning loops. Build the integration once, bind the tools, and let your agent operate freely.
