A tool like my orders needs to know which customer is asking. But we must never let the model choose the customer ID, or a clever prompt could read someone else's orders. Runtime context passes trusted data straight to tools.
We describe the context as a data class, with a customer ID. The tool takes a tool runtime argument, which the model never sees. It reads the customer ID from the runtime. When we invoke the agent, our code supplies the context. Run it. The tool looks up orders for the real customer, whatever the user types.
context.pypython
from dataclasses import dataclassfrom langchain.agents import create_agentfrom langchain.tools import tool, ToolRuntimeORDERS = {"cust-7": ["Dune (shipped)", "Circe (packing)"]}@dataclassclass Ctx: customer_id: str@tooldef my_orders(runtime: ToolRuntime[Ctx]) -> list[str]: """List the current customer's orders.""" return ORDERS.get(runtime.context.customer_id, [])agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[my_orders], context_schema=Ctx)out = agent.invoke({"messages": [{"role": "user", "content": "What are my orders? Be brief."}]}, context=Ctx(customer_id="cust-7"))print(out["messages"][-1].text)
Output
Your orders are:
- Dune (shipped)
- Circe (packing)
Don't mix up context and state. Context is fixed for one run, and comes from your code, like the user ID, their permissions, or a database connection. State is the conversation, which changes as the agent works. Put anything trusted in context, never in the messages.
Runtime context passes trusted data, like the customer ID, straight to tools and middleware, where the model can't change it. Next, practise building a complete bookshop agent.