Give your LangGraph agent real-time web data with Apify

Connect a LangGraph agent to Apify through the official langchain-apify integration or Apify MCP Server, and give it real-time web search, scraping, and social media data.

The usefulness of a LangGraph agent workflow largely depends on the quality and scope of the tools it can access. Apify extends LangGraph agents with real-time web data.

In this tutorial, you'll learn how to connect LangGraph to Apify through the official LangChain integration and via MCP.

Apify support for LangGraph

Apify is a marketplace of ready-to-run tools for AI. It provides tools for accessing web data and automating tasks such as web search, social media monitoring, lead generation, e-commerce data extraction, and more.

At the core of Apify are Actors, serverless programs that perform specific tasks, such as scraping websites, running browser automation, or powering AI workflows.

LangGraph agents can use Apify Actors in two main ways:

  1. Through the official langchain-apify integration.
  2. Via Apify MCP Server.

Official Apify LangGraph integration

The Apify LangGraph integration provides LangChain-compatible tools that wrap specific Actors behind simplified input schemas. This way, LangGraph agents can call Actors without needing to know the underlying input schema.

langchain-apify provides 19 dedicated tools across three categories:

  • APIFY_CORE_TOOLS: for running Actors and tasks, scraping URLs, and retrieving dataset items
  • APIFY_SEARCH_TOOLS: for web search, crawling, maps, YouTube, and e-commerce data
  • APIFY_SOCIAL_TOOLS: for platforms such as Instagram, LinkedIn, TikTok, Facebook, and X

You can give an agent individual tools, an entire tool bundle, or use ApifyActorsTool to run an Actor that doesn’t have a dedicated tool.

Apify MCP Server with LangGraph

Apify MCP Server provides a programmatic interface for AI agents to discover and use Apify tools through the Model Context Protocol. It exposes thousands of Apify Actors as tools, allowing an agent to discover and use Actors on the fly.

The MCP server provides tools for:

  • Actor discovery: search Apify Store and retrieve Actor details and schemas
  • Actor execution: run Actors and retrieve their results
  • Web access: call tools for web scraping, such as RAG Web Browser and Web Fetch
  • Storage: access datasets generated by Actor runs
  • Documentation: search and retrieve Apify documentation
  • Tasks and schedules: manage saved Actor tasks and scheduled runs

The server supports stdio via @apify/actors-mcp-server as well as Streamable HTTP. Supported authentication methods include OAuth and API token.

Common setup steps

Before getting started with the LangGraph + Apify integration, whether via the official integration or MCP, you need to complete a few common tasks first.

Prerequisites

Make sure you have:

Basic knowledge of the following topics will also be useful:

Step #1: Install the libraries

In your Python project, with the virtual environment activated, run:

pip install langchain langchain-openai langchain-apify python-dotenv

This installs the required dependencies:

Note: You don’t need to install langgraph separately for this example. The langchain package installs langgraph as a dependency, as its high-level API helps you build LangGraph agents.

Step #2: Retrieve the Apify API key

Both langchain-apify and the Apify MCP server can use an Apify API token for authentication. To get your API token:

  1. Log in to Apify Console
  2. Go to Settings > API & Integrations
  3. In the API tokens section, copy your token using the “copy to clipboard” button
Retrieving your Apify API token

Store your API token securely. You'll need it in the next steps.

Note: Apify MCP Server supports agentic payments via AGI, direct x402, or Skyfire, so that you can pay for Actor runs without an Apify API token.

Step #3: Configure environment variables

Your LangGraph agent workflow relies on Apify and OpenAI, so you must provide an Apify API token and an OpenAI API key. Never hardcode API keys in your source code. Store them as environment variables instead.

Create a .env file in your project directory and populate it with:

OPENAI_API_KEY="<YOUR_OPENAI_API_KEY>"
APIFY_TOKEN="<YOUR_APIFY_TOKEN>"

Replace <YOUR_OPENAI_API_KEY> and <YOUR_APIFY_TOKEN> with your actual OpenAI API key and Apify API token.

To load these variables from the .env file, import load_dotenv() from python-dotenv and call it at the beginning of your Python file:

from dotenv import load_dotenv

# Load API keys from .env
load_dotenv()

You don't need to load the API keys manually in your agent code. langchain-openai reads OPENAI_API_KEY, and langchain-apify reads APIFY_TOKEN from the environment automatically.

How to build a LangGraph agent workflow with Apify

In this guided section, you'll see how to create a LangGraph agent that uses Apify LangChain tools for web search, social media data extraction, and more.

Step #4: Configure the AI model

Use langchain-openai to configure the OpenAI model that your LangGraph agent will use:

from langchain_openai import ChatOpenAI

# Define the OpenAI model that will serve as the agent's brain
model = ChatOpenAI(model="gpt-5.4-mini")

This sets gpt-5.4-mini, but you can replace it with another OpenAI model based on your requirements.

If you prefer to use a different model provider, see the LangChain documentation for integrations with Anthropic, Google, or other providers.

Step #5: Import the Apify LangChain tools

Begin by importing the desired tool sets from langchain-apify:

from langchain_apify import (
    APIFY_SEARCH_TOOLS,
    APIFY_SOCIAL_TOOLS,
)

This gives you access to the Apify search (6 tools) and social (7 tools) tool bundles.

To get the Apify tools ready for LangGraph, you first need to instantiate each tool class:

tools = [tool_cls() for tool_cls in (APIFY_SEARCH_TOOLS + APIFY_SOCIAL_TOOLS)]

The above line loops through the tool classes in both sets, creates an instance of each class, and stores them in the tools list.

Alternatively, when you need granular control, you can import individual tools:

from langchain_apify import (
    ApifyRAGWebBrowserTool,
    ApifyLinkedInProfileDetailTool,
    # ...
)

Then, instantiate the tools you want to use:

browser = ApifyRAGWebBrowserTool()
linkedin = ApifyLinkedInProfileDetailTool()

tools = [browser, linkedin]

Step #6: Define the LangGraph agent

Add a system prompt that tells the agent its role and how to behave:

agent_system_prompt = (
    "You are a helpful research assistant. Use Apify tools when you need to "
    "fetch web or social media data."
)

Next, create the LangGraph agent by using the model, tools, and system prompt:

from langchain.agents import create_agent

# Create the LangGraph agent with the configured model, tools, and system prompt.
agent = create_agent(
    model=model,
    tools=tools,
    system_prompt=agent_system_prompt,
)

create_agent() is the standard API for creating agents in LangChain v1.0+. It provides a high-level interface for building agents with LangGraph and replaces the now-deprecated langgraph.prebuilt.create_react_agent() API.

agent now stores a LangGraph ReAct agent, which can reason about a task, call tools, observe their results, and iterate until it can provide an answer.

Step #7: Run the agent

To verify that the agent can use the Apify tools for web search and social media data retrieval, define a test prompt like this:

user_prompt = (
    "Research Nike's social media presence on TikTok, LinkedIn, and Facebook.\n"
    "For each platform, retrieve the available profile information and recent relevant data. "
    "Return a report summarizing the key information, including the profile URL, "
    "follower count, and other relevant metrics."
)

Pass the prompt to the agent and stream its execution:

for update in agent.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": user_prompt,
            }
        ]
    },
    stream_mode="updates",
):
    for node_name, node_update in update.items():
        print(f"\n{'=' * 20} {node_name} {'=' * 20}")

        if "messages" not in node_update:
            continue

        for message in node_update["messages"]:
            message.pretty_print()

This lets you see the agent's responses, including the tool calls it makes and their results.

Step #8: Put it all together

This is the final Python script for your LangGraph agent workflow with Apify tools:

# pip install langchain langchain-apify langchain-openai python-dotenv

from dotenv import load_dotenv
from langchain_apify import (
    APIFY_SEARCH_TOOLS,
    APIFY_SOCIAL_TOOLS,
)
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent

# Load API keys from .env
load_dotenv()

# Turn the Apify tool sets into LangGraph-ready tools
tools = [tool_cls() for tool_cls in (APIFY_SEARCH_TOOLS + APIFY_SOCIAL_TOOLS)]

# Define the OpenAI model that will serve as the agent's brain
model = ChatOpenAI(model="gpt-5.4-mini")

# Specify the instructions that guide the agent's behavior
agent_system_prompt = (
    "You are a helpful research assistant. Use Apify tools when you need to "
    "fetch web or social media data."
)

# Create the LangGraph agent
agent = create_agent(
    model=model,
    tools=tools,
    system_prompt=agent_system_prompt,
)

# Specify the agent's task
user_prompt = (
    "Research Nike's social media presence on TikTok, LinkedIn, and Facebook.\n"
    "For each platform, retrieve the available profile information and recent relevant data. "
    "Return a report summarizing the key information, including the profile URL, "
    "follower count, and other relevant metrics."
)

# Stream the agent execution, including tool calls and results
for update in agent.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": user_prompt,
            }
        ]
    },
    stream_mode="updates",
):
    for node_name, node_update in update.items():
        print(f"\n{'=' * 20} {node_name} {'=' * 20}")

        if "messages" not in node_update:
            continue

        for message in node_update["messages"]:
            message.pretty_print()

Run the script. The agent's output will be streamed to the terminal.

Before the agent's final response, you'll see the individual steps it takes, including the Apify tools it calls:

