Skip to content

How to add persistence sessions when working with langgraph #189

@monotykamary

Description

@monotykamary

I have a super simple example that I use with langgraph dev where my config is:

{
  "dependencies": ["."],
  "graphs": {
    "agent": "./src/agent/graph.py:make_graph"
  },
  "env": ".env"
}

where agent invokes the make_graph function.

"""MCP client."""

import os

from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent


SERVER_CONFIGS = {
    "playwright": {
        "command": "npx",
        "args": ["-y", "@playwright/mcp@latest"],
        "transport": "stdio",
    },
}

client = MultiServerMCPClient(SERVER_CONFIGS)


async def make_graph():
    """make_graph."""
    tools = await client.get_tools()
    agent = create_react_agent(
        "google_genai:gemini-2.5-pro-preview-05-06",
        tools,
    )
    return agent

However, when running playwright, the session gets cut off as each new tool call creates a new session. I have read here and there that the recommended solution is to add a session:

"""MCP client."""

import os

from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent


SERVER_CONFIGS = {
    "playwright": {
        "command": "npx",
        "args": ["-y", "@playwright/mcp@latest"],
        "transport": "stdio",
    },
}

client = MultiServerMCPClient(SERVER_CONFIGS)


async def make_graph():
    """make_graph."""
    agent = None
    async with client.session("playwright") as session:
        tools = await load_mcp_tools(session)
        agent = create_react_agent(
            "google_genai:gemini-2.5-pro-preview-05-06",
            tools,
        )
    return agent

But I consistently get this error when the LLM attempts to run any of the tools in playwright:

Error: ClosedResourceError() Please fix your mistakes.

Am I doing something wrong here or am I missing something fundamental?

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions