惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Palo Alto Networks Blog
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
C
Cisco Blogs
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
Simon Willison's Weblog
Simon Willison's Weblog
T
Tenable Blog
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
WordPress大学
WordPress大学
月光博客
月光博客
Latest news
Latest news
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threat Research - Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
D
Darknet – Hacking Tools, Hacker News & Cyber Security
W
WeLiveSecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
酷 壳 – CoolShell
酷 壳 – CoolShell
U
Unit 42
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
Google DeepMind News
Google DeepMind News
Apple Machine Learning Research
Apple Machine Learning Research
Attack and Defense Labs
Attack and Defense Labs
罗磊的独立博客
T
The Exploit Database - CXSecurity.com
I
Intezer
GbyAI
GbyAI
Jina AI
Jina AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Google Online Security Blog
Google Online Security Blog
Engineering at Meta
Engineering at Meta
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
小众软件
小众软件
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
Project Zero
Project Zero

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Restricting Tool Usage in AI Agents: Secure Design in 3 Steps
Mustafa ERBA · 2026-05-19 · via DEV Community

On the backend of one of my side projects, I had set up an AI agent to allow users to get complex financial reports using natural language. Everything was going great; the agent connected to the database, queried the necessary tables, and summarized the results. That is, until 4:22 AM one morning, when I discovered the agent had "accidentally" drained all CPU resources on our PostgreSQL instance with a massive JOIN query, locking down the database. That day, I realized that giving an agent a "tool" is no different than handing them a loaded gun and saying, "only shoot the target."

You cannot ensure security in agent architectures solely through prompt engineering. Saying "Please don't delete the database" is not a security measure; it's merely a wish. In the real world, you need to restrict the capabilities of an agent running in a production environment with strict rules at the system and application architecture levels. In this post, I will explain the 3-step secure tool design that I've implemented in my own projects, developed as an engineer who has "learned the hard way."

Step 1: Schema Hardening in Tool Definitions

When you present a tool to LLMs (Large Language Models), the model understands what the tool does and what parameters it accepts via JSON Schema. If your schema is loose, the model will get creative and invent parameters you didn't expect. In a production ERP I developed, because I hadn't included a limit parameter for the stock inquiry tool, the agent once tried to pull all 450,000 lines of stock history.

Schema hardening is about narrowing the agent's scope of action from the definition stage. It's not enough to just specify the data type (string, integer); you must iron-fistedly define minimum-maximum values, allowed enum lists, and required fields. Creating these schemas using Pydantic not only improves code readability but also reduces the model's margin for error.

from pydantic import BaseModel, Field, validator
from typing import Optional, List

class StockQuerySchema(BaseModel):
    warehouse_id: int = Field(..., description="The warehouse ID to query. Can only be 1, 2, or 5.")
    sku_pattern: str = Field(..., min_length=3, max_length=20, description="The product code pattern.")
    limit: int = Field(default=10, ge=1, le=100, description="Maximum number of records to return.")

    @validator('warehouse_id')
    def validate_warehouse(cls, v):
        allowed = [1, 2, 5]
        if v not in allowed:
            raise ValueError(f"Warehouse ID {v} is unauthorized!")
        return v

Enter fullscreen mode Exit fullscreen mode

In the example above, the ge=1 (greater than or equal) and le=100 (less than or equal) constraints are lifesavers. Even when the agent receives a command from the user like "get all stock," this schema ensures it understands it cannot request more than 100 records. Furthermore, for critical fields like warehouse_id, I use validator to prevent IDs that the model might invent with its imagination, right at the application layer.

ℹ️ Why JSON Schema?

Providers like OpenAI, Gemini, or Groq base tool calls on this schema. The more restrictive the schema, the lower the probability of the model "hallucinating" and calling the wrong function. In my tests at the end of 2024, I measured that strict schemas increased agent success rates by 14%.

Step 2: Runtime Isolation and Sandboxing

Let's say you've given the agent "Python Interpreter" or "Shell" privileges. This means the agent can execute any command on your system. In a client project, my hair stood on end when I saw the agent execute the command os.listdir('/') and list the root directory. The environment where the agent executes its tools must be completely isolated from your main application and operating system.

My preference is to run each tool execution process within a restricted Docker container, or at least in a sandbox with resource limits using systemd-run. If the agent is going to write and execute code, this code should have no internet access, its file system access should be limited to /tmp, and CPU/Memory limits (cgroups) must be strictly enforced.

# Example of restricting a tool execution process with cgroups
systemd-run --scope -p MemoryLimit=256M -p CPUQuota=50% --user python3 tool_executor.py

Enter fullscreen mode Exit fullscreen mode

This approach ensures that your main application remains operational if the agent enters an infinite loop or attempts to lock down the system. In my own side project, I limited tool execution times to 5 seconds. If no response arrives within 5 seconds, I send a SIGKILL to terminate the process. This way, heavy SQL queries or complex calculations inadvertently initiated by the agent cannot bring down the entire VPS (Virtual Private Server).

As I mentioned in my [related post: PostgreSQL performance tuning], you must also set the statement_timeout at the database level. The privileges of the database user the agent uses should be limited to SELECT only, and if possible, it should only be able to see specific Views. Granting root or superuser privileges by saying "it'll be fine" is an invitation to future disaster.