The Apify LangChain tools

In this case, the agent called these Apify tools:

For each tool call, you'll see the data returned by the tool:

The data returned by the apify_tiktok_scraper tool

The agent uses the returned data to generate a contextual response, such as the following:

The output produced by the LangGraph agent

Note how the final response includes real-world social media URLs and other platform-specific metrics. This demonstrates that the LangGraph + Apify agent workflow worked as expected.

How to set up MCP LangGraph integration with Apify MCP Server

Below, you'll learn how to connect a LangGraph agent to Apify MCP Server and give it access to the full range of tools available on Apify Store.

Step #4: Add the required library

Begin by adding a required dependency:

pip install "langchain[mcp]"

"langchain[mcp]" fully replaces the old langchain-mcp-adapters, letting you connect your LangGraph agent to MCP servers and use their tools with LangChain.

Because MCP tool loading is asynchronous, update your script to use asyncio:

import asyncio
# Other imports...

async def main():
    # LangGraph agent logic..


if __name__ == "__main__":
    asyncio.run(main())

Step #5: Load the Apify MCP server tools

Apify recommends connecting to its MCP server using Streamable HTTP. For authentication, pass your Apify API token in the Authorization header.

Read the Apify API token from the APIFY_TOKEN environment variable and add a configuration for connection to Apify MCP Server:

import os
from langchain.mcp import MCPAdapter

# Read the Apify token from the envs
APIFY_TOKEN = os.environ["APIFY_TOKEN"]

# Define the Apify MCP Server configuration via Streamable HTTP
mcp_client = MCPAdapter(
    {
        "apify": {
            "transport": "http",
            "url": "https://mcp.apify.com", # The URL of Apify MCP Server
            "headers": {
                "Authorization": (f"Bearer {APIFY_TOKEN}"),
            },
        },
        # Other MCP server configs here...
    }
)

MCPAdapter is a client provided by langchain[mcp] that lets you connect to one or more MCP servers. In this example, only Apify MCP server is set up, but you can add additional MCP servers later.

Note: The langchain.mcp namespace requires langchain[mcp]>=1.4.0.

Next, load the tools exposed by the configured MCP servers:

# Load all the MCP tools
tools = await mcp_client.list_tools()

list_tools() returns the MCP tools as LangChain-compatible tools. That means you can pass the returned tools list directly to your LangGraph agent.

To verify that the Apify MCP server tools were loaded correctly, consider printing their names:

print("\nAvailable Apify MCP tools:")
for tool in tools:
    print(f"- {tool.name}")

The output will list the tools exposed by Apify MCP Server by default:

The tools exposed to LangGraph by the Apify MCP Server connection

Step #6: Define the agent

Initialize the LangGraph agent by configuring the OpenAI model, system prompt, and MCP tools:

# Define the OpenAI model that will serve as the agent's brain
model = ChatOpenAI(model="gpt-5.4-mini")

# Specify the instructions that guide the agent's behavior
agent_system_prompt = (
    "You are a helpful research assistant. Use Apify MCP Server tools for "
    "web scraping, data extraction, and automation tasks."
)

# Create the LangGraph agent
agent = create_agent(
    model=model,
    tools=tools,
    system_prompt=agent_system_prompt,
)

Step #7: Run the MCP LangGraph agent workflow

To test the integration, give the agent a task that requires web access or any automation scenario supported by one or more Apify Actors. For example:

user_prompt = (
    "Find Nike's latest post on TikTok and return relevant metrics, "
    "including sentiment analysis of the top comments."
)

Pass the prompt to the agent and stream its output to the terminal:

async for update in agent.astream(
    {
        "messages": [
            {
                "role": "user",
                "content": user_prompt,
            }
        ]
    },
    stream_mode="updates",
):
    for node_name, node_update in update.items():
        print(f"\n{'=' * 20} {node_name} {'=' * 20}")

        if "messages" not in node_update:
            continue

        for message in node_update["messages"]:
            message.pretty_print()

Step #8: Final Code

The complete Python script for the MCP LangGraph agent workflow is:

# pip install langchain langchain-openai python-dotenv "langchain[mcp]"

import asyncio
from dotenv import load_dotenv
import os
from langchain.mcp import MCPAdapter
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent

# Load API keys from .env
load_dotenv()


async def main():
    # Read the Apify token from the envs
    APIFY_TOKEN = os.environ["APIFY_TOKEN"]

    # Define the Apify MCP Server configuration via Streamable HTTP
    mcp_client = MCPAdapter(
        {
            "apify": {
                "transport": "http",
                "url": "https://mcp.apify.com", # The URL of Apify MCP Server
                "headers": {
                    "Authorization": (f"Bearer {APIFY_TOKEN}"),
                },
            },
            # Other MCP server configs here...
        }
    )
    # Load all the MCP tools
    tools = await mcp_client.list_tools()

    # Define the OpenAI model that will serve as the agent's brain
    model = ChatOpenAI(model="gpt-5.4-mini")

    # Specify the instructions that guide the agent's behavior
    agent_system_prompt = (
        "You are a helpful research assistant. Use Apify MCP Server tools for "
        "web scraping, data extraction, and automation tasks."
    )

    # Create the LangGraph agent
    agent = create_agent(
        model=model,
        tools=tools,
        system_prompt=agent_system_prompt,
    )

    # Specify the agent's task
    user_prompt = (
        "Find Nike's latest post on TikTok and return relevant metrics, "
        "including sentiment analysis of the top comments."
    )

    # Stream the agent execution, including tool calls and results
    async for update in agent.astream(
        {
            "messages": [
                {
                    "role": "user",
                    "content": user_prompt,
                }
            ]
        },
        stream_mode="updates",
    ):
        for node_name, node_update in update.items():
            print(f"\n{'=' * 20} {node_name} {'=' * 20}")

            if "messages" not in node_update:
                continue

            for message in node_update["messages"]:
                message.pretty_print()


if __name__ == "__main__":
    asyncio.run(main())

Execute the script. The agent should first call the search-actors tool with the “TikTok” keyword to find relevant Apify Actors:

Searching for Apify Actors matching the “TikTok” word

From the search results, the agent selects TikTok Comments Scraper (clockworks/tiktok-comments-scraper) as the right Actor for the task. It then calls fetch-actor-details to learn what the Actor does and how to use it:

Understanding how to use TikTok Comments Scraper

Next, the agent uses the apify--web-fetch tool powered by Web Fetch Actor, to retrieve the Nike TikTok account page:

Retrieving the Nike TikTok page contents

From the returned HTML converted to Markdown, the agent discovers Nike's latest TikTok post. It then passes the post URL to clockworks/tiktok-comments-scraper and calls the Actor to retrieve the latest 20 comments via the call-actor tool:

Getting the last 20 comments from the TikTok post

The agent then calls get-dataset-items to retrieve the dataset containing the scraped comments and related data:

Getting the comments data

Finally, the MCP LangGraph agent analyzes the retrieved data and combines the relevant information into the final response:

The final response

The produced output includes the available metrics for Nike's latest TikTok post, along with sentiment analysis of the retrieved comments. Verify the results by checking the original post:

The analyzed TikTok post

Next steps

The LangGraph and Apify integrations above show how to build simple agents that use Apify tools. You can extend these workflows with more advanced LangGraph capabilities, such as:

  • Custom workflows: Combine deterministic steps, agentic nodes, conditional routing, and Apify tools to build more controlled workflows.
  • Persistence and memory: Save graph state and maintain context across runs, including workflows that work with Apify data over multiple steps.
  • Human-in-the-loop: Pause execution with interrupt() to review or approve actions, such as running an Apify Actor, before resuming the workflow.
  • Multi-agent workflows: Build specialized agents that collaborate on tasks.
  • Durable execution: Resume long-running workflows after failures without restarting from scratch, which is great for use cases involving longer-running Apify Actors.

Conclusion

These workflows give LangGraph agents access to real-time web data and a broad marketplace of ready-made AI tools through Apify. You can connect Apify through the official langchain-apify integration for direct access to specific tools, or use Apify MCP Server to let agents discover and use Actors dynamically.

Apify logo
Largest marketplace of tools for AI
Thousands of Actors to automate your business. Get real-time web data, track competitors, generate leads, monitor social media, and integrate your apps and agents.

FAQ

Does Apify support LangGraph?

Yes. Apify supports LangGraph through the langchain-apify package, which provides LangChain-compatible tools for Apify Actors. You can use these tools in LangGraph agents and workflows.

How does the official Apify LangChain integration work?

The langchain-apify package wraps Apify Actors as LangChain tools with simplified input schemas. You can give these tools to an agent, letting it call Apify Actors for tasks such as web search, scraping, social media data extraction, and more.

Does langchain-apify also work with LangGraph?

Yes. langchain-apify supports both LangChain and LangGraph. The same package provides tools that you can bind to your LangGraph agent workflow, including dedicated tools, complete tool sets, and a generic tool for running other Apify Actors.

What are the benefits of connecting a LangGraph agent to Apify MCP Server?

Apify MCP Server lets a LangGraph agent discover and run Actors dynamically, access Actor results and storage, and use web data tools. This gives agents access to a broad marketplace of ready-made tools without requiring you to integrate each Actor individually.

On this page

Publish and earn on Apify Store

The largest marketplace of tools for AI

Start here