AI AgentsLangChain
How do you inject runtime context into LangChain tools?
Question 294 of 324 · Updated
On this page
- Direct answer
- 1. Two independent input channels
- 2. Define a typed runtime dependency contract
- 3. Inject ToolRuntime into a decorated tool
- 4. Verify schema exclusion rather than assuming it
- What ToolRuntime can carry
- 5. Follow the actual call through the runtime
- 6. Synchronous and asynchronous tools
- 7. Tested implementation: isolate model arguments from trusted dependencies
- 8. Scoped dependencies and least privilege
- 9. Failure handling and observability
- 10. Integration tests to run before deploying
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
In modern LangChain, annotate a tool parameter with ToolRuntime[YourContext], read the application-supplied context through runtime.context, and register the tool with an agent configured using context_schema=YourContext. At invocation time, the trusted host supplies the corresponding context object using context= rather than asking the model to generate identity, credentials or dependencies.
For example, a model may propose get_invoice(invoice_id="INV-1"), but the invoice tool obtains the authenticated tenant, principal and scoped repository from ToolRuntime. The model-facing schema should contain invoice_id, not the runtime parameter or the fields of the context object. The application must independently validate the proposed arguments and check current resource permissions.
Source question #10 (AI Agents #290) covers the invocation-time context contract and the distinction between context, state and store. Source question #13 (#293) covers explicit Pydantic argument validation. This lesson focuses on the tool-side injection boundary, including hidden runtime parameters, schema inspection, scoped services and sync/async execution. Accessing persistent state and stores inside tools is reserved for the following lessons.
1. Two independent input channels#
A tool is executed in a trusted application process. Its inputs can originate from different trust domains, even when they appear in one Python signature.
| Input | Origin | Example | Trust treatment |
|---|---|---|---|
| Model-generated argument | Proposed tool-call payload | invoice_id | Untrusted, validate type and semantics |
| Runtime context | Authenticated host | principal, tenant, request_id | Trust only after validated host construction |
| Service dependency | Application dependency factory | Scoped invoice repository | Enforce narrowly defined capabilities |
| Tool result | Domain service | Invoice status | Validate and minimize before returning |
| Execution metadata | Runtime | Tool-call correlation information | Use for tracing, not as proof of authorization |
The important invariant is not merely that the context field is missing from the schema. It is that the actual object used during execution comes from the trusted runtime and cannot be replaced by a model-proposed argument.
This diagram shows the intended security architecture. It is not a claim about the exact internal order of LangChain graph nodes or validation functions in every release. The host must ensure the injection and validation boundaries cannot be bypassed.
2. Define a typed runtime dependency contract#
A context can carry identity and a service interface rather than a database connection string or raw credential. A simple illustrative design uses an immutable principal and a Protocol describing the domain capability.
PYTHONfrom dataclasses import dataclass from typing import Protocol @dataclass(frozen=True) class Principal: tenant: str subject: str class InvoiceRepository(Protocol): def read(self, principal: Principal, invoice_id: str) -> str | None: ... @dataclass(frozen=True) class InvoiceContext: principal: Principal repo: InvoiceRepository request_id: str
A repository interface limited to a read operation is preferable to injecting an unrestricted database client into a read-only tool. The implementation should verify current permissions for the principal and resource and apply tenant isolation. The principal must be derived from authenticated server-side identity, not from the user message or a claimed tenant in a request body.
A frozen dataclass prevents ordinary field reassignment but does not make the referenced repository thread-safe or immutable. A Protocol describes an interface; it does not itself prove that an implementation enforces access control. These remain application responsibilities.
3. Inject ToolRuntime into a decorated tool#
The following illustrative SDK code uses the common modern LangChain ToolRuntime interface. The host constructs InvoiceContext and supplies it when invoking the agent, following the invocation contract introduced in #290.
PYTHONfrom langchain.agents import create_agent from langchain.tools import tool, ToolRuntime from pydantic import BaseModel, ConfigDict, Field class LookupArgs(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") invoice_id: str = Field( pattern=r"^INV-[0-9]+$", description="Exact invoice identifier, such as INV-1", ) @tool(args_schema=LookupArgs) def get_invoice( invoice_id: str, runtime: ToolRuntime[InvoiceContext], ) -> dict: """Read the status of an invoice authorized for the current caller.""" ctx = runtime.context if not isinstance(ctx, InvoiceContext): raise PermissionError("invalid runtime context") status = ctx.repo.read(ctx.principal, invoice_id) return {"status": status if status is not None else "not available"} agent = create_agent( model="openai:gpt-4o-mini", tools=[get_invoice], context_schema=InvoiceContext, system_prompt="Report only authorized invoice evidence.", ) def handle(trusted_context: InvoiceContext, user_text: str): return agent.invoke( {"messages": [{"role": "user", "content": user_text}]}, context=trusted_context, )
This is intended SDK wiring for a compatible release. Verify that the installed version supports an explicit args_schema together with ToolRuntime injection; if it does not, use a documented compatible registration pattern and validate the public argument model at the domain boundary. Do not expose runtime as a model argument to work around an integration mismatch.
The example assumes a repository implementation that enforces resource-level authorization. It does not implement authentication or an actual billing service. The model identifier is illustrative and not a guarantee of availability.
SDK verification limitation: LangChain, langchain_core and langgraph were absent from the local Python environment. The SDK snippets are illustrative, unexecuted and not version-verified. The Pydantic and standard-library implementation in section 7 was executed on Python 3.13.5 and Pydantic 2.13.5.
4. Verify schema exclusion rather than assuming it#
The tool's public argument schema should describe only the values that the model may propose. For this example the intended public shape is:
JSON{ "type": "object", "properties": { "invoice_id": { "type": "string", "pattern": "^INV-[0-9]+$" } }, "required": ["invoice_id"], "additionalProperties": false }
This is a simplified intended schema, not an observed provider payload. Actual schema serialization may include titles, descriptions and other metadata. Provider conversion may modify supported constraints.
In supported modern LangChain versions, ToolRuntime is an injected argument and is excluded from the model-facing tool schema. Local input schemas and model-facing schemas can differ. Inspect the specific interface used to construct the provider tool definition, not just an arbitrary local schema.
PYTHON# Illustrative inspection in a compatible installed release. print(get_invoice.name) print(get_invoice.description) print(get_invoice.tool_call_schema.model_json_schema())
The expected invariant is that invoice_id is a public field and runtime, principal, repo, tenant and subject are not. The exact schema accessor and its return type can differ by tool class and version; consult the installed reference. Inspect the actual converted tool specification where the provider adapter makes that possible.
A second test is equally important: send an intentionally malformed proposal containing an extra tenant or runtime property through the real tool execution path. Verify that the system rejects or safely discards unexpected input and uses only the trusted injected object. For sensitive actions, prefer explicit rejection at the application's input boundary. Do not rely on provider schema conformance or an implicit unknown-field policy.
What ToolRuntime can carry#
ToolRuntime is a runtime-supplied access object, not simply an alias for the custom context dataclass. In modern documented patterns it can expose context and other runtime facilities, which may include state, store, configuration, tool-call ID and streaming support. Availability depends on the configured runtime and installed version.
This lesson uses only runtime.context. State and store access, state updates and stream writers require their own lifecycle and persistence rules. Do not treat a runtime object as a general-purpose bag of credentials or serialize it into a model-visible observation.
5. Follow the actual call through the runtime#
Consider tenant A and tenant B, each with a locally named invoice INV-1. Alice is authenticated in tenant A and Bob in tenant B. The tool name and argument schema are identical for both sessions.
For Alice the result might be paid; for Bob the same proposed argument might yield open. This does not require the model to know either tenant's ID. A malicious instruction telling the model to pretend to be Bob cannot change the actual authenticated context. However, the host and repository must correctly enforce that invariant.
A valid invoice_id is not proof that the invoice is accessible. An authenticated user may have access to only part of a tenant's records. The repository needs both tenant and resource-level authorization, and should return a bounded denial or unavailable response without disclosing whether an inaccessible record exists.
6. Synchronous and asynchronous tools#
A synchronous tool can call a compatible synchronous repository. For a remote service, bound network timeouts and avoid creating a new expensive connection for every call unless the client lifecycle requires it.
An async tool can instead await an asynchronous service dependency. This illustrative pattern defines a separate context type with an async repository contract.
PYTHONfrom dataclasses import dataclass from typing import Protocol from langchain.tools import tool, ToolRuntime class AsyncInvoiceRepository(Protocol): async def read( self, principal: Principal, invoice_id: str ) -> str | None: ... @dataclass(frozen=True) class AsyncInvoiceContext: principal: Principal repo: AsyncInvoiceRepository request_id: str @tool(args_schema=LookupArgs) async def get_invoice_async( invoice_id: str, runtime: ToolRuntime[AsyncInvoiceContext], ) -> dict: """Read an authorized invoice using an asynchronous repository.""" ctx = runtime.context if not isinstance(ctx, AsyncInvoiceContext): raise PermissionError("invalid runtime context") status = await ctx.repo.read(ctx.principal, invoice_id) return {"status": status if status is not None else "not available"}
Construct an agent using this tool and context_schema=AsyncInvoiceContext, and invoke it through the supported asynchronous interface such as ainvoke(..., context=ctx). This SDK example is unexecuted.
Do not assume that making a function async def turns a blocking database or HTTP operation into a nonblocking operation. Prefer an asynchronous client where appropriate. If a blocking read must be offloaded, asyncio.to_thread is one possible standard-library mechanism for a suitable thread-safe dependency. Cancelling the await does not necessarily interrupt the underlying worker thread or external request; enforce deadlines at the service boundary.
Keep resource ownership explicit. The host should release request-owned clients after the invocation and any associated streaming work finish. A tool should not close a shared connection pool owned by the application. Concurrent calls must not overwrite a global current_tenant variable or mutate a shared client with a request's credentials.
7. Tested implementation: isolate model arguments from trusted dependencies#
The following standalone example tests the two input channels using actual Pydantic v2 validation and a fake repository. It uses explicit dependency passing to represent the application boundary without pretending to implement LangChain's ToolRuntime injection.
PYTHONimport asyncio from dataclasses import dataclass from typing import Protocol from pydantic import BaseModel, ConfigDict, Field, ValidationError class LookupArgs(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') invoice_id: str = Field(pattern=r'^INV-[0-9]+$') @dataclass(frozen=True) class Principal: tenant: str subject: str class Repository(Protocol): def read(self, principal: Principal, invoice_id: str) -> str | None: ... @dataclass(frozen=True) class Context: principal: Principal repo: Repository request_id: str class FakeRepository: def __init__(self): self.rows = {('a', 'alice', 'INV-1'): 'paid', ('b', 'bob', 'INV-1'): 'open'} self.calls = [] def read(self, principal, invoice_id): self.calls.append((principal.tenant, principal.subject, invoice_id)) return self.rows.get((principal.tenant, principal.subject, invoice_id)) def lookup(payload, ctx): args = LookupArgs.model_validate(payload) if not isinstance(ctx, Context) or not ctx.principal.tenant or not ctx.principal.subject: raise PermissionError('invalid context') return {'status': ctx.repo.read(ctx.principal, args.invoice_id) or 'not available'} async def lookup_async(payload, ctx): # Example only: offload a blocking read with a thread-safe dependency. return await asyncio.to_thread(lookup, payload, ctx) repo = FakeRepository() a = Context(Principal('a','alice'), repo, 'r1') b = Context(Principal('b','bob'), repo, 'r2') p = {'invoice_id':'INV-1'} assert set(LookupArgs.model_json_schema()['properties']) == {'invoice_id'} assert lookup(p,a) == {'status':'paid'} assert lookup(p,b) == {'status':'open'} assert lookup({'invoice_id':'INV-2'},a) == {'status':'not available'} assert lookup(p,Context(Principal('a','mallory'),repo,'r3')) == {'status':'not available'} for bad in ({**p,'tenant':'b'}, {**p,'runtime':b}, {'invoice_id':1}): before = len(repo.calls) try: lookup(bad,a) except ValidationError: pass else: raise AssertionError('invalid input accepted') assert len(repo.calls) == before before = len(repo.calls) try: lookup(p,None) except PermissionError: pass else: raise AssertionError('missing context accepted') assert len(repo.calls) == before async def check(): assert await asyncio.gather(lookup_async(p,a),lookup_async(p,b)) == [{'status':'paid'},{'status':'open'}] asyncio.run(check()) print('10 scenarios passed')
Actual local result:
10 scenarios passedTest environment: Python 3.13.5, Pydantic 2.13.5.
| Scenario | Verified result |
|---|---|
| Public schema | Contains invoice_id only |
| Tenant A / Alice | paid |
| Tenant B / Bob | open |
| Unknown or unavailable invoice | not available |
| Unauthorized subject in same tenant | not available |
| Extra tenant property | ValidationError before repository access |
| Extra runtime property | ValidationError before repository access |
| Invalid invoice ID type | ValidationError before repository access |
| Missing runtime context | PermissionError before repository access |
| Concurrent async wrapper invocations | Correct independent statuses |
The tests are deliberately scoped. The public schema is the standalone Pydantic model, not the actual LangChain provider-converted schema. The fake identity and repository demonstrate resource scoping; they do not authenticate a real caller. The concurrent test uses a small in-memory fixture with fixed rows and a call log; it does not certify that a production repository or arbitrary shared mutable data is thread-safe. A real client used with to_thread must support that execution pattern, and shared mutable state needs appropriate synchronization. The example does not test cancellation, external deadlines or actual SDK injection.
The crucial negative test is the attempt to supply a runtime object through the model-facing payload. The explicit public schema forbids unknown fields, and the fake repository is never reached for that input. A production LangChain integration test must reproduce this invariant at the actual tool node and adapter boundary.
8. Scoped dependencies and least privilege#
There are two common designs for a domain dependency.
| Design | Advantages | Risks and responsibilities |
|---|---|---|
| Repository plus trusted principal | Reuses a single interface across requests; supports per-operation permission checks | Every operation must apply the principal and tenant filter |
| Pre-scoped capability | Tool receives only methods permitted for the invocation | Factory must construct the scope correctly; permissions may become stale |
| Unrestricted service client | Convenient for prototypes | Broad privileges and greater risk of accidental cross-resource access; avoid in narrow tools |
A pre-scoped capability may expose read_invoice(invoice_id) while internally binding an authenticated principal. It can make unsafe invocation harder by construction. However, an object created yesterday must not allow access after permissions change. Recheck current policy for security-sensitive operations.
A tool that updates an invoice or sends a message needs controls beyond read permission: explicit action scope, approval where required, validated parameters, idempotency and authoritative outcome verification. Neither the tool-call ID nor a context request_id is automatically an idempotency key for a business transaction.
Never inject a service-role secret or unrestricted credential solely because the model cannot see the runtime parameter. A tool can leak sensitive data through logs, errors, returned payloads or an overly broad service call. Use scoped credentials and minimal result objects, and restrict what is returned to the model.
9. Failure handling and observability#
A missing runtime context is a configuration or lifecycle error; it is not a missing field that the model should invent. A denied resource is a policy outcome; do not try another tenant automatically. A malformed invoice ID is an input-validation error. A temporary repository timeout is a service failure.
| Failure | Recommended response |
|---|---|
| Context absent or wrong type | Fail closed; diagnose trusted host invocation |
| Model attempts identity override | Reject unexpected input or enforce trusted injection |
| Valid input but unauthorized record | Controlled denial without existence disclosure |
| Repository unavailable | Bounded retry only for safe operations, or report unavailability |
| Credential or permission revoked | Reauthorize or terminate; do not reuse stale privilege |
| Concurrent requests with different scopes | Ensure dependencies and request metadata stay isolated |
| Interrupted run or resumed checkpoint | Reconstruct runtime dependencies and verify current authorization |
For telemetry, record a safe correlation ID, tool name, policy outcome, latency and redacted error classification. Avoid serializing the whole context or logging raw identity tokens, private records or service-client internals. A context object may be visible to tracing or debugging infrastructure even when excluded from the model-facing schema.
The actual LangChain version may surface validation or execution exceptions differently. Use supported error-handling mechanisms and verify whether failures propagate, produce tool observations or interrupt the run. The later error-handling lesson focuses on those configuration details.
10. Integration tests to run before deploying#
A production test suite should go beyond directly calling a domain function. Verify the installed LangChain runtime, model adapter and tool schema in a controlled environment.
Use a compatible scripted model or mock transport to exercise the real tool execution graph. Confirm that the public definition excludes injected parameters, that the runtime supplies the expected context and that malicious extra fields cannot alter it. Test both invoke and ainvoke as appropriate for the tool. Verify context reconstruction after a supported resume path without storing raw dependencies in checkpointed state.
Run separate service-level tests for resource permissions, stale membership, cancellation, timeouts and isolation. Then use an approved synthetic provider test to verify actual tool-call generation. Treat the result as a deployment-specific compatibility check, not proof of universal model behavior.
Version the tool name, argument schema, dependency contract and policy revision. If a dependency interface changes, test compatibility across all tools that consume it. Keep model-facing metadata stable unless a deliberate behavioral change is needed.
Interview-ready answer#
I define an application-owned context type, register it with create_agent through context_schema and pass an authenticated context instance at invocation. Inside the decorated tool I annotate a runtime parameter using ToolRuntime[ContextType] and access runtime.context. The model supplies only task arguments; the framework supplies the runtime parameter. I inspect the actual model-facing schema to verify exclusion and validate untrusted arguments independently. I inject a narrow authorized repository rather than a global client, enforce tenant and resource permissions at the service boundary, and test missing context, override attempts, sync/async calls and concurrent tenant isolation. Context injection helps preserve the boundary, but it does not authenticate a caller or replace authorization.
Official documentation research leads and verification status#
- LangChain tools
- LangChain runtime
- LangChain agents
- LangChain API reference
- Pydantic models
- Pydantic strict mode
- Python asyncio tasks and to_thread
Authorized offline research exception applied. These are official documentation research leads, not live-accessed sources. Actual local tests ran with Python 3.13.5 and Pydantic 2.13.5: 10 scenarios passed. LangChain, langchain_core and langgraph were absent, so ToolRuntime wiring, model-facing schema exclusion in the actual SDK, provider integration and current signatures were not executed or verified. Mermaid diagrams are standard triple-backtick fenced blocks, but live rendering and public website display were not verified. All identities, repositories and invoice statuses are synthetic.
References
- 1.LangChain toolsdocs.langchain.com
- 2.LangChain runtimedocs.langchain.com
- 3.LangChain agentsdocs.langchain.com
- 4.LangChain API referencereference.langchain.com
- 5.Pydantic modelsdocs.pydantic.dev
- 6.Pydantic strict modedocs.pydantic.dev
- 7.Python asyncio tasks and to_threaddocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps