AI AgentsLangChain

How do you pass runtime context to an agent?

Question 290 of 324 · Updated

On this page

Direct answer#

In modern LangChain, declare the type of application-supplied runtime context using create_agent(context_schema=...), then pass a corresponding context object through the context keyword when invoking the agent. The context provides invocation-scoped dependencies and trusted information, such as an authenticated user identity, tenant scope, request identifier, approved configuration or a scoped service interface.

Runtime context is different from the messages supplied as agent input. Messages express the task and observations that may reach the model. Context carries application dependencies that supported runtime components can access without automatically exposing them to the model. It is also distinct from mutable graph state and a persistent cross-thread store.

This lesson extends the previous system-prompt lesson (#289), which describes model-facing instructions, and the generic state and context lessons (#33, #50, #57 and #69). The goal here is to understand the invocation-time dependency boundary. Detailed tool-runtime access, middleware hook signatures, memory backends and concurrent-session orchestration have separate lessons later in the curriculum.

1. Why runtime context is needed#

Imagine a multi-tenant order-support agent. Two customers each have an order named X1. The model needs to ask for the status of an order, but it should not decide which tenant owns the request.

An unsafe architecture gives the model a tool that accepts tenant_id and order_id, then trusts both values. A malicious user or misleading retrieved document could induce a call with another tenant's ID. A safer architecture derives the tenant from authenticated application identity, authorizes the request, and injects a scoped service or identity into the agent runtime. The model supplies only task-specific arguments, such as the order identifier. The application checks resource authorization before any external operation.

Runtime context is an instance of dependency injection. Rather than constructing a global database client with unrestricted permissions inside an agent tool, the host supplies a dependency with the appropriate lifetime and scope. This improves reuse, deterministic testing and separation of concerns.

RequirementRuntime context contribution
Authenticated identityProvides the verified principal chosen by the host
Tenant isolationCarries the authorized tenant or scoped domain service
Request trackingCarries an application-generated correlation ID
ConfigurationSupplies approved deployment or feature-profile information
DependenciesProvides a scoped client, service interface or factory where supported
TestingLets tests supply deterministic substitutes instead of live services

A typed context is not automatically trusted just because it is typed. The trust comes from how the host authenticates and authorizes the request and constructs the object.

Loading diagram…

This diagram describes intended application architecture, not the exact internal node structure of every LangChain version. Runtime context is not itself a model prompt; a component can deliberately expose selected context values, and such exposure requires appropriate review.

2. Define a typed context schema#

A common pattern is to use a dataclass or another type supported by the installed LangChain release. Define fields according to the agent's actual needs rather than forwarding the entire HTTP request object.

PYTHON
from dataclasses import dataclass @dataclass(frozen=True) class SupportContext: tenant_id: str user_id: str request_id: str locale: str = "en"

The type documents the invocation's dependency contract. A frozen dataclass discourages accidental reassignment, but does not deeply freeze referenced mutable objects, authenticate the fields, or enforce type annotations at runtime. Explicitly validate input values and construct the object from trusted application sources. If using a supported schema-validation library, remember that schema validation confirms shape and types, not resource permissions.

Avoid putting raw bearer tokens, API keys, database passwords or whole customer records into an ordinary context object unless a carefully controlled integration absolutely requires them. Prefer a narrow service capability or secret reference resolved by trusted infrastructure. Even non-model-facing context may be visible to process inspection, callbacks, tracing systems or application logs; do not assume that the framework automatically redacts it.

3. Register context_schema and pass context at invocation time#

The following illustrative LangChain SDK example uses a typed context object. It shows the boundary between input messages and invocation context. The demo tool reads only synthetic data; the minimal runtime-access example is included to make the data flow observable, while detailed ToolRuntime typing, schema exclusion and tool injection are covered in source question #14.

PYTHON
from dataclasses import dataclass from langchain.agents import create_agent from langchain.tools import tool, ToolRuntime @dataclass(frozen=True) class SupportContext: tenant_id: str user_id: str request_id: str # Synthetic fixtures only. A real service checks current resource # permissions for the authenticated subject, not just tenant membership. ORDERS = { ("tenant-a", "X1"): "shipped", ("tenant-b", "X1"): "pending", } ALLOWED = { ("tenant-a", "user-a"): frozenset({"X1"}), ("tenant-b", "user-b"): frozenset({"X1"}), } @tool def lookup_order(order_id: str, runtime: ToolRuntime[SupportContext]) -> str: """Read the status of an order available to the authenticated caller.""" ctx = runtime.context permitted = ALLOWED.get((ctx.tenant_id, ctx.user_id), frozenset()) if order_id not in permitted: return "not available" return ORDERS.get((ctx.tenant_id, order_id), "not available") agent = create_agent( model="openai:gpt-4o-mini", tools=[lookup_order], context_schema=SupportContext, system_prompt="Use authorized order evidence. Do not invent a status.", ) # In production these values come from validated server-side identity. ctx = SupportContext("tenant-a", "user-a", "request-001") result = agent.invoke( {"messages": [{"role": "user", "content": "What is the status of X1?"}]}, context=ctx, ) print(result["messages"][-1].content)

The context_schema declaration identifies the expected runtime context type, and context=ctx supplies the data for this invocation. In supported versions, ToolRuntime makes the context available to tool code without requiring the model to generate those identity fields as tool arguments. Context does not automatically become visible to the model; the tool returns only the authorized observation.

The expected outcome is a grounded shipped status for tenant-a. It is not a guaranteed exact natural-language response. The same agent can be invoked with a separately authenticated tenant-b context, in which case the allowed order X1 has status pending.

SDK verification status: This snippet is illustrative and unexecuted. Local inspection confirmed langchain, langchain_core, langgraph and langchain_openai were absent. Live documentation and provider access were unavailable. Verify imports, context schema support, invocation signatures and model availability against the installed version. The standalone dependency-injection test in section 7 was actually executed.

Asynchronous invocation#

A service with compatible asynchronous dependencies can use the corresponding asynchronous invocation interface, for example:

PYTHON
async def handle(agent, trusted_context, user_text): return await agent.ainvoke( {"messages": [{"role": "user", "content": user_text}]}, context=trusted_context, )

This is another version-dependent SDK illustration, not an executed integration test. An async invocation does not make every synchronous dependency nonblocking or safe for concurrent use. Select clients compatible with the event loop, and manage their lifetime through the host's resource-management mechanisms.

4. Runtime context versus state versus store#

The word context has multiple meanings in agent engineering. Model context is the effective input visible to the model. LangChain runtime context is the application-supplied invocation dependency object. Graph state is the evolving execution data. A store provides access to information that may outlive the current thread, subject to its configuration and namespace policy.

DimensionRuntime contextAgent stateStore
PurposeIdentity and dependencies for an invocationCurrent workflow data and progressReusable information across threads or runs
Typical contentsVerified user ID, scoped service, request IDMessages, intermediate results, workflow fieldsPreferences or approved long-term records
Change patternTreat as stable within an invocationUpdated by supported graph transitionsUpdated through explicit store operations
LifetimeInvocation or associated execution lifecycleRun or thread, optionally checkpointedDepends on configured storage and retention
Model visibilityNot automaticSelected fields/messages may reach the modelOnly explicitly retrieved or exposed data reaches the model
PersistenceDo not assume it is checkpointedMay be persisted with a checkpointerDepends on store implementation
SecurityTrusted construction and narrow dependency scopeAuthorized state access and safe serializationNamespace and resource-level authorization

For example, in a support workflow:

  • Context identifies the authenticated user and provides an authorized order service.
  • State records that the agent has asked for an order ID, retrieved a status and prepared a response.
  • A store may retain an approved language preference across separate support sessions.

A checkpointer and a store are not interchangeable. A checkpointer records execution state for a thread so that the runtime can recover or continue; a store supports explicitly managed information across threads. Neither automatically enforces multi-tenant permissions.

Loading diagram…

The store and checkpointer are optional and must be configured for the selected runtime. In-memory implementations are not durable production databases. Do not serialize a database client, live HTTP connection, request object or raw credential into checkpointed state simply to make it available after a pause.

5. Invocation lifecycle and dependency ownership#

Context is best constructed by the host after successful authentication and authorization, rather than parsed directly from a user-controlled JSON body.

A typical request lifecycle is:

  1. Authenticate the incoming caller and resolve authorized tenant membership.
  2. Validate the requested workload and resource scope.
  3. Acquire a scoped service dependency and create a fresh context object.
  4. Invoke the agent with user messages and the trusted context separately.
  5. Validate tool actions and final outcomes against the current application policy.
  6. Record bounded diagnostics and release request-scoped resources in a finally block or context manager.

For a suspended workflow, reconstruct the necessary runtime dependencies at the next supported invocation or resume boundary. Consult the installed runtime's resume contract; do not assume context objects or live service clients survive a process restart. Persist only stable, necessary identifiers and durable workflow facts, then reauthenticate or reauthorize as appropriate. An old context should not grant access after a user's permissions have been revoked.

Loading diagram…

A request-scoped client must not be closed while an active stream or background task still needs it. If the work moves into a durable queue, pass an approved durable job identifier and reconstruct the dependencies in the worker. Do not transfer a live Python object through a serialized queue.

A shared connection pool may be appropriate when the client supports concurrent use and tenant authorization is enforced per operation. By contrast, a mutable global variable such as current_tenant is unsafe because overlapping requests can change its value. Use explicit dependency passing, immutable invocation configuration and appropriately scoped resource ownership.

6. Runtime context is not a security policy by itself#

There are three distinct questions:

  • Who is the caller? Establish identity through the application's trusted authentication mechanism.
  • What is the caller allowed to do? Check current tenant membership, resource ownership, action scope and policy.
  • How does the agent obtain what it needs? Supply validated context and narrow dependencies through the runtime.

A tenant identifier is not a credential. Even an authenticated user within a tenant may lack permission to access a particular record. The tool or domain service must enforce resource-level authorization. The context object can carry the principal or a service that already enforces a narrow scope, but the tool must never trust model-supplied resource identifiers without validation.

For instance, consider two tenants using the same local order identifier X1. A repository method that looks up by order_id only is ambiguous and can expose the wrong record. Its lookup must include the tenant boundary, or the caller must use a capability that has already enforced it. For write actions, enforce current policy at commit time and bind approval to the exact operation. A context snapshot can become stale.

If an API receives a body containing a user message and an alleged tenant_id, do not instantiate SupportContext with the body as-is. Resolve the tenant from validated credentials and authorized membership; if the user chooses among multiple tenants, check that the selected tenant belongs to that principal.

The same rules apply to thread IDs and store namespaces. A guessed thread identifier must not allow a caller to restore another tenant's checkpoint. Authorize the thread before reading its state and use explicit namespace controls for persistent storage.

7. Locally tested Python implementation: inject a scoped read-only snapshot#

This dependency-free example demonstrates the application boundary before any model or framework is involved. The host receives a synthetic verified identity, constructs a request-scoped snapshot containing only permitted order records and passes that context into an ordinary domain function. Two different tenants share an order identifier. The domain function never looks up another tenant's records.

PYTHON
from dataclasses import dataclass from types import MappingProxyType from typing import Mapping @dataclass(frozen=True) class Identity: tenant: str subject: str allowed: frozenset[str] @dataclass(frozen=True) class Context: tenant: str subject: str request_id: str orders: Mapping[str, str] def make_context(identity, request_id, rows): if (not isinstance(identity, Identity) or not identity.tenant or not identity.subject or not request_id): raise ValueError('invalid invocation identity') scoped = { oid: status for (tenant, oid), status in rows.items() if tenant == identity.tenant and oid in identity.allowed } return Context(identity.tenant, identity.subject, request_id, MappingProxyType(scoped)) def read_order(order_id, ctx): return ctx.orders.get(order_id, 'not available') rows = { ('a', 'X1'): 'shipped', ('b', 'X1'): 'pending', ('a', 'X2'): 'delivered', } a = make_context(Identity('a', 'u1', frozenset({'X1'})), 'r1', rows) b = make_context(Identity('b', 'u2', frozenset({'X1'})), 'r2', rows) assert read_order('X1', a) == 'shipped' assert read_order('X1', b) == 'pending' assert read_order('X2', a) == 'not available' assert read_order('unknown', a) == 'not available' assert a.request_id != b.request_id assert dict(a.orders) == {'X1': 'shipped'} try: a.orders['X1'] = 'wrong' except TypeError: pass else: raise AssertionError('snapshot mutable') try: make_context(Identity('', 'u1', frozenset({'X1'})), 'r3', rows) except ValueError: pass else: raise AssertionError('missing tenant accepted') rows[('a', 'X1')] = 'delivered' assert read_order('X1', a) == 'shipped' assert read_order('X1', make_context( Identity('a', 'u1', frozenset({'X1'})), 'r4', rows)) == 'delivered' print('10 checks passed')

Actual local execution on Python 3.13.5: 10 checks passed.

ScenarioVerified behavior
Tenant A reads X1Receives shipped
Tenant B reads X1Receives pending
Tenant A reads unauthorized X2Receives a bounded unavailable response
Unknown orderSame unavailable response
Two invocationsDistinct request identifiers
Scoped snapshotContains only the approved record
Attempt to mutate snapshotTypeError
Missing tenantValueError
Source changes after snapshotExisting snapshot unchanged
Fresh invocationSees the updated record

The test uses synthetic identities and fixtures; constructing Identity does not actually authenticate a person. The mapping proxy wraps a newly created dictionary containing immutable strings. It does not generally make arbitrary nested values immutable. The host must validate identity values, resource permissions and dependency types in production; the simple nonempty-field check is not sufficient for a real authentication boundary.

The snapshot is suitable as a small, controlled teaching example. In a real large order database, constructing a snapshot of every authorized row could be wasteful or stale. Prefer a scoped repository interface that queries the authoritative service only for the requested order and checks current permissions at the appropriate boundary. Do not place large datasets in context just to avoid writing a tool.

Notice that testing the context and domain function requires neither a model call nor a provider credential. This makes deterministic unit tests inexpensive and repeatable. The test does not establish how the actual LangChain runtime injects context, whether the provider accepts the tool schema or whether a real model uses the tool correctly.

8. Context validation and dependency testing#

Separate validation into stages rather than relying on a single schema declaration.

StageRequired checks
IngressAuthentication, request size and allowed workload
Context constructionRequired fields, trusted identity source, tenant membership, approved dependency configuration
Invocation boundaryCorrect context type and supported runtime API
Tool actionArgument validation, live resource authorization, deadline and action policy
CompletionEvidence grounding, schema validation and authorized disclosure
ResumeReconstruct dependencies, authorize thread and check current permissions

A context schema can expose type errors earlier, but actual validation behavior varies by schema and installed framework version. Test wrong types, missing fields, expired identity, unauthorized tenant selection, disallowed resources and an unavailable service. Ensure the application fails safely rather than substituting a broad default context.

For integration testing, use a deterministic fake dependency to record which tenant and resource were requested. Verify that the runtime-supplied identity reaches the domain boundary and is not included in the model-generated tool schema. Test with two concurrent invocations using the same agent definition and different contexts. Use scripted model outputs where supported, including an attempted request for another tenant's data. Then run separately approved provider tests with synthetic data.

Test cancellation and resource cleanup as well. A failed agent run must release dependencies it owns, without closing a shared client that belongs to the host. A missing context on a resumed workflow must produce a controlled error or require reconstruction, not silently use a previous request's identity.

9. Production use cases and lifecycle trade-offs#

Use caseSuitable contextKeep elsewhere
Customer supportVerified customer identity, scoped order service, request IDConversation in state; approved preferences in store
Enterprise searchAuthorized tenant, document-search capability, policy revisionRetrieved excerpts in selected model input or state
Internal coding assistantApproved workspace handle, task deadline, permissionsFile edits and verification evidence in durable task state
Multi-region serviceApproved deployment profile, scoped clientCurrent routing policy in reviewed configuration
Background research jobReconstructed worker identity and job scopeJob status, evidence and checkpoint references in durable storage

A context object may hold an approved configuration value that influences a system prompt, model choice or tool availability. That does not mean every value should be inserted into the model's messages. Select only fields necessary for the current task. The upcoming middleware lesson will show how supported hooks can use these dependencies without changing the underlying authorization policy.

Numerical illustration: avoid unnecessary model-visible context#

Suppose an application mistakenly adds a 1,200-token serialization of identity metadata, feature flags and service configuration to each of four model requests. If only a 100-token approved task summary actually belongs in the model input, the application can avoid approximately 4 × 1,100 = 4,400 logical input tokens per run by retaining the dependencies in runtime context and exposing only that summary.

At a hypothetical uncached input price of $2 per million tokens, the gross difference is $0.0088 per run or $88 over 10,000 comparable runs. These figures are illustrative, not measured LangChain behavior or current provider pricing. Actual billing depends on tokenization, caching and provider accounting. Do not omit information the model needs to complete the task merely to reduce cost; keep secrets and privileged dependencies outside the model input regardless of price.

10. Common mistakes and corrective practices#

MistakeCorrection
Pass user JSON directly into context_schemaAuthenticate and construct a reviewed context explicitly
Treat dataclass typing as identity verificationValidate identity, membership and policy independently
Store a global current user variableInject request-scoped identity for every invocation
Put secrets into prompt text or stateResolve credentials in trusted infrastructure
Assume context is persisted with the checkpointReconstruct dependencies at resume according to the runtime contract
Treat a store namespace as automatic authorizationAuthorize access and enforce namespace/resource scope
Expose the complete request context to the modelSelect only necessary safe information
Reuse a stale permissions snapshot for writesRecheck authorization and approval at execution time
Assume context is deeply immutableUse immutable values or explicitly manage dependency concurrency
Test only one successful requestTest isolation, malformed context, cancellation and unavailable dependencies

Interview-ready answer#

In LangChain, I declare the application's runtime dependency contract using context_schema when constructing an agent and supply a validated context object with context= at invocation time. Runtime components can access it through supported interfaces, while user messages remain task input. I use context for trusted identity, tenant scope and narrow service dependencies, state for evolving execution data, and an explicitly configured store for cross-thread information. I authenticate and authorize outside the model, validate each action at the domain boundary, reconstruct invocation dependencies on resume and test tenant isolation with fake services. A context schema does not itself enforce permissions or automatically make every context field model-visible or durable.

Official documentation research leads and verification status#

Authorized offline research exception applied. The official documentation URLs are research leads and were not live-accessed. The standalone Python example was actually executed on Python 3.13.5 and passed 10 checks; the four checked LangChain packages were absent, so SDK integration snippets were not executed and current APIs were not verified against an installed release. Mermaid diagrams are stored in standard triple-backtick fences; live renderer and public website display were unavailable. No real identities, customer records, provider credentials or model calls were used.

References

  1. 1.
    LangChain runtimedocs.langchain.com
  2. 2.
    LangChain agentsdocs.langchain.com
  3. 3.
    LangChain toolsdocs.langchain.com
  4. 4.
  5. 5.
    LangChain short-term memorydocs.langchain.com
  6. 6.
    LangGraph persistencedocs.langchain.com
  7. 7.
    LangChain API referencereference.langchain.com

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.