DEV Community

Cover image for Building a Complete LinkedIn Automation Agent with ConnectSafely.AI MCP
AMAAN SARFARAZ
AMAAN SARFARAZ

Posted on

Building a Complete LinkedIn Automation Agent with ConnectSafely.AI MCP

From Months of Development to Full LinkedIn Automation in 1 Hour

Building comprehensive LinkedIn automation is a massive undertaking. You need separate tools for groups, posts, profiles, messaging, account managementβ€”each with their own authentication, rate limiting, and maintenance burden. This typically takes 3-6 months to build properly.

That's where ConnectSafely.AI changes everything.

In this tutorial, I'll show you how I got instant access to 20+ production-ready LinkedIn tools through ConnectSafely.AI's MCP server and built a complete automation agent in under an hour.


What is ConnectSafely.AI?

ConnectSafely.AI is a comprehensive LinkedIn automation platform that provides complete LinkedIn automation through the Model Context Protocol (MCP).

One API key gives you instant access to:

  • βœ… 20+ LinkedIn Tools - Complete automation coverage
  • βœ… All Operations - Groups, posts, profiles, messaging, accounts
  • βœ… MCP Server - Industry-standard integration protocol
  • βœ… Production-Ready - 99.9% uptime across all tools
  • βœ… Zero Maintenance - ConnectSafely handles all updates
  • βœ… Single Connection - One MCP endpoint for everything

Get started: https://connectsafely.ai/docs/integrations/mcp-server


Why I Chose ConnectSafely.AI

❌ The Traditional Approach:

// Building each tool separately...
async function getGroupMembers() { /* weeks of code */ }
async function searchPosts() { /* more weeks */ }
async function sendMessage() { /* even more weeks */ }
async function checkProfile() { /* you get it... */ }
// ... and 16 more tools to build
// ... plus authentication for each
// ... plus rate limiting for each
// ... plus maintenance when LinkedIn changes
Enter fullscreen mode Exit fullscreen mode

βœ… With ConnectSafely.AI:

// Get ALL tools instantly
import { MCPClient } from "@mastra/mcp";

const mcp = new MCPClient({
  servers: {
    connectsafely: {
      url: new URL(`https://mcp.connectsafely.ai/?apiKey=${apiKey}`)
    }
  }
});

const tools = await mcp.getTools();
// 20+ LinkedIn tools ready to use! πŸŽ‰
Enter fullscreen mode Exit fullscreen mode

Time saved: 3-6 months β†’ 1 hour

Tools available: 20+ complete operations

Maintenance: Zero


What We're Building

A complete LinkedIn automation agent with full access to:

  • πŸ”΅ Group Operations - Member extraction, analysis
  • πŸ“ Post Operations - Search, scraping, engagement
  • πŸ‘€ Profile Operations - Data fetching, relationships
  • πŸ’¬ Messaging - Direct messages, InMail, connections
  • πŸ“Š Account Management - Status, warmup, activity

Example Usage:

# Group operations
> Get active members from AI Engineers group

# Post operations
> Search for top posts about "automation" from last week
> Comment on trending AI posts

# Profile operations
> Get profile data for these LinkedIn URLs
> Check if I'm connected to these profiles

# Messaging
> Send personalized connection requests to decision makers

# Account management
> Check my account health and recent activity

# Complex workflows
> Find premium members in SaaS groups, verify messaging support,
  and send personalized InMails
Enter fullscreen mode Exit fullscreen mode

Architecture: Complete Automation via ConnectSafely

User Input (Natural Language)
    ↓
AI Agent (Gemini 2.5 Flash)
    ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  ConnectSafely.AI MCP Server             β”‚
β”‚  (Complete LinkedIn Automation)          β”‚
β”‚                                          β”‚
β”‚  βœ“ Group Operations (3+ tools)          β”‚
β”‚  βœ“ Post Operations (7+ tools)           β”‚
β”‚  βœ“ Profile Operations (4+ tools)        β”‚
β”‚  βœ“ Messaging & Networking (3+ tools)    β”‚
β”‚  βœ“ Account Management (3+ tools)        β”‚
β”‚                                          β”‚
β”‚  ALL via single MCP connection!         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    ↓
LinkedIn API (handled by ConnectSafely)
    ↓
