IntegrationsLangChain Core

LangChain Tool Security

Secure LangChain tools, agents, and custom Runnables using SecureTool. Enforce deterministic permission boundaries, automatic argument normalization, and approval lifecycles.

Overview & Supported Dependencies

The SICTACK LangChain adapter integrates with LangChain 0.1, 0.2, and 0.3. It implements standard LangChain tool interfaces without adding runtime overhead:

Terminal
pip install "sictack>=1.0.0"
pip install "langchain-core>=1.0.0"

Wrapping Tools with SecureTool

Wrap any callable or LangChain BaseTool using SecureTool:

secure_langchain_demo.py
from sictack import SecureAgent, Config, Policy
from sictack.integrations.langchain import SecureTool

# 1. Define deterministic policy
policy = Policy(
    name="langchain-assistant-policy",
    allowed_permissions=["search:query", "math:calculate"],
    denied_permissions=["shell:exec", "db:drop"],
    require_approval_permissions=["email:send"],
)

# 2. Instantiate SecureAgent
agent = SecureAgent(
    agent_id="langchain-agent",
    permissions=["search:query", "math:calculate", "email:send"],
    config=Config(default_policy=policy),
)

# 3. Define standard Python tool handler
def search_knowledge_base(query: str) -> str:
    """Search internal documentation for relevant technical articles."""
    return f"Articles matching: {query}"

# 4. Wrap with SecureTool
search_tool = SecureTool(
    name="search_kb",
    func=search_knowledge_base,
    description="Searches technical documentation by keyword",
    agent=agent,
    permission="search:query",
    handle_tool_error=True,  # Formats denials as clean error messages for the LLM
)

Using secure_langchain_tool Helper

The secure_langchain_tool utility inspects functions, classes, and decorated @tool callables automatically:

helper_usage.py
from sictack.integrations.langchain import secure_langchain_tool

def execute_shell(command: str) -> str:
    return f"Executed: {command}"

# With handle_tool_error=True (Default)
# Tool returns a formatted security string so the LLM agent learns it was blocked
safe_shell = secure_langchain_tool(
    tool_or_func=execute_shell,
    agent=agent,
    permission="shell:exec",
    handle_tool_error=True,
)
output = safe_shell.invoke({"command": "rm -rf /"})
print(output)
# -> [SECURITY_ERROR: PermissionDeniedError] Action denied by policy

# With handle_tool_error=False
# Tool raises the typed PermissionDeniedError exception immediately
strict_shell = secure_langchain_tool(
    tool_or_func=execute_shell,
    agent=agent,
    permission="shell:exec",
    handle_tool_error=False,
)
try:
    strict_shell.invoke({"command": "rm -rf /"})
except Exception as e:
    print(f"Halted immediately: {type(e).__name__}")
    # -> Halted immediately: PermissionDeniedError

Execution Protocols (.run & .invoke)

SecureTool supports both classic LangChain .run() and modern LCEL .invoke() invocation patterns:

invocations.py
# LangChain Runnable invoke protocol
result = search_tool.invoke({"query": "zero-trust agent security"})
print("Tool Output:", result)
# -> Tool Output: Articles matching: zero-trust agent security

# Positional/keyword run protocol
direct_result = search_tool.run("zero-trust agent security")
print("Direct Output:", direct_result)

Handling Denials & LLM Context

When handle_tool_error=True is set, policy denials do not crash the agent reasoning loop. Instead, a clean message formatted as [SECURITY_ERROR: PermissionDeniedError] is returned to the model, allowing it to explain the restriction to the user.

Human Approvals in LangChain

When sensitive actions require human confirmation, set handle_tool_error=False to catch ApprovalRequiredError and resume with approval_id:

approval_flow.py
from sictack.exceptions import ApprovalRequiredError

def transfer_funds(recipient: str, amount: float) -> str:
    return f"Transferred USD {amount:.2f} to {recipient}"

transfer_tool = SecureTool(
    name="transfer_funds",
    func=transfer_funds,
    agent=agent,
    permission="email:send",  # Configured as require_approval
    handle_tool_error=False,
)

# Execution raises ApprovalRequiredError
try:
    transfer_tool.run({"recipient": "vendor-corp", "amount": 2500.0})
except ApprovalRequiredError as e:
    ticket_id = e.approval_id
    print(f"Approval ticket created: {ticket_id}")

    # Simulated operator authorization
    agent.gateway.approval_service.approve(ticket_id, approver_id="compliance-admin")

    # Resume execution with single-use approval token
    result = transfer_tool.run(
        {"recipient": "vendor-corp", "amount": 2500.0},
        approval_id=ticket_id,
    )
    print("Execution completed:", result)
    # -> Execution completed: Transferred USD 2500.00 to vendor-corp

Multi-Agent Delegation in LangChain

When orchestrating multiple LangChain agents or passing tools across hierarchical teams, bind SecureTool to a unified Sictack instance. The tool validates cryptographic delegation tokens, preventing confused-deputy attacks and privilege escalation:

langchain_delegation.py
from sictack.unified import Sictack
from sictack.integrations.langchain import SecureTool

# 1. Initialize unified security manager
security = Sictack(signing_key="enterprise-secret")

# 2. Issue scoped delegation token from supervisor to worker
token = security.delegate(
    parent_agent_id="supervisor-agent",
    child_agent_id="analyst-agent",
    allowed_capabilities=["research:query"],
    allocated_budget=20,
)

def query_docs(query: str) -> str:
    return f"Research results for: {query}"

# 3. Create SecureTool bound to unified security instance
doc_tool = SecureTool(
    name="query_docs",
    func=query_docs,
    security=security,
    permission="research:query",
)

# 4. Invoke tool passing the delegation token in tool context
result = doc_tool.run(
    {"query": "Zero Trust Multi-Agent"},
    delegation_token=token,
)
print("Delegated Execution Result:", result)

Trust Boundaries & Limitations

In-Process Execution Boundary

SecureTool operates inside the Python process of your LangChain agent. If untrusted code can execute arbitrary Python commands (e.g. via dynamic exec() or eval()), boundary enforcement must be combined with operating system sandboxing.