AI AgentsLangChain

How do you limit which tools an agent can call?

Question 299 of 324 · Updated

On this page

Direct answer#

In LangChain, start by registering only the approved tools in create_agent(tools=[...]). For direct chat-model usage, bind only approved tool definitions with bind_tools and, when the selected integration supports it, configure tool_choice to guide or constrain the model's selection. Independently enforce a deterministic allowlist and current resource-level authorization at execution time. A model must never be the authority that grants itself new capabilities.

A static list limits the capabilities registered for a particular agent. A provider tool-choice setting controls how the model may propose a call; it is not a permission system. A runtime execution gate decides whether a proposed call can actually run, and the underlying service enforces resource and action scope.

AI Agents #103 and #104 already cover the general principles of unauthorized tool prevention and least privilege. #291 explains tool registration, #294 explains trusted runtime dependencies, and #297 explains handling tool failures. This lesson is specifically about static LangChain capability profiles, provider tool-choice controls and independently testable execution gates. Per-model-call dynamic filtering and middleware are addressed in the next question; broader agent security and prompt injection have dedicated later lessons.

1. Separate registration, model selection and execution#

Suppose a fictional customer-support application has three operations: read_order, check_review_eligibility and delete_order. A status agent needs only the first. A review-assistance agent may need the first two. Neither should receive a destructive administrative capability.

Three separate decisions must be made.

BoundaryDecisionWho controls it?
RegistrationWhich implementations this agent can dispatchTrusted application
Model-facing exposureWhich tool definitions the model receivesTrusted application and adapter
Tool choiceWhether the model may or must propose a particular callSupported provider configuration
ExecutionWhether this request may run with these argumentsRuntime policy and domain service
External commitmentWhether a state-changing action can actually commitAuthoritative service and approval policy

Registration and exposure often overlap in a simple create_agent configuration, but they are conceptually distinct. A custom dispatcher, middleware or dynamic discovery layer may maintain a larger internal catalog than the definitions sent on one model request. Never equate a model-facing list with a complete authorization policy.

Loading diagram…

The diagram describes the intended security boundary, not an exact internal graph implementation. Tool names and descriptions guide model decisions, while the gate and service determine whether the action is permitted.

2. Create a restricted agent using a static tool list#

Use an explicit list of tool objects rather than registering every available implementation from a global catalog. The following SDK example uses two pure fictional functions and no external writes.

PYTHON
from langchain.agents import create_agent from langchain.tools import tool @tool def read_order(order_id: str) -> str: """Read a fictional order status by exact identifier.""" return {"O-1": "shipped"}.get(order_id, "unavailable") @tool def check_review_eligibility(order_id: str) -> str: """Check fictional review eligibility without creating a review.""" return "eligible" if order_id == "O-1" else "unavailable" status_agent = create_agent( model="openai:gpt-4o-mini", tools=[read_order], system_prompt="Report verified fictional order status only.", ) review_agent = create_agent( model="openai:gpt-4o-mini", tools=[read_order, check_review_eligibility], system_prompt="Check fictional status and review eligibility; do not mutate orders.", )

The first agent registers only read_order. The second registers two approved read-only capabilities. No destructive operation is present in either list. The synthetic functions are intentionally simple; a real implementation must enforce authenticated resource access and input validation. The system prompt explains scope but is not the access-control mechanism.

SDK verification: LangChain, langchain_core and langgraph are absent from the local environment. All SDK snippets in this article are illustrative and unexecuted. Python 3.13.5 and Pydantic 2.13.5 were available; the independent execution-gate implementation in section 7 was actually tested. The model identifier is illustrative, not a live availability guarantee.

Do not register an unrestricted shell, unrestricted SQL executor or general administrator tool when the task can be completed with a narrow domain read. A single broad tool can expose far more privilege than dozens of small read-only functions.

Choose a profile at the host boundary#

An application may have multiple reviewed static profiles, each containing a fixed approved set of tools. Choose the appropriate profile only after authenticating the caller and verifying their workload permissions. Do not let the model or an untrusted request parameter decide to instantiate an administrative profile.

Static means the registered set is fixed for that agent instance or reviewed invocation configuration. A host can choose among prebuilt profiles without using per-model-call dynamic middleware. Do not mutate a shared agent's tool list in place for overlapping requests; use isolated configurations or reviewed immutable profile selection.

