Async graph creation function

Hey folks, I fail to figure how you’re expected to build a graph from an async function, in the context of a LangGraph app.

Documentation often shows using `ainvoke` etc. but when creating an actual LangGraph Server you don’t control how the graph is invoked, what you do is exposing a graph object from a module.

graph = create_agent(...) # OK
graph = await build_agent(...) # How to do that? I can't await from a module top-level code

This is needed for instance to get the tools from an MCPAdapter ( Connections - Docs by LangChain ). I couldn’t find a proper answer in the Async LangGraph guide ( Use the graph API - Docs by LangChain ).

I’ve tried a hacky setup with `asyncio.run` as recommended by AI but it didn’t work, see PR here: mcp support by eric-burel · Pull Request #1 · lbke/langgraph-simple-agent-openrouter · GitHub

Hi @eric-burel, you don’t need to await at module top level. LangGraph Server accepts a graph factory function in langgraph.json, and that function can be async. The server calls it for you, so you can await inside it.

import contextlib
from langchain.agents import create_agent
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph_sdk.runtime import ServerRuntime

client = MultiServerMCPClient({
    "my_server": {"transport": "streamable_http", "url": "http://localhost:8000/mcp"}
})

@contextlib.asynccontextmanager
async def make_graph(runtime: ServerRuntime):
    if runtime.execution_runtime:
        tools = await client.get_tools()
    else:
        tools = []  # same topology, no MCP call for schema/state reads
    yield create_agent("openai:gpt-4.1", tools)

Langraph.json


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

Please checkout the following: Rebuild graph at runtime - Docs by LangChain

Hey @keenborder786 , thanks a lot for pointing me in the right direction, I figured that you need the complete “context manager factory” as you pointed out. This is not super intuitive especially since you can’t just pass an async function and must handle context properly, so I’ve PRed the doc with a proper link in the MCP page : Update MCP documentation for Agent Server by eric-burel · Pull Request #6838 · langchain-ai/docs · GitHub