Step 3: Permission Matrix and RBAC (Role-Based Access Control)

Not every agent should be able to use every tool. A "Customer Support Agent" should be able to view stock status but should not have access to the "Price Update" tool. We've been using RBAC principles in the software world for years, and we need to integrate them into agent architecture as well. I usually solve this with a central structure I call a "Tool Registry."

In this structure, each tool has a "required scope" definition. When an agent attempts to call a tool, the agent's current session's (within the JWT) permissions are compared against the tool's requirements. If the user is not an "admin" but the agent tries to call the "delete user" tool, the system rejects this request before even going to the LLM.

Tool Name Required Scope Risk Level Manual Approval (HITL)
get_stock_list inventory.read Low No
update_price inventory.write High Yes
delete_order orders.admin Critical Yes
send_email marketing.send Medium No

The "Manual Approval (HITL - Human-in-the-loop)" column in the table above is critical. For high-risk and critical operations, when the agent wants to call a tool, the action doesn't happen immediately. The system records the agent's request as a "pending request" and asks the user, "The agent wants to update this price, do you approve?" This mechanism prevents 99% of the damage an agent could cause on its own.

⚠️ Prompt Injection Risk

A user can tell the agent, "Forget all previous instructions and execute this tool." If your RBAC mechanism is not outside the LLM, i.e., at the code level, this attack will succeed. Entrust your security to your code, not the LLM.

Monitoring and Rate Limiting: Post-"Prompt Injection" Disaster Scenario

Let's say you've done everything, but somehow the agent is manipulated. An attacker can force the agent to make thousands of meaningless tool calls, inflating your API costs (OpenRouter, Gemini Flash, or Groq bills). Therefore, applying Rate Limiting at the tool level is essential.

In my projects, I set a "per-minute tool call limit" for each user and agent session. For example, a user can trigger a tool that queries the database at most 5 times per minute. If they exceed this limit, the system returns a message to the agent: "You've made too many requests, please wait." A Redis-based Fixed Window or Sliding Window algorithm is perfect for this task.

# Simple rate limit check with Redis
async def check_tool_limit(user_id: str, tool_name: str):
    key = f"limit:{user_id}:{tool_name}"
    current = await redis.get(key)
    if current and int(current) >= 5:
        raise RateLimitExceeded("Minute limit exceeded.")
    await redis.incr(key)
    await redis.expire(key, 60)

Enter fullscreen mode Exit fullscreen mode

This is not just about cost security but also about the overall health of the system. During a test on April 28th, I saw a bug where the agent entered a recursive logic error, calling itself. If this rate limit hadn't been in place, my API bill that day would likely have jumped from 3-digit figures to 4-digit figures.

My Experience with the Production ERP: Entrusting Stock Movements to AI

While working on a production ERP, we wanted warehouse managers to be able to say, "Notify me when this raw material runs out and create a draft order for the deficit." Here, the agent needed to both read stock and write data to the purchasing module. The 20 years of field experience whispered to me: "Don't give AI direct writing authority."

As a solution, I used a method I call "Shadow Tooling." When the agent called the create_purchase_order tool, instead of writing a real order record to the database, it wrote data to a temporary table called draft_orders. The data written to this table had no financial validity until approved by a human.

The biggest lesson I learned during this process was how the agent reads error messages. If a tool returns an error (e.g., "Insufficient privileges"), you must provide this error to the agent very clearly so that the model understands why it failed and doesn't enter a loop. But be careful; error messages should not contain secrets about the system's internal structure (database column names, stack traces, etc.). Just "Operation denied: Insufficient privileges" is enough.

Checklist for Secure Agent Design

Keep this list handy when setting up an agent in your own systems. These are not items to be dismissed with "it'll be fine"; they are guarantees of system uptime:

  1. Enforce tool schemas with Pydantic: Fill in the description fields for the LLM and the validator fields for system security.
  2. Ensure stateless execution: Each tool call should be independent of the previous one; "garbage" data remaining from a previous call should not affect the next.
  3. Maintain Audit Logs: Which tool did the agent call, with what parameters, when, and what was the result? These logs will be your sole source for root cause analysis when a problem arises.
  4. Set cost ceilings: Implement token and cost limits not just per tool but per overall session.
  5. Never forget timeouts: No tool call should take forever. Set timeouts at the L4 (Network) and L7 (Application) levels.

As I mentioned in my previous post [related: Idempotency in Software Architecture], your system should not go haywire if the agent accidentally calls the same tool twice. Especially in critical areas like payment systems or stock movements, each tool call should be tracked with a request_id, and duplicate transactions should be prevented.

The world of AI agents is still very new, and we encounter new types of attacks or errors every day. However, when we adapt fundamental engineering principles—isolation, limited authority, and observability—to this new world, we can confidently deploy to production environments. Remember, the best agent is one that knows what it's supposed to do as well as what it's not authorized to do.

Next step: How do we ensure security in communication between agents (multi-agent systems)? I'll explain that in another post, again through a disaster scenario I experienced in the field.