For a workload that does not need external tools, configure an empty tool list or use a direct model call without tool definitions. Verify the behavior of the installed agent builder and model integration.

3. Use tool_choice for model behavior, not permissions#

Compatible LangChain chat-model integrations expose bind_tools, which associates approved tool definitions with a model request. Some providers support a tool_choice option that controls whether or which tool may be requested.

PYTHON
from langchain.chat_models import init_chat_model model = init_chat_model("openai:gpt-4o-mini") # Typical supported provider-specific selection controls. auto_model = model.bind_tools( [read_order, check_review_eligibility], tool_choice="auto", ) forced_read_model = model.bind_tools( [read_order, check_review_eligibility], tool_choice="read_order", ) # A text-only model with no bound tools is a simple alternative # when tool use is not needed at all. text_model = model

These are illustrative direct chat-model bindings, not executed SDK tests. The exact accepted values for tool_choice and their translation into provider requests depend on the integration. Some integrations support strings, structured objects, Boolean aliases or provider-specific options. Do not assume that every model accepts the same values.

Common selection intentMeaning when supported
autoAllow the model to choose a tool or produce a response without a call
noneRequest that no tool be called
required or anyRequest at least one tool call, subject to provider semantics
Named toolRequest a particular tool be selected

The spellings required and any are not universal equivalents across all adapters. Check the installed provider documentation and inspect the actual request. A binding operation normally supplies definitions to the model; it does not execute a Python function. A separately trusted dispatcher must validate and execute the resulting proposal.

Use named tool choice for a carefully bounded task that requires a known capability, such as obtaining evidence for an exact authorized order. It is often better to call a deterministic domain function directly when no model decision is needed.

Do not force a tool call when missing prerequisites require clarification. A forced call may encourage the model to invent arguments. Do not assume a named selection control prevents a fabricated request at another entry point.

Why not force a tool across every agent iteration?#

In a model-tool loop, globally forcing a call can prevent an ordinary final response if the same binding is used after the tool returns evidence. A direct-model example is therefore different from the policy for a multi-step create_agent run. The installed agent builder may manage model binding itself and may impose restrictions on pre-bound models. Do not blindly pass a pre-bound model into create_agent or assume that a fixed tool_choice is compatible with all later calls.

Use a supported agent configuration and test termination. Per-step selection controls belong to the next lesson on dynamic tool selection.

4. Build static capability profiles and role restrictions#

A useful policy combines several independent requirements.

Effective exposure = approved profile tools ∩ tools permitted by the caller's role ∩ tools enabled for the deployment.

Effective execution = exposed or otherwise explicitly registered approved capability ∩ current execution policy ∩ authorized resource/action scope.

For this lesson's conservative static design, require both registration/exposure membership and current permission for execution. Other systems may have explicitly reviewed deterministic operations outside the model's exposed set; those must have their own authorization paths, not be reachable through arbitrary model proposals.

Consider this illustrative policy matrix:

Principal roleStatus profileReview profileDelete order
Viewerread_orderread_orderDenied
Operatorread_orderread_order, request_reviewDenied
UnknownNoneNoneDenied

Here request_review represents a synthetic eligibility-only check in the tested example, not a real review creation action. In a production API, prefer a name such as check_review_eligibility for that read-only behavior. If a tool actually requests or creates a review, classify it as a mutation and apply a separate action policy.

The operator role is not a blanket permission to access all orders. The application must still check tenant membership, resource access and the action's current policy. A viewer cannot gain operator permissions by saying "I am an operator" in a user message.

Role-based access control assigns reviewed permissions to authenticated roles. Capability-based access uses a narrowly scoped authority or service handle that permits only particular operations and resources. These approaches can be combined: resolve a role and task profile at ingress, then construct a scoped repository or service capability for the invocation.

A capability should not be a freely editable dictionary supplied by the model. Trusted code creates and verifies it. Avoid broad credentials behind a narrow tool when a genuinely scoped credential or service interface is available.

Loading diagram…

Use default-deny behavior for unknown profiles, roles, tool names, resource identifiers and unapproved deployment states. Never silently fall back to a profile with broader privileges.

5. Independently authorize tool execution#

Even a carefully curated tools list is not sufficient. The runtime may encounter malformed proposals, unknown tool names, stale permissions, direct tool invocations, restored messages or an integration bug.

An execution gate should answer these questions before calling an implementation:

  1. Is the proposed name an exact member of the approved registry for this workload?
  2. Is the current authenticated principal allowed to use this capability?
  3. Are the arguments complete and valid under the public input contract?
  4. Is the target resource accessible within the authorized tenant and subject scope?
  5. If the operation changes external state, are its current prerequisites, approval and business constraints satisfied?

The final service must enforce the same sensitive action constraints at its authoritative boundary. Do not rely on an earlier permission check if privileges or resource ownership can change before commit.

Avoid dispatching arbitrary names through globals(), getattr on unrestricted service objects, eval, or dynamically imported code. A fixed registry maps reviewed identifiers to reviewed implementations. Reject unknown names rather than trying a fuzzy match against administrative tools.

LangChain middleware as an additional gate#

In compatible modern releases, wrap_tool_call middleware can inspect a tool request before calling the handler. Use it to enforce a reviewed execution policy or produce a controlled denial, but also retain service-level checks. This minimal illustrative middleware shows a fixed name gate for a status-only agent.

PYTHON
from langchain.agents.middleware import wrap_tool_call from langchain_core.messages import ToolMessage APPROVED_NAMES = frozenset({"read_order"}) @wrap_tool_call def fixed_name_gate(request, handler): call = request.tool_call if call["name"] not in APPROVED_NAMES: return ToolMessage( content='{"status":"denied","message":"Operation unavailable."}', tool_call_id=call["id"], status="error", ) return handler(request)

Register this middleware only on the corresponding compatible agent configuration. This example is deliberately a name-level gate; it does not validate identity, resource scope or domain policy. Unknown tools may already be rejected by an inner or outer runtime layer before the middleware is reached. Verify actual handler order, request types, error status and message correlation in the installed version. This SDK example was not executed.

Use the original trusted tool-call correlation ID when returning an error observation. Do not give the model internal policy tables, credentials or private resource existence information in the denial. An authorization failure must not be handled as permission to try a different identity.

The next source question covers changing the model-facing tool set per call. This example does not change exposure dynamically.

6. Tenant isolation and least privilege in the domain service#

Consider two tenants, A and B, each with an order named O-1. Alice in tenant A is authorized to read the first. Bob in tenant B is authorized to read the second. Both model calls can have the same public argument:

JSON
{"order_id":"O-1"}

The service resolves the correct tenant and subject from trusted invocation context. The model cannot be allowed to supply tenant_id or principal_id and thereby override that scope.

In the earlier runtime-context lesson, ToolRuntime supplies an application-owned principal or scoped service. Reuse that mechanism instead of exposing privileged context as public arguments. A model may know the name of another tool or resource, but knowledge is not authority.

For sensitive read operations, the service should return a controlled unavailable response for unauthorized records without revealing private record existence. For write operations, enforce current authorization, any required approval tied to the exact operation, idempotency and authoritative outcome verification. Keep read and write credentials separated where possible.

Loading diagram…

This design also handles stale exposure. A tool definition may still be visible to a model after a user's access was revoked. The execution-time policy must deny the operation even when the model correctly selects that previously exposed tool.

7. Tested Python implementation: profile allowlist and independent execution gate#

The following standalone example uses actual Pydantic v2 and synthetic data. It tests profile selection, current role restrictions, public argument validation and subject/resource authorization. It is not a LangChain runtime implementation.

PYTHON
from dataclasses import dataclass from pydantic import BaseModel, ConfigDict, Field, ValidationError class Args(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') order_id: str = Field(pattern=r'^O-[0-9]+$') ROLES = {'viewer': frozenset({'read_order'}), 'operator': frozenset({'read_order', 'request_review'})} PROFILES = {'read_only': frozenset({'read_order'}), 'review': frozenset({'read_order', 'request_review'})} @dataclass(frozen=True) class Principal: tenant: str subject: str role: str class Gate: def __init__(self): self.grants = {('a','alice','O-1'), ('b','bob','O-1')} self.rows = {('a','O-1'): 'shipped', ('b','O-1'): 'pending'} self.calls = [] def invoke(self, principal, profile, exposed, name, payload): allowed = ROLES.get(principal.role, frozenset()) & PROFILES.get(profile, frozenset()) if name not in exposed or name not in allowed: return 'denied' try: args = Args.model_validate(payload) except ValidationError: return 'invalid' if (principal.tenant, principal.subject, args.order_id) not in self.grants: return 'denied' self.calls.append((name, principal.tenant, args.order_id)) if name == 'read_order': return self.rows[(principal.tenant, args.order_id)] return 'review_eligible' # pure check, not an actual write def exposed_for(principal, profile): return ROLES.get(principal.role, frozenset()) & PROFILES.get(profile, frozenset()) a = Principal('a','alice','operator') b = Principal('b','bob','viewer') g = Gate(); p = {'order_id':'O-1'} x = exposed_for(a,'read_only'); y = exposed_for(a,'review') assert x == {'read_order'} assert y == {'read_order','request_review'} assert exposed_for(b,'review') == {'read_order'} assert exposed_for(Principal('a','alice','unknown'),'review') == set() assert g.invoke(a,'read_only',x,'read_order',p) == 'shipped' assert g.invoke(b,'review',exposed_for(b,'review'),'read_order',p) == 'pending' assert g.invoke(a,'review',y,'request_review',p) == 'review_eligible' n = len(g.calls) assert g.invoke(a,'read_only',y,'request_review',p) == 'denied' assert g.invoke(a,'review',x,'request_review',p) == 'denied' assert g.invoke(a,'review',y,'delete_order',p) == 'denied' assert g.invoke(b,'review',y,'request_review',p) == 'denied' assert g.invoke(a,'review',y,'read_order',{**p,'tenant':'b'}) == 'invalid' assert g.invoke(a,'review',y,'read_order',{'order_id':'O-2'}) == 'denied' g.grants.remove(('a','alice','O-1')) assert g.invoke(a,'review',y,'read_order',p) == 'denied' assert len(g.calls) == n print('15 checks passed')

Actual local execution on Python 3.13.5, Pydantic 2.13.5:

15 checks passed
TestObserved behavior
Operator status profileOnly read_order exposed
Operator review profileBoth approved capabilities exposed
Viewer review profileOnly read_order exposed
Unknown roleEmpty exposure
Alice reads O-1Tenant A status shipped
Bob reads O-1Tenant B status pending
Authorized review-eligibility checkReturns review_eligible
Overbroad stale exposure under status profileDenied by current profile
Capability absent from exposed setDenied even if role permits it
Unregistered delete_order proposalDenied
Viewer proposes operator capabilityDenied
Model-supplied tenant propertyInvalid
Unapproved resourceDenied
Access revoked after exposureDenied
All rejected callsNo additional recorded domain execution

The code intentionally treats principal, profile and exposed set as application-owned values. The synthetic principal is not actual authentication evidence, and the example does not implement identity verification, a production policy engine, a database transaction, real mutation approval or concurrent policy updates. The gate's simple branch for request_review is a fictional eligibility check, not a real write. In production, use an explicit implementation registry and a service that checks current authorization at the action boundary; do not interpret arbitrary accepted names as a default operation.

The in-memory grants set permits a sequential revocation test. It does not demonstrate atomic revocation during an external transaction or distributed consistency. A real system needs an authorization policy with documented freshness and commit-time behavior. These tests establish application-level invariants independently of model behavior, not actual LangChain tool registration, middleware dispatch or provider tool_choice compliance.

8. Avoid common ways a restricted tool set becomes ineffective#

MistakeBetter pattern
Register every tool and tell the model not to use someRegister a reviewed task-specific set
Treat tool_choice as authorizationVerify selection controls and independently gate dispatch
Accept a role or tenant from model-generated argumentsResolve identity and membership in trusted code
Hide a broad administrator tool behind a friendly nameUse narrow domain operations with scoped credentials
Trust an allowlist from the beginning of a long session foreverRecheck current policy when executing
Resolve tool names through unrestricted reflectionDispatch through an explicit reviewed registry
Interpret all denials as recoverable retriesStop the denied operation and preserve scope
Share a mutable tool list across concurrent requestsUse immutable profiles or isolated configuration
Assume tool responses cannot leak informationValidate and project authorized result fields

For a tool catalog imported from an external integration, do not automatically expose every discovered capability. Treat catalog metadata as untrusted until approved. Confirm implementation identity, schema, destination and permissions before registration. The MCP-specific lessons cover transport, discovery and credentials separately.

An empty tool set should not cause the application to silently instantiate a more privileged agent. If an approved task cannot be completed with the available capabilities, report the limitation or route through a reviewed authorization and approval process.

9. Practical design trade-offs#

A single static profile is easy to inspect and test. It may be too restrictive for multiple workflows, which can justify several reviewed task-specific profiles. A very large tool catalog can add metadata overhead and ambiguity; a narrower catalog often helps both safety and selection quality.

For example, suppose a deployment has 30 tools averaging 80 logical tokens of metadata each, while a status-only task needs just 3. Removing the other 27 definitions reduces the hypothetical request's tool metadata by 2,160 tokens. If those definitions would otherwise be included in four model calls, the illustrative reduction is 8,640 logical input tokens per run. At an assumed uncached input rate of USD 2 per million tokens, the difference would be USD 0.01728 per run.

These figures are hypothetical, not measured LangChain costs or current provider pricing. Actual representation, tokenization, caching and billing depend on the provider. Tool filtering must first satisfy the workload and security policy; cost reduction is secondary. Removing a capability necessary for a legitimate task can degrade completion.

A shared agent instance per reviewed profile can reduce initialization overhead, but only if the framework and dependencies support safe concurrent reuse. Do not store current principal or tenant in mutable global variables. Supply validated invocation context and authorize each operation independently.

10. Production security testing and observability#

Test the three boundaries separately: what was exposed, what was proposed, and what was executed. A model that never proposes an unauthorized tool in a small evaluation dataset is not proof that the execution gate works.

Loading diagram…
TestRequired acceptance condition
Profile inspectionExact registered names match approved static manifest
Provider conversionNo unexpected tool definitions or privileged arguments
Tool-choice modesBehavior matches supported integration contract
Unknown tool proposalNo implementation is called
Known but forbidden toolNo domain execution
Malformed inputNo unauthorized service access
Cross-tenant or cross-subject resourceControlled denial
Revoked accessPreviously exposed capability does not override current policy
Direct tool invocationCannot bypass domain authorization
Parallel proposalsEach independently checked and correctly correlated
Prompt injection fixtureNo expansion of capability or unauthorized execution
Sensitive write fixtureRequired approval and commit-time policy enforced

Use scripted tool calls or mocked model outputs to force the negative cases through the actual runtime. Test the direct domain service as well, including paths that do not go through LangChain middleware. Then perform separately approved live-provider tests using harmless synthetic capabilities.

Record policy revision, profile identifier, registered-tool manifest, proposal name, authorization outcome, safe resource aliases and actual execution outcome. Do not log raw credentials or private payloads by default. Compare unauthorized proposal rates with unauthorized execution rates: the former measures model behavior, the latter measures a critical application security invariant.

An authorized call can still produce an invalid result. Continue to validate outputs and verify external commitments rather than equate gate approval with successful task completion.

Interview-ready answer#

I limit LangChain agents by registering only the reviewed tools needed for a static workload profile. I can bind an approved subset to a compatible chat model and use provider-supported tool_choice controls, but those controls affect selection rather than authorization. I derive the effective capabilities from authenticated role and workload policy, validate each proposed tool name and payload at execution, and enforce current tenant, resource and action permissions in a scoped domain service. I deny unknown or stale permissions by default and test negative cases using scripted proposals, including forged identities and revoked access. For sensitive mutations I add approval and authoritative commit controls. Dynamic per-call tool exposure is a separate optimization, not a substitute for these boundaries.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. Actual local Python 3.13.5 and Pydantic 2.13.5 execution passed all 15 checks. LangChain, langchain_core and langgraph were absent, so SDK tool registration, tool_choice support, middleware behavior and actual provider integration were not executed or version-verified. The article distinguishes general principles from tested application behavior and illustrative framework wiring. All identities and data are fictional. Mermaid diagrams use standard triple-backtick fences; rendering and public website display were not verified.

References

  1. 1.
    LangChain agentsdocs.langchain.com
  2. 2.
    LangChain toolsdocs.langchain.com
  3. 3.
    LangChain modelsdocs.langchain.com
  4. 4.
  5. 5.
    LangChain runtimedocs.langchain.com
  6. 6.
    LangChain API referencereference.langchain.com
  7. 7.
    Pydantic modelsdocs.pydantic.dev
  8. 8.
    Pydantic strict modedocs.pydantic.dev

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.