Runtime context passed to graph builder factories within the Agent Server.
Requires version 0.7.30 or later of the agent server.
The server calls your graph factory in multiple contexts: executing runs,
reading state, fetching schemas, and more. ServerRuntime provides
the authenticated user, store, and access context for every call. Use
.execution_runtime to narrow to the execution variant and access
context.
Example — conditionally initialize MCP tools only during execution:
import contextlib
from dataclasses import dataclass
from langchain.agents import create_agent
from langgraph_sdk.runtime import ServerRuntime
from my_agent import connect_mcp, disconnect_mcp
@dataclass
class MyCtx:
mcp_endpoint: str
_readonly_agent = create_agent("anthropic:claude-3-5-haiku", tools=[])
@contextlib.asynccontextmanager
async def my_factory(runtime: ServerRuntime[MyCtx]):
if ert := runtime.execution_runtime:
# Only connect to MCP servers for actual runs.
# Schema / graph introspection calls skip this.
user_id = runtime.ensure_user().identity
mcp_tools = await connect_mcp(ert.context.mcp_endpoint, user_id)
yield create_agent("anthropic:claude-3-5-haiku", tools=mcp_tools)
await disconnect_mcp()
else:
yield _readonly_agent
Example — simple factory that ignores context:
from langgraph_sdk.runtime import ServerRuntime
def build_graph(user: BaseUser) -> CompiledGraph:
...
async def my_factory(runtime: ServerRuntime) -> CompiledGraph:
# No generic needed if you don't use context.
return build_graph(runtime.ensure_user())
This API is in beta and may change in future releases.