Results β†’ User
Enter fullscreen mode Exit fullscreen mode

ConnectSafely.AI handles everything:

  • Authentication for all tools
  • Rate limiting across all operations
  • Data normalization for all responses
  • Error handling for all requests
  • Updates for all tools

Step 1: Get ConnectSafely.AI API Key

Sign up at ConnectSafely.AI and get your API key.

This single key unlocks ALL 20+ LinkedIn tools.


Step 2: Project Setup

git clone https://github.com/ConnectSafelyAI/agentic-framework-examples/tree/remote-mcp-integration/extract-linkedin-premium-users-from-linkedin-groups/mcp
cd extract-linkedin-premium-users-from-linkedin-groups/mcp

bun install

touch .env
Enter fullscreen mode Exit fullscreen mode

Add to .env:

# Get from https://connectsafely.ai/docs/integrations/mcp-server
CONNECTSAFELY_API_KEY=your_key_here

# Get from https://aistudio.google.com/api-keys
GOOGLE_GENERATIVE_AI_API_KEY=your_gemini_key

GOOGLE_REFRESH_TOKEN=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
Enter fullscreen mode Exit fullscreen mode

Step 3: Connect to ConnectSafely (Get ALL Tools)

Create src/mcp/connectsafely-client.ts:

import { MCPClient } from "@mastra/mcp";

// Connect to ConnectSafely MCP - get ALL tools
export const connectSafelyMCP = new MCPClient({
  servers: {
    connectsafely: {
      url: new URL(
        `https://mcp.connectsafely.ai/?apiKey=${process.env.CONNECTSAFELY_API_KEY}`
      ),
    },
  },
});

// Get complete LinkedIn toolkit from ConnectSafely
export async function getConnectSafelyTools() {
  try {
    const tools = await connectSafelyMCP.getTools();
    console.log(`βœ… Connected to ConnectSafely MCP`);
    console.log(`πŸ“‹ Loaded ${Object.keys(tools).length} LinkedIn tools\n`);

    // Log available tools
    Object.keys(tools).forEach((name, i) => {
      console.log(`   ${i + 1}. ${name}`);
    });

    return tools;
  } catch (error) {
    console.error("❌ Failed to connect:", error.message);
    throw error;
  }
}

export async function disconnectConnectSafely() {
  await connectSafelyMCP.disconnect();
}
Enter fullscreen mode Exit fullscreen mode

You now have access to ALL ConnectSafely tools!


Step 4: Create AI Agent with Complete Toolkit

Create src/agent/linkedin-agent.ts:

import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { LibSQLStore } from "@mastra/libsql";
import { getConnectSafelyTools } from "../mcp/connectsafely-client.js";

export async function createLinkedInAgent() {
  // Get ALL tools from ConnectSafely
  const linkedInTools = await getConnectSafelyTools();

  const agent = new Agent({
    name: "Complete LinkedIn Automation Agent",
    model: "google/gemini-2.5-flash",

    instructions: `
You are a LinkedIn automation expert with FULL ACCESS to ConnectSafely's 
complete LinkedIn automation toolkit via MCP.

YOU HAVE ACCESS TO ALL TOOLS for:

GROUP OPERATIONS:
- Extract members from any group
- Analyze group activity
- Filter by premium status, verified status, industry, etc.

POST OPERATIONS:
- Search posts with advanced filters
- Scrape post details and engagement metrics
- Get all comments and replies
- Comment on posts
- React to posts (like, praise, appreciate, etc.)
- Track post performance

PROFILE OPERATIONS:
- Fetch complete profile data
- Get profile activity and posts
- Check relationship status
- Follow/unfollow profiles
- Verify messaging capabilities

MESSAGING & NETWORKING:
- Send direct messages
- Send InMail (premium messaging)
- Send connection requests
- Manage conversations

ACCOUNT MANAGEMENT:
- Monitor account status
- Track activity history
- Check warmup status
- Manage account health

Use ANY of these tools to accomplish the user's LinkedIn automation goals.
Be creative and combine tools for complex workflows.
    `,

    tools: linkedInTools, // ALL ConnectSafely tools

    memory: new Memory({
      storage: new LibSQLStore({
        url: "file:./mastra.db",
      }),
    }),
  });

  return agent;
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Create Interactive CLI

Create src/index.ts:

import "dotenv/config";
import readline from "readline";
import { createLinkedInAgent } from "./agent/linkedin-agent.js";
import { disconnectConnectSafely } from "./mcp/connectsafely-client.js";

async function main() {
  console.log("πŸš€ Initializing Complete LinkedIn Automation Agent...\n");

  const agent = await createLinkedInAgent();
  console.log("\nβœ… Agent ready with ALL ConnectSafely tools!\n");

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  console.log("πŸ’¬ Type 'list-tools' to see all available tools");
  console.log("πŸ’¬ Type your automation requests or 'exit' to quit\n");

  function loop() {
    rl.question("> ", async (input) => {
      if (input.toLowerCase() === "exit") {
        await disconnectConnectSafely();
        rl.close();
        process.exit(0);
      }

      if (input.toLowerCase() === "list-tools") {
        console.log("\nπŸ“‹ Available ConnectSafely Tools:\n");
        // Agent will list all available tools
        await agent.generate("List all available tools");
        loop();
        return;
      }

      if (!input.trim()) {
        loop();
        return;
      }

      try {
        const result = await agent.generate(input);
        console.log(`\n${result.text}\n`);
      } catch (error) {
        console.error(`\n❌ Error: ${error.message}\n`);
      }

      loop();
    });
  }

  loop();
}

main();
Enter fullscreen mode Exit fullscreen mode

Step 6: Run It - Complete Automation!

npm start

> list-tools

πŸ“‹ Available ConnectSafely Tools:

GROUP OPERATIONS:
1. Get_group_members_by_group_URL
2. Get_group_members_by_group_ID

POST OPERATIONS:
3. Search_posts_by_keyword
4. Scrape_LinkedIn_post_details
5. Get_comments_from_a_post
6. Get_all_comments_from_a_post
7. Comment_on_a_LinkedIn_post
8. React_to_a_LinkedIn_post
9. Reply_to_a_comment
10. Get_latest_posts_from_a_profile

PROFILE OPERATIONS:
11. Fetch_LinkedIn_profile_information
12. Check_relationship_status_with_profile
13. Follow_or_unfollow_a_LinkedIn_profile
14. Check_if_profile_supports_email_messaging

MESSAGING & NETWORKING:
15. Send_a_LinkedIn_message
16. Send_a_connection_request

ACCOUNT MANAGEMENT:
17. Get_account_status
18. Get_account_warmup_status
19. Get_account_activity_history

... and more!

> Search for posts about "AI automation" from last week

Agent: Searching LinkedIn posts using ConnectSafely...

[Tool: Search_posts_by_keyword - ConnectSafely]

βœ“ Found 23 posts about "AI automation" from last 7 days
βœ“ Top post: 456 likes, 89 comments
βœ“ Average engagement: 124 interactions/post

> Get all comments from the top post

Agent: Fetching comments using ConnectSafely...

[Tool: Get_all_comments_from_a_post - ConnectSafely]

βœ“ Retrieved 89 comments
βœ“ Top commenter: @username (5 comments)
βœ“ Most discussed: AI tools and automation platforms

> Check my account status

Agent: Checking account health via ConnectSafely...

[Tool: Get_account_status - ConnectSafely]

βœ“ Account status: Active
βœ“ Health: Good
βœ“ Warmup: Complete
βœ“ Recent activity: Normal

> exit

πŸ”Œ Disconnected from ConnectSafely
πŸ‘‹ Goodbye!
Enter fullscreen mode Exit fullscreen mode

Complete ConnectSafely.AI Tool Catalog

πŸ”΅ Group Operations (ConnectSafely)

// Member extraction
Get_group_members_by_group_URL
Get_group_members_by_group_ID

// Features:
- Extract all members from any LinkedIn group
- Advanced filtering (premium, verified, industry, location)
- Pagination for large groups (1000+ members)
- Rich member data (profile, headline, company, etc.)
Enter fullscreen mode Exit fullscreen mode

Use cases:

  • Lead generation
  • Market research
  • Competitor analysis
  • Network building

πŸ“ Post Operations (ConnectSafely)

// Search & discovery
Search_posts_by_keyword
Scrape_LinkedIn_post_details
Get_latest_posts_from_a_profile

// Comment management
Get_comments_from_a_post
Get_all_comments_from_a_post
Reply_to_a_comment

// Engagement
Comment_on_a_LinkedIn_post
React_to_a_LinkedIn_post

// Features:
- Advanced search filters (date, sort, author job titles)
- Complete engagement metrics
- Comment pagination
- Multiple reaction types
- Post performance tracking
Enter fullscreen mode Exit fullscreen mode

Use cases:

  • Content research
  • Social listening
  • Engagement automation
  • Trend analysis

πŸ‘€ Profile Operations (ConnectSafely)

// Data fetching
Fetch_LinkedIn_profile_information
Get_latest_posts_from_a_profile

// Relationship management
Check_relationship_status_with_profile
Follow_or_unfollow_a_LinkedIn_profile
Check_if_profile_supports_email_messaging

// Features:
- Complete profile data (bio, experience, education, skills)
- Contact information (when available)
- Activity history
- Connection degree
- Messaging capability verification
Enter fullscreen mode Exit fullscreen mode

Use cases:

  • Profile enrichment
  • CRM integration
  • Prospect research
  • Relationship tracking

πŸ’¬ Messaging & Networking (ConnectSafely)

// Communication
Send_a_LinkedIn_message
Send_a_connection_request

// Features:
- Direct messaging (normal + InMail)
- Personalized connection requests
- Custom message templates
- Message type detection
- Delivery confirmation
Enter fullscreen mode Exit fullscreen mode

Use cases:

  • Outreach campaigns
  • Network building
  • Sales prospecting
  • Relationship nurturing

πŸ“Š Account Management (ConnectSafely)

// Monitoring
Get_account_status
Get_account_warmup_status
Get_account_activity_history

// Features:
- Real-time account health
- Warmup progress tracking
- Activity history and patterns
- Safety status monitoring
- Compliance checking
Enter fullscreen mode Exit fullscreen mode

Use cases:

  • Account health monitoring
  • Compliance tracking
  • Activity auditing
  • Risk management

Real-World Workflows

1. Complete Lead Pipeline

> Find active members in "SaaS Founders" group who post regularly,
  get their profiles, check if we're connected, verify messaging support,
  and send personalized connection requests to qualified leads
Enter fullscreen mode Exit fullscreen mode

ConnectSafely tools used:

  1. Get_group_members_by_group_URL
  2. Get_latest_posts_from_a_profile
  3. Check_relationship_status_with_profile
  4. Check_if_profile_supports_email_messaging
  5. Send_a_connection_request

Result: Complete automated lead pipeline

2. Content Intelligence System

> Search for trending posts about AI, get all comments,
  analyze top commenters, check their profiles,
  and identify potential collaboration partners
Enter fullscreen mode Exit fullscreen mode

ConnectSafely tools used:

  1. Search_posts_by_keyword
  2. Get_all_comments_from_a_post
  3. Fetch_LinkedIn_profile_information
  4. Check_relationship_status_with_profile

Result: Automated content research and network discovery

3. Competitor Monitoring

> Get all recent posts from @competitor account,
  analyze engagement patterns, extract active commenters,
  check their profiles and industries
Enter fullscreen mode Exit fullscreen mode

ConnectSafely tools used:

  1. Get_latest_posts_from_a_profile
  2. Scrape_LinkedIn_post_details
  3. Get_all_comments_from_a_post
  4. Fetch_LinkedIn_profile_information

Result: Comprehensive competitive intelligence

4. Network Growth Automation

> Check my account status, find premium members in target groups,
  verify we're not connected, send personalized requests,
  and track my activity
Enter fullscreen mode Exit fullscreen mode

ConnectSafely tools used:

  1. Get_account_status
  2. Get_group_members_by_group_URL
  3. Check_relationship_status_with_profile
  4. Send_a_connection_request
  5. Get_account_activity_history

Result: Automated, compliant network building


Performance Metrics

ConnectSafely.AI Performance

Metric Value
Tools Available 20+
Setup Time < 5 minutes
Uptime 99.9%
Response Time < 2 seconds
Rate Limit 60 req/min
Daily Operations 1000+

My Automation Results

Operation Time Success Tools Used
Complete lead pipeline 15 sec 100% 5 tools
Content intelligence 8 sec 100% 4 tools
Competitor analysis 12 sec 100% 4 tools
Network automation 10 sec 100% 5 tools

All powered by ConnectSafely.AI's complete toolkit!


Cost Analysis

Building All Tools vs ConnectSafely

Aspect DIY (All Tools) ConnectSafely.AI
Development $50,000-$100,000 (3-6 months) $0 (1 hour)
Tools Built 5-10 typical 20+ included
Maintenance $2,000/month $0
Infrastructure $500/month Included
Monitoring $200/month Included
Updates Manual for each Auto for all

Why ConnectSafely.AI Wins

βœ… Complete Coverage

  • 20+ tools vs building 5-10
  • All operations in one place
  • Single integration for everything

βœ… Zero Maintenance

  • Automatic updates for all tools
  • Breaking changes handled by ConnectSafely
  • Focus on product not infrastructure

βœ… Enterprise Quality

  • 99.9% uptime for all tools
  • Built-in safety across all operations
  • Production-ready from day one

βœ… Developer Experience

  • MCP standard integration
  • One API key for everything
  • Comprehensive docs for all tools

Getting Started

# 1. Sign up
https://connectsafely.ai/docs/integrations/mcp-server

# 2. Install
npm install @mastra/mcp @mastra/core

# 3. Connect (3 lines!)
const mcp = new MCPClient({
  servers: {
    connectsafely: {
      url: new URL(`https://mcp.connectsafely.ai/?apiKey=${key}`)
    }
  }
});

# 4. Get ALL tools
const tools = await mcp.getTools();

# 5. Build anything!
Enter fullscreen mode Exit fullscreen mode

Time to complete automation: 30 minutes


Common Questions

Q: Do I get all 20+ tools with one API key?

A: Yes! One key = full toolkit

Q: What if I only need specific tools?

A: You get access to all tools, use what you need

Q: Does ConnectSafely handle rate limiting?

A: Yes, automatically across all tools

Q: What about account safety?

A: Built-in warmup and safety for all operations

Q: Can I build commercial products?

A: Yes, all plans support commercial use


Resources

ConnectSafely.AI

Additional


Conclusion

Complete LinkedIn automation used to take 3-6 months to build. With ConnectSafely.AI, you get the full toolkit in under an hour.

What I got with ConnectSafely.AI:

  • βœ… 20+ production-ready tools
  • βœ… Complete LinkedIn automation coverage
  • βœ… Single MCP connection
  • βœ… Zero maintenance
  • βœ… Enterprise reliability
  • βœ… Saved months of development

Stop building tools one by one. Get complete automation instantly.

Get your API key: https://connectsafely.ai/docs/integrations/mcp-server


Your Turn

Building LinkedIn automation? What tools do you need most?

Trying ConnectSafely.AI? Share your experience!

Questions? Drop a comment below!


Top comments (0)