T
traeai
登录
返回首页
Machine Learning Mastery

在Python代理中实现权限控制的工具调用

7.5Score
在Python代理中实现权限控制的工具调用

TL;DR · AI 摘要

文章介绍了如何在Python代理系统中实现权限控制的工具调用机制,提供具体代码示例和安全策略。

核心要点

  • 使用装饰器实现权限验证,确保工具调用前进行身份检查
  • 通过配置文件管理权限规则,提升系统可维护性
  • 结合JWT令牌实现细粒度访问控制

结构提纲

按章节快速跳转。

  1. 介绍权限控制在代理系统中的重要性。

  2. 描述使用装饰器实现权限验证的具体方法。

  3. 说明如何通过配置文件管理权限规则。

  4. 讨论结合JWT令牌实现细粒度访问控制的方案。

思维导图

用一张图看清主题之间的关系。

查看大纲文本(无障碍 / 无 JS 友好)
  • Python代理系统权限控制
    • 权限验证机制
      • 装饰器实现
    • 配置管理
      • 配置文件
    • 安全实践
      • JWT令牌

金句 / Highlights

值得收藏与分享的关键句。

#Python#安全#权限控制
打开原文

Implementing Permission-Gated Tool Calling in Python Agents - MachineLearningMastery.com

Implementing Permission-Gated Tool Calling in Python Agents - MachineLearningMastery.com

[Navigation](https://machinelearningmastery.com/implementing-permission-gated-tool-calling-in-python-agents/#navigation)

Image 2: MachineLearningMastery.com

Making developers awesome at machine learning

Image 3

Making Developers Awesome at Machine Learning

Click to Take the FREE Crash-Course

*

Making developers awesome at machine learning

Click to Take the FREE Crash-Course

Image 4

Making Developers Awesome at Machine Learning

Click to Take the FREE Crash-Course

*

Image 5: Go from Data to Strategy: Tepper School of Business

Go from Data to Strategy: Tepper School of Business

Implementing Permission-Gated Tool Calling in Python Agents

By[Iván Palomares Carrascosa](https://machinelearningmastery.com/author/ivanpc/ "Posts by Iván Palomares Carrascosa")on May 8, 2026 in[Artificial Intelligence](https://machinelearningmastery.com/category/artificial-intelligence/ "View all items in Artificial Intelligence")0

Share _Post_ Share

In this article, you will learn how to implement a human-in-the-loop permission gate for autonomous AI agents using a Python decorator pattern.

Topics we will cover include:

  • Why high-stakes tool calls in AI agents require human oversight, and how a decorator-based approach addresses this cleanly.
  • How to build a @requires_approval decorator that intercepts tool execution and requests explicit human confirmation before proceeding.
  • How this pattern scales toward production environments, such as replacing the CLI prompt with asynchronous webhooks or admin dashboards.
Image 6: Implementing Permission-Gated Tool Calling in Python Agents

Implementing Permission-Gated Tool Calling in Python Agents

Introduction

AI agents have evolved beyond passive chatbots. They are nowadays built as active software entities that can perform actions autonomously, such as executing external code. Unsurprisingly, there is an overall risk increase associated with these autonomous tool-calling capabilities.

Low-risk actions such as querying a weather API are usually run in the background and are deemed safe. Meanwhile, high-stakes actions like initiating financial transactions, manipulating a database, or delivering emails require much more rigorous oversight mechanisms. One such strategy to address this is to inject a middle human-in-the-loop layer.

This article illustrates how to implement a permission-gated tool in a Python agent, relying completely on built-in language functionality. The result: a robust, cost-free interception mechanism based on a simple decorator pattern.

Our example solution will not hardcode safety checks directly into the agent’s main reasoning loop or within the business logic. Instead, we will use a Python decorator named @requires_approval. This decorator acts as a gateway: if the agent tries to use a wrapped tool, the gateway interrupts the execution flow, displays the arguments to a human decision-maker, and awaits explicit approval.

The proposed implementation relies fully on Python’s functools library, with no paid services or external APIs required when run locally.

The Python Decorator Function

The first part of the code defines our main Python decorator function. It wraps a function and adds a “human approval” layer before executing the function passed as an argument, func. When any other function (which we will define later) is decorated with @requires_approval, the decorator will print a security alert message, show the proposed arguments, and request the user’s approval or denial through a simple text input — ‘y’ for approval, ‘n’ for denial.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22 import functools

1. Interceptor (Middle Layer)

def requires_approval(func):

"""Decorator to pause execution and request human validation."""

@functools.wraps(func)

def wrapper(*args,**kwargs):

print(f"\n[SECURITY ALERT] Agent attempting high-risk action: '{func.__name__}'")

print(f"-> Proposed Arguments: args={args}, kwargs={kwargs}")

Simulating Human-in-the-Loop via CLI input

approval=input("-> Approve this execution? (y/n): ").strip().lower()

if approval=='y':

print("[SYSTEM] Action approved. Executing...\n")

return func(*args,**kwargs)

else:

print("[SYSTEM] Action blocked by human overseer.\n")

Returning a string to let the agent know the tool failed

return"ERROR: Tool execution blocked by administrator."

return wrapper

The Agent’s Tools

Next, we define two functions that constitute the agent’s available tools. For simplicity, they simulate tool use by an agent rather than relying on real external tools.

  1. The first one, intended for retrieving the current date and time, is deemed a low-risk tool and can be executed autonomously.
  2. The second one — which simulates permanently deleting a table in a database — is labeled a high-risk operation. We decorate it so that before its execution, the previously defined decorator intercepts the call and requests human approval.

1

2

3

4

5

6

7

8

9# 2. Defining the Agent's Tools

def get_current_time(timezone):

"""Low-risk tool: Can be executed autonomously."""

return f"The simulated time in {timezone} is 10:00 AM."

@requires_approval

def drop_database_table(table_name):

"""High-risk tool: Guarded by the HITL decorator."""

return f"SUCCESS: Table '{table_name}' has been permanently deleted."

Running The Simulation

Next, simulate_agent() contains a simulated sequence of actions an agent would typically perform by calling the two tools defined above. Log messages will be printed throughout the process.

1

2

3

4

5

6

7

8

9

10# 3. Simulating the Agent's Execution Pipeline

def simulate_agent():

print("Agent Log: User asked for the time.")

time_result=get_current_time("UTC")

print(f"Tool Result: {time_result}\n")

print("Agent Log: User asked to clear the staging database.")

Agent's attempt to call the high-risk tool

db_result=drop_database_table(table_name="staging_users")

print(f"Tool Result: {db_result}")

We are now ready to run the simulation. We define a main block that invokes the simulated agent workflow:

1

2

3# Run the simulation

if __name__ =="__main__":

simulate_agent()

The following output is obtained — note that the user has typed ‘y’ in the interface to approve execution after the security alert was triggered:

1

2

3

4

5

6

7

8

9

10

11 Agent Log:User asked for the time.

Tool Result:The simulated time in UTC is 10:00 AM.

Agent Log:User asked to clear the staging database.

[SECURITY ALERT]Agent attempting high-risk action:'drop_database_table'

->Proposed Arguments:args=(),kwargs={'table_name':'staging_users'}

->Approve this execution?(y/n):y

[SYSTEM]Action approved.Executing...

Tool Result:SUCCESS:Table'staging_users'has been permanently deleted.

Simple but effective. One question you might be asking is: how does this middle-layer solution scale? The decorator-based strategy scales nicely for production environments. You may want to replace the simple input() call inside the wrapper with an asynchronous webhook. The wrapper could send a payload to an internal admin dashboard or even to a Slack channel, passing the function name and its arguments. The agent will keep waiting for the webhook’s response — a human approval or denial from the comfort of a mobile phone.

Wrapping Up

In this article, I showed you the core programmatic ideas behind implementing a permission-gated tool-calling mechanism for autonomous AI agents using a Python decorator — a practical approach for controlling the execution of high-risk tasks that may require human approval.

Share _Post_ Share

More On This Topic

Image 13: Iván Palomares Carrascosa

#### About Iván Palomares Carrascosa

**Iván Palomares Carrascosa** is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.

View all posts by Iván Palomares Carrascosa →

The Roadmap to Mastering Tool Calling in AI Agents

##### No comments yet.

Leave a Reply [Click here to cancel reply.](https://machinelearningmastery.com/implementing-permission-gated-tool-calling-in-python-agents/#respond)

Comment *

Name (required)

Email (will not be published) (required)

Δ

Image 14

Welcome!

I'm _Jason Brownlee_ PhD

and I help developers get results with machine learning.

Read more

#### Never miss a tutorial:

![Image 15: LinkedIn](https://www.linkedin.com/company/machine-learning-mastery/)![Image 16: Twitter](https://twitter.com/TeachTheMachine)![Image 17: Facebook](https://www.facebook.com/MachineLearningMastery/)![Image 18: Email Newsletter](https://machinelearningmastery.com/newsletter/)![Image 19: RSS Feed](https://machinelearningmastery.com/rss-feed/)

#### Picked for you:

![Image 20: Tour of Deep Learning Algorithms](https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/)Your First Deep Learning Project in Python with Keras Step-by-Step

![Image 21](https://machinelearningmastery.com/machine-learning-in-python-step-by-step/)Your First Machine Learning Project in Python Step-By-Step

![Image 22: How to Develop LSTM Models for Time Series Forecasting](https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/)How to Develop LSTM Models for Time Series Forecasting

![Image 23: ARIMA Rolling Forecast Line Plot](https://machinelearningmastery.com/arima-for-time-series-forecasting-with-python/)How to Create an ARIMA Model for Time Series Forecasting in Python

![Image 24: Machine Learning Frustration](https://machinelearningmastery.com/machine-learning-for-programmers/)Machine Learning for Developers

#### Loving the Tutorials?

The EBook Catalog is where

you'll find the _Really Good_ stuff.

>> See What's Inside

Image 25

Machine Learning Mastery is part of Guiding Tech Media, a leading digital media publisher focused on helping people figure out technology. Visit our corporate website to learn more about our mission and team.

© 2026 Guiding Tech Media All Rights Reserved

[](https://machinelearningmastery.com/implementing-permission-gated-tool-calling-in-python-agents/ "Close")

Start Machine Learning

You can master applied Machine Learning

without math or fancy degrees.

Find out how in this_free_and_practical_course.

Email Address *

  • [x] I consent to receive information about services and special offers by email. For more information, see the Privacy Policy.

Website

Start My Email Course

Thank you for signing up!

Please check your email and click the link provided to confirm your subscription.

Image 26

Do not sell or share my personal information.

You have chosen to opt-out of the sale or sharing of your information from this site and any of its affiliates. To opt back in please click the "Reenable Personalization" link.

This site collects information through the use of cookies and other tracking tools. Cookies and these tools do not contain any information that personally identifies a user, but personal information that would be stored about you may be linked to the information stored in and obtained from them. This information would be used and shared for Analytics, Ad Serving, Interest Based Advertising, among other purposes.

For more information please visit this site's Privacy Policy.

CANCEL

CONTINUE

Your Use of Our Content

The content we make available on this website [and through our other channels] (the “Service”) was created, developed, compiled, prepared, revised, selected, and/or arranged by us, using our own methods and judgment, and through the expenditure of substantial time and effort. This Service and the content we make available are proprietary, and are protected by these Terms of Service (which is a contract between us and you), copyright laws, and other intellectual property laws and treaties. This Service is also protected as a collective work or compilation under U.S. copyright and other laws and treaties. We provide it for your personal, non-commercial use only.

You may not use, and may not authorize any third party to use, this Service or any content we make available on this Service in any manner that (i) is a source of or substitute for the Service or the content; (ii) affects our ability to earn money in connection with the Service or the content; or (iii) competes with the Service we provide. These restrictions apply to any robot, spider, scraper, web crawler, or other automated means or any similar manual process, or any software used to access the Service. You further agree not to violate the restrictions in any robot exclusion headers of this Service, if any, or bypass or circumvent other measures employed to prevent or limit access to the Service by automated means.

×

Information from your device can be used to personalize your ad experience.

Do not sell or share my personal information.

Terms of Content Use

AI 可能会生成不准确的信息,请核实重要内容

在Python代理中实现权限控制的工具调用 | Machine Learning Mastery | traeai