Method and system for code security auditing based on agent tool invocation loop
Patent Information
- Application Number
- CN202611086604.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-21
- Publication Date
- 2026-10-27
AI Technical Summary
采用智能体工具调用循环机制,实现多轮迭代深度推理,模拟人类安全研究员的审计思维过程,可发现传统规则匹配工具无法检测的逻辑漏洞与业务漏洞,显著提升漏洞检出率。采用子任务边界约束下的多专用智能体分工式工具调用循环机制,区别于通用ReAct范式的单智能体开放域执行模式,既实现了多轮迭代深度推理、模拟人类安全研究员的审计思维过程,可发现传统规则匹配工具无法检测的逻辑漏洞与业务漏洞,又避免了通用ReAct范式任务漂移、资源耗散的缺陷,显著提升漏洞检出率与审计执行稳定性。
Smart Images

Figure CN122987012A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of network security technology, and in particular to the application of artificial intelligence technology in code security auditing, specifically a code security auditing method and system based on intelligent agent tool call loop. Background Technology
[0002] With the rapid development of the software industry, code security issues have become increasingly prominent, and code security auditing has become a crucial link in ensuring the security of the software supply chain. Existing code security auditing technologies mainly suffer from the following shortcomings: Traditional static code analysis (SAST) tools rely on rule matching mechanisms, which can only detect known vulnerability patterns and cannot discover logical or business vulnerabilities, resulting in a low vulnerability detection rate.
[0003] Existing tools lack deep semantic analysis capabilities, making it difficult to trace the propagation path of taints across methods and modules, resulting in a large number of false alarms and requiring security personnel to invest a lot of time in manual verification.
[0004] Existing AI-SAST (Artificial Intelligence-Assisted Static Code Auditing) solutions fall into two categories, neither of which can meet the needs of enterprise-level deep code auditing: One type adopts a single-round question-and-answer style large-model reasoning mode, which can only perform single analysis based on input code snippets. It cannot simulate the multi-round iterative reasoning process of human security researchers, cannot autonomously call tools for code navigation, path tracing, and vulnerability verification, and has insufficient deep semantic analysis capabilities, making it difficult to discover cross-module logic vulnerabilities. The other type adopts a single-agent open-domain architecture based on the general ReAct paradigm (such as the AutoGPT-type autonomous agent solution), which has not been specifically designed for code auditing scenarios. It suffers from defects such as easily uncontrollable agent task boundaries, undirected tool calls, lack of structured accumulation mechanism for audit results, and inability to conduct parallel collaboration among multiple tasks. It also has poor execution stability and serious resource consumption, making it unsuitable for enterprise-level large-scale code auditing scenarios.
[0005] The audit process is rigid and inflexible, making it impossible to customize audit strategies according to the characteristics of different projects. Audit experience is difficult to accumulate and reuse, resulting in slow improvement of the team's overall audit capabilities.
[0006] The separation between code security and infrastructure security makes it difficult to quickly link vulnerabilities to affected operational assets after they are discovered, and makes it hard to assess the actual scope and risk level of vulnerabilities.
[0007] Existing AI-driven code auditing solutions are mostly based on black-box intelligent agent reasoning. External entities can only obtain the final output results, lacking standardized observable interfaces and verifiable output features. This makes it difficult to prove infringement and has poor verifiability after the solution is implemented, which is not conducive to rights protection and compliance verification.
[0008] Therefore, there is an urgent need for a code security auditing method and system that can achieve deep semantic analysis, low false positive rate, and full-process automation. Summary of the Invention
[0009] To achieve the above objectives, the present invention adopts the following technical solution: A code security auditing method based on agent tool call loops includes the following steps: S1: Create an audit session for the target code, bind the preset audit rule set, and initialize the global context and audit artifact storage area; S2: Schedule multiple function-oriented dedicated agents to execute well-defined audit sub-tasks according to task dependencies; S3: Each agent enters an independent closed-loop tool call loop within the boundary of its subtask: The agent generates a targeted tool call request based on the current subtask context, the platform executes the corresponding code analysis tool operation and returns the structured result, the agent updates the subtask context based on the returned result and generates the next tool call request, and repeats the loop until the subtask is completed or the preset termination condition is reached. S4: After each agent completes its execution, it generates a standardized structured audit product and stores it in the global product storage area. Downstream agents directly read the upstream structured product as task input, avoiding repeated code analysis operations. S5: Perform multiple rounds of cross-validation on candidate vulnerabilities, dynamically adjust vulnerability confidence scores, and filter out false alarms below the threshold; S6: Generate a complete audit report.
[0010] Furthermore, the multiple dedicated intelligent agents adopt a layered architecture, including a control layer, an analysis layer, and an output layer.
[0011] Furthermore, the tools that can be invoked in the tool call loop include an integrated development environment toolset and a code property graph toolset. The integrated development environment toolset includes tools for reading file content, jumping to symbol definitions, floating type queries, reference lookup, global symbol search, and call hierarchy analysis. The code property graph toolset includes tools for querying node attributes, analyzing call point conditional branches, and expanding call chains bidirectionally.
[0012] Furthermore, the method is based on an architecture that separates the control plane and the execution plane. The control plane provides verifiable tool service capabilities to the outside world through a standardized and unified tool call interface, and is responsible for task scheduling, agent management, tool services and result processing. The execution plane includes a lightweight Go language execution agent and a containerized scanning engine. The execution agent connects to the control plane through secure encrypted communication at the transport layer, and is responsible for starting the scanning engine and reporting the execution results.
[0013] Furthermore, the tool call loop specifically includes: S31: The agent receives the current subtask target and context information, and loads the whitelist of callable tools and termination judgment rules corresponding to the subtask. S32: The agent determines whether to call the tool under the constraints of the subtask objective. If not, it directly outputs the structured subtask result. S33: If a tool needs to be invoked, the agent generates a standardized tool invocation request, including the tool name, parameters, and execution target; S34: The platform tool service layer parses tool call requests and executes the corresponding tool operations; S35: The platform returns the tool execution results to the agent in a structured format; S36: The agent updates the subtask context based on the tool execution result, and repeats steps S32 to S35 until the subtask is completed or the maximum number of iterations is reached.
[0014] Furthermore, the audit deliverables are structured deliverables, including the following five categories: system context, which includes the target project's technology stack, architectural patterns, and threat model; code map, which includes a file tree structure and method signature index; entry point set, which includes a list of entry points such as Hypertext Transfer Protocol endpoints and event handlers; additional vulnerability point rules, which include custom vulnerability point rules discovered by the agent; and audit report, which includes vulnerability summaries and remediation suggestions.
[0015] Furthermore, the dynamic adjustment of vulnerability confidence scores specifically includes: weighting each candidate vulnerability path based on the code snippets returned by the tool call, call chain information, security guard conditions, and parameter filtering; marking a high-confidence vulnerability when the confidence score is higher than a first threshold, triggering an additional tool call loop for deep verification when the score is between the first and second thresholds, and automatically marking a false alarm and filtering it when the score is lower than the second threshold; the confidence scores of all remaining vulnerabilities are structured and output along with the audit report to form an independently verifiable list of scored vulnerabilities.
[0016] Furthermore, it also includes multi-language taint path tracing steps: for Java / Kotlin, it constructs method indexes and call points based on code property graphs to trace taint propagation paths across methods; for Python, it uses abstract syntax tree analysis to trace taint propagation in asynchronous functions and across modules; for TypeScript, it uses export-import chain parsing to parse module-level method call chains; the path analysis results for all languages are output in a unified standardized format, including entry points, vulnerability points, intermediate jump nodes, and confidence scores.
[0017] Furthermore, it also includes an automatic desensitization step for AI content: during the input and output phases of the intelligent agent, private keys, JSON Web tokens, bearer tokens, basic authentication credentials in Uniform Resource Locators, application interface keys in JavaScript object representation, secret keys, password fields, intranet Internet Protocol addresses and internal domain names are filtered in real time; the desensitization rules are configured through environment variables, including custom mask strings and replacement upper limit parameters.
[0018] Furthermore, it also includes token usage control steps: real-time tracking of AI token consumption by project and audit session dimensions, displaying the input token quantity, output token quantity, and total token quantity of the current session on the research dashboard; when token consumption reaches a preset threshold, it automatically triggers a degradation strategy that shuts down deep analysis, reduces the number of iterations, or switches to a lightweight model.
[0019] Furthermore, it also includes a vulnerability governance linkage step: converting verified vulnerabilities into structured issue tickets, and through an externally observable manifest issue ticket enhancement mechanism, converting audit issue tickets containing entry points, vulnerability point rules, verification tracing links, summaries and remediation suggestions in the research mode into global vulnerability discovery in the management mode; synchronizing the severity level, status and handling information of vulnerabilities, and carrying out vulnerability allocation, tracking and closed-loop governance in the management mode.
[0020] A code security auditing system that implements any of the methods described above includes: The audit session management module is used to create and manage audit sessions, bind audit rule sets, and maintain the global context and audit artifact storage area. The agent scheduling module is used to schedule multiple dedicated agents to execute audit sub-tasks; The tool call loop engine drives each agent to perform multiple rounds of iterative tool calls and inference processes. The unified tool service module is used to provide standardized and verifiable unified tool call interfaces to the outside world, and to encapsulate and provide integrated development environment tools and code property graph tools; The vulnerability verification module is used to verify candidate vulnerabilities in multiple rounds, dynamically adjust the vulnerability confidence score, and filter false positives. The content desensitization module is used to perform the automatic content desensitization step using artificial intelligence; The token usage control module is used to execute token usage control steps; The vulnerability governance linkage module is used to execute vulnerability governance linkage steps and realize the observable improvement and transformation of the global vulnerability work order in the research mode audit issue unidirectional management mode. The results output module is used to generate a complete audit report that can be independently verified, carrying a confidence score for each vulnerability.
[0021] Compared with the prior art, the present invention has the following beneficial effects: Employing an agent-based tool invocation loop mechanism, multi-round iterative deep reasoning is achieved, simulating the auditing thought process of human security researchers. This enables the discovery of logical and business vulnerabilities that traditional rule-matching tools cannot detect, significantly improving the vulnerability detection rate. The multi-agent, division-of-labor tool invocation loop mechanism, constrained by subtask boundaries, differs from the single-agent open-domain execution mode of the general ReAct paradigm. It achieves multi-round iterative deep reasoning, simulating the auditing thought process of human security researchers, and discovering logical and business vulnerabilities that traditional rule-matching tools cannot detect. Furthermore, it avoids the task drift and resource dissipation defects of the general ReAct paradigm, significantly improving the vulnerability detection rate and audit execution stability.
[0022] By employing a multi-round vulnerability verification and dynamic confidence assessment mechanism, and combining multi-dimensional data such as code snippets, call chain information, and security guard conditions for comprehensive judgment, the false alarm rate is significantly reduced, and the workload of manual verification is greatly reduced.
[0023] Generates various types of structured audit products, enabling the accumulation and reuse of audit knowledge, avoiding redundant calculations, significantly improving code audit efficiency, and greatly reducing manual audit costs.
[0024] It adopts a control plane and execution plane separation architecture, supports distributed deployment and horizontal scaling, integrates multiple code analysis tools and supports mainstream development languages, and realizes closed-loop management of the entire process of auditing and vulnerability governance. Through standardized and unified tool call interfaces, verifiable audit reports with confidence, and work order improvement mechanisms from research mode to management mode, it solves the problem of poor infringement determination of pure black box intelligent agent solutions, which facilitates compliance verification and infringement evidence collection.
[0025] It has a built-in AI-powered automatic content desensitization mechanism to prevent the leakage of sensitive information and meet the needs of industries with strict data security requirements, such as finance, government, and energy. Attached Figure Description
[0026] Figure 1 This is an overall flowchart of the code security auditing method based on the intelligent agent tool call loop of the present invention; Figure 2 This is a detailed flowchart of the tool call loop for a single intelligent agent in this invention; Figure 3 This is a diagram of the hierarchical multi-agent collaborative architecture in this invention; Figure 4 This is a diagram illustrating the separation of the control plane and execution plane in the system of this invention. Figure 5 This is a flowchart of the dynamic confidence score and vulnerability verification process in this invention. Detailed Implementation
[0027] The specific embodiments of the present invention will be further described below with reference to the accompanying drawings. It should be noted that these descriptions are for the purpose of aiding understanding the present invention, but do not constitute a limitation thereof. Furthermore, the technical features involved in the various embodiments of the present invention described below can be combined with each other as long as they do not conflict with each other.
[0028] Example 1 This embodiment provides a code security auditing method based on intelligent agent tool call loops. The overall process is as follows: Figure 1 As shown, this method can be deployed in the research mode of a security governance platform for deep automated auditing of target code repositories.
[0029] 1. Audit session initialization (step S1) When a user initiates an audit request for a target code repository and a specified commit version (such as a code commit hash) through the web console, the system first creates an audit session. This session has a unique session identifier and is bound to a preset audit rule set. The rule set contains built-in vulnerability trigger point rules, such as matching rules for common vulnerability types like Structured Query Language injection, command injection, and path traversal.
[0030] Simultaneously, the system initializes the global context and audit artifact storage area. The global context is a key-value pair storage structure used to store shared information throughout the audit process, such as the identified technology stack, the list of analyzed modules, and token consumption statistics. The audit artifact storage area is used to persist the following five types of structured artifacts, supporting reuse in subsequent sessions.
[0031] 2. Schedule multiple dedicated intelligent agents to execute audit sub-tasks (step S2) The system adopts a hierarchical multi-agent collaborative architecture, the components of which are as follows: Figure 3 As shown, it comprises twenty-one specialized intelligent agents. In this embodiment, they are organized into three layers: a control layer, an analysis layer, and an output layer. The control layer comprises a task scheduling agent, a resource management agent, and a token control agent. The task scheduling agent parses the user-selected workflow (e.g., "deep full scan" or "fast static scan"), generates a directed acyclic graph of task dependencies, and sequentially activates downstream agents. The resource management agent monitors the executor load and dynamically allocates computing resources. The token control agent tracks token consumption of the large language model by project and session dimensions, displays the number of input tokens, output tokens, and total tokens in real-time on a dashboard, and triggers a degradation strategy (e.g., disabling deep attribute graph analysis and retaining only integrated development environment (IDE) tool analysis) when a preset threshold is reached.
[0032] The analysis layer includes agents for framework detection, code indexing, entry point extraction, taint path tracing, vulnerability verification, remediation suggestion, custom rule mining, multi-language analysis, dependency scanning, configuration auditing, permission checking, vulnerability priority ranking, sandbox verification, code similarity analysis, and compliance checking. This embodiment focuses on describing the execution of the analysis layer in detail.
[0033] Output layer: includes agents for generating problem forms, generating reports, and de-identifying data.
[0034] The aforementioned 15 analytical agents are functionally divided into a basic analysis group, a vulnerability detection group, and a verification and optimization group. The basic analysis group is responsible for collecting basic project information (framework detection, code indexing, dependency scanning, and configuration auditing). The vulnerability detection group is responsible for core vulnerability discovery (entry point extraction, taint path tracing, permission checks, custom rule discovery, and multi-language analysis). The verification and optimization group is responsible for vulnerability quality control and compliance verification (vulnerability verification, sandbox verification, vulnerability priority ranking, code similarity analysis, compliance checks, and remediation suggestions). The agents in each group achieve data flow and collaboration through structured audit products.
[0035] The aforementioned intelligent agents belong to the core functional modules of the system: the control layer intelligent agent belongs to the token usage management module and the intelligent agent scheduling module; the analysis layer intelligent agent belongs to the tool call loop engine and the vulnerability verification module; the data desensitization intelligent agent in the output layer belongs to the content desensitization module; the issue ticket generation intelligent agent belongs to the vulnerability governance linkage module; and the report generation intelligent agent belongs to the result output module.
[0036] 3. Each agent enters an independent tool invocation loop (step S3) Step S3 is one of the core technical features of this invention. It is important to clarify that the tool invocation loop mechanism in this step differs fundamentally from both existing AI-SAST solutions: Compared to single-round question-and-answer AI solutions, this invention achieves multi-round iterative reasoning through closed-loop tool invocation, autonomously acquiring code semantic information and progressively verifying vulnerabilities, possessing deep semantic analysis and logical vulnerability mining capabilities; compared to the single-agent open-domain solution of the general ReAct paradigm, this invention adopts a multi-specialized agent division of labor mode. Each agent's tool invocation loop is strictly constrained within the boundaries of its corresponding audit sub-task, only calling tools within the whitelist of code auditing tools. Furthermore, standardized structured products enable information flow and collaboration between agents, eliminating the need for a single agent to cover the entire audit process, significantly improving audit execution efficiency, result stability, and reproducibility.
[0037] Each agent runs in an independent tool call loop, with the loop execution flow as follows: Figure 2 As shown, the specific implementation of this loop is as follows (taking the tainted path tracing agent as an example): Sub-step 3.1: Receive the subtask target and context The taint path tracing agent obtains its task objective from the global context and upstream artifacts (e.g., a list of entry points for the agent's output, and the system context for the framework's detection of the agent's output): starting from a given entry point (e.g., obtaining user parameters from a Hypertext Transfer Protocol endpoint), it traces whether the data flow can reach the vulnerability point (e.g., a database execution method) without being filtered by security guards. Before a subtask begins, the task scheduling agent loads the corresponding whitelist of callable tools (e.g., the taint path tracing agent is not authorized to call the global symbol search tool) and termination rules (e.g., maximum number of iterations N or time threshold T) from the platform configuration library based on the subtask type. This whitelist is then passed to the agent as part of the initialization context, serving as a hard boundary constraint for the tool invocation loop.
[0038] Sub-step 3.2: Determine if it is necessary to call the tool. The agent's built-in decision-making logic is based on the information already collected. If there is enough information to determine whether a path is reachable or not, the result is output directly; otherwise, external tools are called to obtain more code information.
[0039] Sub-step 3.3: Generate standardized tool invocation requests When a tool needs to be invoked, the agent generates a tool invocation request that conforms to the platform protocol. The request format is structured text, which includes the tool name, parameters, and session identifier.
[0040] Sub-step 3.4: The platform tool service layer executes tool operations. The platform's tool service layer (deployed within the code audit gateway) receives requests and invokes the corresponding tools. For example, the symbol definition navigation tool locates symbol definitions based on the language server protocol and returns the file path and location of the definition.
[0041] Sub-step 3.5: Return the tool execution result The tool returns the execution results to the agent in a structured text format, including whether the execution was successful and the returned data (such as definition location and type information).
[0042] Sub-step 3.6: Update the context and repeat the loop. The agent integrates the returned results into its internal context and updates part of the inference state. For example, if it finds that a user parameter has been passed to an update method of another service class, it needs to continue tracing from that method. Then it jumps back to sub-step 3.2 and repeats the loop until a termination condition is met (e.g., a vulnerability is found, the path is confirmed to be blocked by a security guard, or the maximum number of iterations is reached, or a time threshold is reached, etc., as termination criteria).
[0043] The toolset that can be invoked in this embodiment includes two types: Integrated Development Environment (IDE) code navigation toolset: file content reading, symbol definition jumping, type hover search, reference lookup, global symbol search, and call hierarchy analysis. These tools are implemented based on the language server protocol and provide code navigation capabilities at the same level as the IDE.
[0044] Code Attribute Graph Toolset: Node attribute query, call point conditional branching and security guard analysis, and bidirectional call chain expansion. These tools are based on a code attribute graph engine that integrates abstract syntax trees, control flow graphs, and program dependency graphs, enabling deep semantic analysis across methods and classes.
[0045] 4. Generate structured audit products for downstream reuse (step S4) After each agent completes its execution, it outputs the analysis results as structured audit artifacts and stores them in the audit artifact storage area. This embodiment defines five types of artifacts: System context: generated by the framework detection agent, including the target project's technology stack (such as development framework and its version), architectural patterns (such as model-view-controller pattern, microservice architecture), threat model, etc.
[0046] Code map: Generated by a code indexing agent, it includes a file tree structure and method signature indexes. Optionally, a large language model can be invoked to generate a natural language summary for each method to assist subsequent agents in quickly understanding the code's functionality.
[0047] Entry Point List: Generated by extracting agents from entry points, this list includes all externally invoked entry points, such as Hypertext Transfer Protocol routes (e.g., Uniform Resource Locators in Request Map annotations), message queue processors, and scheduled tasks. Each entry point records its parameter type, return value type, and access permissions.
[0048] Additional vulnerability rules: generated by a custom rule-mining agent. This agent calls a large language model to analyze sensitive functions unique to the project (such as custom encryption functions or database operation encapsulations), discovers new vulnerabilities not included in the built-in rule base, and stores them as supplementary rules for subsequent path tracing.
[0049] Audit report: The final output of the report generation agent, which includes vulnerability summary, detailed findings, and remediation recommendations.
[0050] Downstream agents (such as vulnerability verification agents) proactively read upstream artifacts before execution. For example, a vulnerability verification agent directly uses an entry point list and code map to avoid repeatedly indexing code.
[0051] 5. Verify candidate vulnerabilities in multiple rounds, dynamically adjust confidence scores, and filter false positives (step S5). Each candidate vulnerability path output by the tainted path tracing agent carries an initial confidence score. This score is calculated by weighting factors such as path length, the strength of security guards along the path (e.g., the presence of regular expression validation and permission checks), and the controllability of entry point parameters (e.g., whether they originate from user input). This embodiment employs the following dynamic adjustment mechanism, and the scoring and verification process is as follows: Figure 5 As shown: Feature extraction: For each candidate path, the conditional branch analysis tool is called to obtain the conditional branch information of each call point (such as format validation of user input), the file content reading tool is called to read the relevant code snippets, and the reference lookup tool is called to check whether the parameters are processed by the filtering function.
[0052] Weighted scoring: Define the initial score. If a security guard exists on the path and the guard is determined to be strongly validated (e.g., the regular expression is limited to alphanumeric characters and has a fixed length), a certain number of points are deducted; if the guard can be bypassed (e.g., the validation only checks for non-empty values), a smaller number of points are deducted; if no guards exist, the score is increased. In addition, a small number of points are deducted for every certain number of hops the call chain length exceeds.
[0053] Threshold comparison: Set a first threshold and a second threshold, for example, set the first threshold to 0.8 and the second threshold to 0.4.
[0054] If the score is higher than or equal to the first threshold, it is marked as a high-confidence vulnerability and directly enters the report generation queue.
[0055] If the score falls between the first and second thresholds, an additional tool call loop is triggered for deep validation. The validation agent initiates a new tool call loop specifically for tainted reachability simulation of that path, such as attempting to construct an actual attack vector and checking if it will be intercepted. The score is recalculated after validation.
[0056] If the score is below the second threshold, it is automatically marked as a false alarm and filtered out from the results set.
[0057] Through the above dynamic adjustments, this embodiment can significantly reduce the false alarm rate, and after sandbox verification, the false alarm level can be further significantly reduced.
[0058] 6. Generate a complete audit report (Step S6) The report-generating agent collects all verified high-confidence vulnerabilities, categorizes them by vulnerability type and severity, and generates a structured report. The report supports DOCX, PDF, and HTML formats and supports bilingual (Chinese and English) output. Each report includes a detailed description of each vulnerability, a complete tracing path from the entry point to the vulnerability, relevant code snippets, remediation suggestions, and a confidence score. All confidence scores are individually linked to each vulnerability entry and output in structured field format, allowing for independent verification without relying on internal agent reasoning processes, ensuring complete traceability and verifiability. Remediation suggestions can be generated by the remediation suggestion agent using a large language model to produce specific code examples (e.g., changing string concatenation to parameterized queries).
[0059] Other key features supplemented In addition to the above six basic steps, this embodiment also integrates the following important technical features: Multilingual tainted path tracing: This embodiment automatically selects different path analyzers based on the language of the target code.
[0060] For Java or Kotlin projects, use a code property graph-based analyzer: build a code property graph, traverse nodes via scripts, and track complex semantics such as field sensitivity and alias relationships.
[0061] For Python projects, an abstract syntax tree-based analyzer is used, supporting the tracing of asynchronous functions and cross-module import chains.
[0062] For TypeScript or JavaScript projects, path analysis is performed by resolving module call chains based on export and import dependency graphs and combining them with type inference.
[0063] The path analysis results for all languages are output in a standardized format, including the entry point location, vulnerability location, list of intermediate jump nodes, and confidence level for each hop, facilitating unified processing by the agent in the future.
[0064] Automatic content anonymization via AI: During the input (sending code snippets to a large language model) and output (audit recommendations returned by the large language model) phases of the intelligent agent, the data anonymization agent filters sensitive information in real time. Anonymization rules include: identifying and replacing PEM-formatted private keys, network tokens, and bearer tokens; filtering basic authentication credentials and sensitive query parameters in Uniform Resource Locators (URLs); scanning application programming interface keys, secret keys, passwords, and other fields in structured data objects and replacing their values with anonymized tags; identifying internal network Internet Protocol addresses and internal domain names and replacing them with internal network address tags. Anonymization rules are configurable via environment variables, allowing customization of the mask string and the maximum number of replacements.
[0065] Token usage control and degradation: The token control agent calculates the token consumption of large language model calls in real time by project and session dimension. When session consumption approaches the threshold (e.g., less than 10% of tokens remain), a degradation strategy is automatically executed: first, the code property graph deep analysis tool is disabled, and only the integrated development environment code navigation tool is retained; if the threshold is still exceeded, the system switches to a lightweight large language model to continue the remaining analysis, ensuring that the audit task is not interrupted due to token exhaustion.
[0066] Linked Vulnerability Management: This embodiment supports elevating audit findings in research mode to global vulnerabilities in management mode. Specifically, when a user confirms a problem ticket as a genuine vulnerability, they click the "Elevate" button. This elevation operation is an externally observable, explicit business process, and the operation and data conversion are logged in a complete system log. The problem ticket generation agent converts the problem ticket (including entry point, vulnerability rules, verification and tracing links, summary, and remediation suggestions) into a unified vulnerability discovery in management mode, and automatically creates a work order through the built-in ticketing system or external integration (such as ZenTao), assigns responsibility, and tracks the remediation status. There is a one-to-one mapping between problem tickets in research mode and global vulnerabilities in management mode, and the conversion link can be fully verified through data records. This achieves a complete closed loop from code auditing to vulnerability management.
[0067] Example 2 In addition to the above-described method embodiments, the present invention also provides a code security auditing system for implementing the above methods. This embodiment describes the specific deployment architecture of the system.
[0068] The system adopts a design that separates the control plane and the execution plane, and the deployment architecture is as follows: Figure 4 As shown: The control plane is deployed on one or more server nodes, including: The server module, built on Java and the Spring Boot framework, is responsible for business logic such as authentication and authorization, audit session management, task orchestration and scheduling, scan result management, asset management, and invoice system. It communicates asynchronously with the execution plane via message queues.
[0069] Console module: A web application developed based on the Vue.js front-end framework, providing two user interfaces: management mode and research mode. It includes a workflow canvas editor (directed acyclic graph editor), asset topology visualization, scan task configuration, token usage dashboard, etc.
[0070] Artificial Intelligence Service Module: A microservice built on the Python language, it deploys an execution engine of 21 dedicated intelligent agents, responsible for driving the tool call loop and integrating the model context protocol with the interface of external large language models.
[0071] Code Audit Gateway: An independently deployed gateway service that provides a standardized, protocol-open, and externally observable unified tool call interface. The interface inputs and return results all conform to structured specifications and can be fully verified through packet capture or call logs. It encapsulates the calls to the language server, code attribute graph engine, and syntax parser, shielding the underlying details from the upper-layer intelligent agents.
[0072] Execution Agent Gateway: A gateway for secure encrypted communication at the transport layer, managing the connection pool, heartbeat detection, and reconnection after disconnection for all execution agents.
[0073] Content anonymization module: An independently deployed microservice that performs real-time filtering of sensitive information during the input and output phases of the agent. It supports configuring anonymization rules through environment variables, including custom mask strings and replacement upper limit parameters.
[0074] Token usage control module: Deeply integrated with the artificial intelligence service module, it tracks the consumption of large language model tokens in real time by project and audit session. When the token consumption reaches the preset threshold, it automatically triggers the degradation strategy.
[0075] Vulnerability Management Linkage Module: This module interfaces with the ticketing system of the server module and is responsible for converting audit issue forms in the research mode into global vulnerability discoveries in the management mode. It synchronizes the severity level, status, and processing information of vulnerabilities to achieve vulnerability allocation, tracking, and closed-loop management.
[0076] The execution plane includes: Execution Agent: A lightweight execution agent written in Go, deployed as a static binary file on a standalone virtual machine or physical machine (no containerization required). It communicates with the execution agent gateway through a transport layer secure encrypted channel, receives scan task instructions, and is responsible for launching the containerized scan engine, monitoring the engine's running status, collecting logs and scan results, and reporting them to the control plane.
[0077] Scanning Engine: Packaged as a container image, it provides a static code analysis engine and a software composition analysis engine by default. It also supports users to access custom engines through a standardized interface (only needing to provide the container image and the running script), such as self-developed key scanning tools or commercial static analysis tools.
[0078] In actual operation, after receiving an audit request from a user, the control plane creates an audit session, and the AI service module schedules the agent to perform analysis. When the agent needs to call code analysis tools, the AI service accesses the code audit gateway through an internal remote procedure call; when it needs to execute the scanning engine, the AI service sends the task to the execution agent gateway, which selects a suitable execution agent instance. The execution agent pulls the specified engine image, starts the container to perform the scan, and then compresses the results before returning them.
[0079] This decoupled architecture allows for horizontal scaling: as auditing tasks increase, the number of execution agent instances can be increased; when large language model calls are frequent, the number of artificial intelligence service instances can be increased. All communication uses transport layer security encryption to ensure data transmission security.
[0080] Example 3 The system of this invention can also integrate an asset management module to achieve end-to-end correlation between code vulnerabilities and infrastructure risks. This module is not a core step of this invention, but as a preferred embodiment, it can further enhance the practicality of the system.
[0081] When a code audit discovers a key leak (such as a cloud service access key) or a remote code execution vulnerability, the asset management module automatically performs the following actions: The asset topology map identifies runtime assets that may be affected by a key or vulnerability (e.g., which host environment variables the key is configured in, and which containers or servers the code corresponding to the vulnerability is deployed on). The asset data model is organized around three layers: hosts, services, and deployments. Each asset supports a snapshot mechanism to record its state at a specific point in time, and snapshot differences can be compared to track changes.
[0082] The system models network traffic and dependencies between assets based on topological edges; for example, one host can access another host's database port. When an asset is compromised, the system calculates all other reachable assets, generating an blast radius assessment report. Two assessment modes are supported: Baseline assessment: Calculate the scope of direct and indirect impact based on graph algorithms (such as breadth-first search).
[0083] AI-enhanced assessment: It calls upon large language models to analyze the feasibility of attack paths and generates a natural language assessment report in both Chinese and English.
[0084] If users need to export an asset list or impact assessment report, the system enforces a two-stage approval process (application and approval), and all export operations leave audit logs to meet compliance requirements.
[0085] Through the above extensions, the security governance platform of this invention can not only deeply audit code vulnerabilities, but also correlate vulnerabilities with asset risks in the actual operating environment, providing security teams with a complete risk management view.
[0086] The embodiments of the present invention have been described in detail above with reference to the accompanying drawings, but the present invention is not limited to the described embodiments. For those skilled in the art, various changes, modifications, substitutions, and variations can be made to these embodiments without departing from the principles and spirit of the present invention, and these variations still fall within the protection scope of the present invention.
Claims
1. A code security auditing method based on agent tool call loop, characterized in that, Includes the following steps: S1: Create an audit session for the target code, bind the preset audit rule set, and initialize the global context and audit artifact storage area; S2: Schedule multiple function-oriented dedicated agents to execute well-defined audit sub-tasks according to task dependencies; S3: Each agent enters an independent closed-loop tool call loop within the boundary of its subtask: The agent generates a targeted tool call request based on the current subtask context, the platform executes the corresponding code analysis tool operation and returns the structured result, the agent updates the subtask context based on the returned result and generates the next tool call request, and repeats the loop until the subtask is completed or the preset termination condition is reached. S4: After each agent completes its execution, it generates a standardized structured audit product and stores it in the global product storage area. Downstream agents directly read the upstream structured product as task input. S5: Perform multiple rounds of cross-validation on candidate vulnerabilities, dynamically adjust vulnerability confidence scores, and filter out false alarms below the threshold; S6: Generate a complete audit report.
2. The code security auditing method according to claim 1, characterized in that, The multiple dedicated intelligent agents mentioned in step S2 adopt a layered architecture, including a control layer, an analysis layer, and an output layer.
3. The code security auditing method according to claim 1, characterized in that, The tools that can be called in the tool call loop in step S3 include the integrated development environment toolset and the code property graph toolset. The integrated development environment toolset includes tools for reading file content, jumping to symbol definitions, floating type queries, reference lookup, global symbol search, and call hierarchy analysis. The code property graph toolset includes tools for querying node attributes, analyzing call point conditional branches, and expanding call chains bidirectionally.
4. The code security auditing method according to claim 1, characterized in that, The method is based on an architecture that separates the control plane and the execution plane. The control plane provides verifiable tool service capabilities to the outside world through a standardized and unified tool call interface, and is responsible for task scheduling, agent management, tool services and result processing. The execution plane includes a lightweight Go language execution agent and a containerized scanning engine. The execution agent connects to the control plane through secure encrypted communication at the transport layer, and is responsible for starting the scanning engine and reporting the execution results.
5. The code security auditing method according to claim 1, characterized in that, The tool call loop described in step S3 specifically includes: S31: The agent receives the current subtask target and context information, and loads the whitelist of callable tools and termination judgment rules corresponding to the subtask. S32: The agent determines whether to call the tool under the constraints of the subtask objective. If not, it directly outputs the structured subtask result. S33: If a tool needs to be invoked, the agent generates a standardized tool invocation request, including the tool name, parameters, and execution target; S34: The platform tool service layer parses tool call requests and executes the corresponding tool operations; S35: The platform returns the tool execution results to the agent in a structured format; S36: The agent updates the subtask context based on the tool execution result, and repeats steps S32 to S35 until the subtask is completed or the maximum number of iterations is reached.
6. The code security auditing method according to claim 1, characterized in that, The audit products mentioned in step S4 are structured products, including the following five categories: system context, which includes the target project's technology stack, architectural patterns, and threat model; code map, which includes the file tree structure and method signature index; and entry point set, which includes a list of entry points such as Hypertext Transfer Protocol endpoints and event handlers. Additional vulnerability rules, including custom vulnerability rules discovered by the agent; audit report, including vulnerability summary and remediation recommendations.
7. The code security auditing method according to claim 1, characterized in that, The dynamic adjustment of vulnerability confidence scores in step S5 specifically includes: weighting each candidate vulnerability path based on the code snippets returned by the tool call, call chain information, security guard conditions, and parameter filtering; marking a high-confidence vulnerability when the confidence score is higher than the first threshold, triggering an additional tool call loop for deep verification when the score is between the first and second thresholds, and automatically marking it as a false alarm and filtering it when the score is lower than the second threshold; and outputting the confidence scores of all remaining vulnerabilities in a structured manner along with the audit report to form an independently verifiable list of scored vulnerabilities.
8. The code security auditing method according to claim 1, characterized in that, It also includes multi-language taint path tracing steps: for Java / Kotlin, it constructs method indexes and call points based on code property graphs to trace taint propagation paths across methods; for Python, it uses abstract syntax tree analysis to trace taint propagation in asynchronous functions and across modules; for TypeScript, it uses export-import chain parsing to parse module-level method call chains; the path analysis results for all languages are output in a unified standardized format, including entry points, vulnerability points, intermediate jump nodes, and confidence scores.
9. The code security auditing method according to claim 1, characterized in that, It also includes an automatic desensitization step for artificial intelligence content: during the input and output phases of the intelligent agent, private keys, JSON Web tokens, bearer tokens, basic authentication credentials in Uniform Resource Locators, application interface keys in JavaScript object representation, secret keys, password fields, intranet Internet Protocol addresses and internal domain names are filtered in real time; the desensitization rules are configured through environment variables and include custom mask strings and replacement upper limit parameters.
10. The code security auditing method according to claim 1, characterized in that, It also includes token usage control steps: real-time tracking of AI token consumption by project and audit session dimensions, displaying the input token amount, output token amount and total token amount of the current session on the research dashboard; when token consumption reaches a preset threshold, it automatically triggers a degradation strategy that shuts down deep analysis, reduces the number of iterations or switches to a lightweight model.
11. The code security auditing method according to claim 1, characterized in that, It also includes vulnerability governance linkage steps: converting verified vulnerabilities into structured issue tickets, and through an externally observable manifest issue ticket enhancement mechanism, converting audit issue tickets in the research mode, which contain entry points, vulnerability rules, verification tracing links, summaries and remediation suggestions, into global vulnerability discovery in the management mode; Synchronize the severity level, status, and handling information of vulnerabilities, and perform vulnerability allocation, tracking, and closed-loop governance in management mode.
12. A code security auditing system for implementing the method of any one of claims 1 to 11, characterized in that, include: The audit session management module is used to create and manage audit sessions, bind audit rule sets, and maintain the global context and audit artifact storage area. The agent scheduling module is used to schedule multiple dedicated agents to execute audit sub-tasks; The tool call loop engine drives each agent to perform multiple rounds of iterative tool calls and inference processes. The unified tool service module is used to provide standardized and verifiable unified tool call interfaces to the outside world, and to encapsulate and provide integrated development environment tools and code property graph tools; The vulnerability verification module is used to verify candidate vulnerabilities in multiple rounds, dynamically adjust the vulnerability confidence score, and filter false positives. The content desensitization module is used to perform the automatic content desensitization step using artificial intelligence; The token usage control module is used to execute token usage control steps; The vulnerability governance linkage module is used to execute vulnerability governance linkage steps and realize the observable improvement and transformation of the global vulnerability work order in the research mode audit issue unidirectional management mode. The results output module is used to generate a complete audit report that can be independently verified, carrying a confidence score for each vulnerability.