Method and apparatus for tool execution based on mcp protocol, computer device and storage medium
By defining a unified tool interface and dependency injection mechanism for the MCP protocol, dynamic tool discovery and permission management are achieved during the integration of AI Agent tools. This solves the problems of high development costs, poor system scalability, and weak runtime security control during the integration of AI Agent tools, and improves the efficiency and security of the tool invocation process.
Patent Information
- Application Number
- CN202611022817.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-09
- Publication Date
- 2026-11-03
AI Technical Summary
During the integration of AI Agent tools, different protocol adaptation logic needs to be implemented for local calls and remote calls, resulting in high development costs, poor system scalability, and weak security control during runtime.
Define a unified tool interface for the MCP protocol, scan and load utility class instances when the container starts through a dependency injection mechanism, utilize memory registry management tool identifiers to achieve dynamic lookup and permission verification of tool call requests, and adopt a two-phase confirmation process to ensure the idempotency and security of operations.
It improves system scalability, reduces development costs, enhances runtime security control capabilities, and ensures consistency of state during tool invocation and flexibility of access control.
Smart Images

Figure CN123030241A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the fields of artificial intelligence and distributed systems technology, and in particular to a tool execution method, apparatus, computer device and storage medium based on the MCP protocol. Background Technology
[0002] With the continuous development of large language models, AI Agents (Artificial Intelligence Agents) based on large language models are evolving from simple dialogue systems into executors capable of autonomously invoking external tools to complete complex tasks. Whether it's code interpreters, web searches, internal business system operations, or cross-application collaboration, AI Agents need to connect to various capabilities in the digital network through tool invocation. However, different tools have different invocation protocols, parameter formats, authentication methods, and execution semantics. For example, some tools are local Java methods, some are RESTful APIs (RESTful Application Programming Interfaces) exposed via HTTP (Hypertext Transfer Protocol), some are encapsulated as Dubbo or gRPC (gRPC Remote Procedure Call) remote services, and some involve database changes or cloud resource scheduling, making the tool integration and execution of AI Agents a highly complex engineering problem.
[0003] In related technologies, separate call adaptation code needs to be written for each tool, meaning different call logic needs to be implemented for local and remote tools. Local tools execute via reflection or direct method calls, while remote tools require additional HTTP client development, load balancing, and service discovery logic. For tools involving sensitive operations, a manual confirmation process must be implemented, thus relying on temporary state machines or callback logic written for specific scenarios. Furthermore, regarding access control, permission judgment logic needs to be hard-coded within the tool implementation, and when adding a new tool, tool information needs to be manually declared in the configuration file, and several framework classes need to be modified to complete the registration.
[0004] In the process of implementing the relevant technology, the applicant recognized that the relevant technology has at least the following technical problems: Different protocol adaptation logics need to be implemented for local and remote calls. This not only requires modifying the core framework code to accommodate new protocol types when adding new tool types, violating the open / closed principle, but also necessitates developers to temporarily code each sensitive operation to ensure the persistence of confirmation records, idempotency guarantees in concurrent scenarios, and automatic handling after timeouts. This can easily introduce risks of inconsistent state management and concurrent race conditions. At the same time, the permission control logic is coupled with specific tools. When permission judgments are required based on business dimensions, the judgment code in each tool implementation class must be modified one by one. This process is not only cumbersome but also difficult to handle dynamic changes in permission rules, resulting in high development costs, poor system scalability, and weak runtime security control during the integration of AI Agent tools. Summary of the Invention
[0005] In view of this, this application provides a tool execution method, apparatus, computer equipment and storage medium based on the MCP protocol, the main purpose of which is to solve the problems of high development cost, poor system scalability and weak security control during the current AI Agent tool integration process.
[0006] According to a first aspect of this application, a tool execution method based on the MCP protocol is provided, the method comprising: Define a unified tool interface for the MCP protocol, wherein the unified tool interface defines a first method for obtaining the tool identifier, a second method for constructing the display content, and a third method for performing tool operations; By using the dependency injection mechanism, all utility class instances that implement the unified tool interface are scanned and loaded when the container starts. The tool identifier of each utility class instance is obtained by calling the first method, and each utility class instance and its corresponding tool identifier are stored in the memory registry in the form of key-value pairs. In response to a tool invocation request, the target tool instance is retrieved from the memory registry based on the target tool identifier carried in the tool invocation request, and the target tool configuration information is queried based on the target tool identifier; When it is determined that the target tool configuration information indicates a confirmation requirement, a confirmation record marked as pending confirmation is created and a confirmation deadline is set. The confirmation page is then constructed and returned by calling the second method. When a confirmation instruction is received based on the confirmation page, an initial verification is performed based on the confirmation record and the deadline. After the verification is passed, permission verification is performed using preset permission rules. After the permission verification is passed, the third method is called to execute the tool operation of the target tool instance, and the status of the confirmation record is updated according to the execution result.
[0007] According to a second aspect of this application, a tool execution device based on the MCP protocol is provided, the device comprising: The interface definition module is used to define a unified tool interface for the MCP protocol. The unified tool interface defines a first method for obtaining the tool identifier, a second method for constructing and displaying content, and a third method for performing tool operations. The scanning module is used to scan and load all utility class instances that implement the unified tool interface when the container starts through the dependency injection mechanism, and to obtain the tool identifier of each utility class instance by calling the first method, and store each utility class instance and its corresponding tool identifier in the memory registry in the form of key-value pairs; The query module is used to respond to a tool call request, obtain a target tool instance from the memory registry based on the target tool identifier carried in the tool call request, and query the target tool configuration information based on the target tool identifier; The verification module is used to create a confirmation record marked as pending confirmation and set a confirmation deadline when it is determined that the target tool configuration information indicates that there is a confirmation requirement. It then constructs a confirmation page and returns it by calling the second method. The verification module is also used to perform an initial verification based on the confirmation record and the deadline when a confirmation instruction is received based on the confirmation page; The permission verification module is used to verify permissions using preset permission rules after the verification is passed. The execution module is used to call the third method to execute the tool operation of the target tool instance after the permission verification is passed, and update the status of the confirmation record according to the execution result.
[0008] According to a third aspect of this application, a computer device is provided, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement the steps of the method described in any of the first aspects above.
[0009] According to a fourth aspect of this application, a computer-readable storage medium is provided, on which a computer program is stored, wherein the computer program, when executed by a processor, implements the steps of the method described in any one of the first aspects above.
[0010] By employing the above technical solutions, this application provides a tool execution method, apparatus, computer device, and storage medium based on the MCP protocol. This application defines a unified tool interface and, in conjunction with a dependency injection mechanism, encapsulates the differences in calling local and remote tools within the interface implementation. Automatic scanning and registration during container startup eliminates the need for the framework to be aware of the underlying protocol type, thereby eliminating core code modifications when adding new tools, improving system scalability, and conforming to the open / closed principle. Simultaneously, based on the confirmation and verification process using the memory registry and configuration information, the maintenance of confirmation record status, deadline control, and idempotency guarantees are uniformly incorporated into the framework management, avoiding developers repeatedly writing error-prone state machines and callback logic for sensitive operations, and reducing concurrency race conditions and consistency issues. Furthermore, permission verification achieves logical decoupling through preset rules and matching with business data, enabling dynamic adaptation to multi-dimensional permission control needs without modifying each tool implementation class individually, improving development efficiency while enhancing the system's runtime security control capabilities.
[0011] The above description is only an overview of the technical solution of this application. In order to better understand the technical means of this application and to implement it in accordance with the contents of the specification, and to make the above and other objects, features and advantages of this application more obvious and understandable, the following are specific embodiments of this application. Attached Figure Description
[0012] Various other advantages and benefits will become apparent to those skilled in the art upon reading the following detailed description of preferred embodiments. The accompanying drawings are for illustrative purposes only and are not intended to limit the scope of this application. Furthermore, the same reference numerals denote the same parts throughout the drawings. In the drawings: Figure 1 This illustration shows a flowchart of a tool execution method based on the MCP protocol provided in an embodiment of this application. Figure 2 This paper illustrates a schematic diagram of the system architecture of a tool management system provided in an embodiment of this application. Figure 3 This paper illustrates a schematic diagram of the system architecture of a tool management system provided in an embodiment of this application. Figure 4 This illustration shows a schematic diagram of a specific two-stage verification process provided in an embodiment of this application; Figure 5 This illustration shows a schematic diagram of an authorization verification process provided in an embodiment of this application; Figure 6 This illustration shows a schematic diagram of a tool execution device based on the MCP protocol provided in an embodiment of this application; Figure 7 A schematic diagram of the device structure of a computer device provided in an embodiment of this application is shown. Detailed Implementation
[0013] Exemplary embodiments of the present application will now be described in more detail with reference to the accompanying drawings. While exemplary embodiments of the present application are shown in the drawings, it should be understood that the present application may be implemented in various forms and should not be limited to the embodiments set forth herein. Rather, these embodiments are provided so that this application will be thorough and complete, and will fully convey the scope of the present application to those skilled in the art.
[0014] This application provides a tool execution method based on the MCP protocol, such as... Figure 1 As shown, the method includes: S10: Defines a unified tool interface for the MCP protocol.
[0015] This application embodiment can be applied to a tool management system. In this embodiment, a unified tool interface of the MCP protocol needs to be defined first. This unified tool interface defines a first method for obtaining tool identifiers, a second method for constructing display content, and a third method for executing tool operations. MCP (Model Context Protocol) is an open protocol used to connect AI Assistants (Artificial Intelligence Assistants) and external data sources or tools, providing a unified tool call interface. The first method obtains tool identifiers such as tool names, with no input parameters, returning a unique string identifier for the tool, in the format of underscore-separated English strings, such as "engine_switch" indicating engine switching. This tool identifier is used simultaneously as the key in the hash table in the tool registry and the value of the name field in the database tool table for precise matching during tool calls. The second method constructs display content, with trigger parameters as input parameters, and returns a structured result containing Markdown-formatted display content and result data. The third method executes tool operations, with merged execution parameters as input parameters, and returns the execution result.
[0016] In the above process, by defining a unified tool interface, the differences in calling local and remote tools are encapsulated within the interface implementation, so that when the AI Agent calls tools of different protocol types in actual applications, it does not need to be aware of the underlying implementation details.
[0017] For example, in a scenario where the AI Agent needs to call the "engine switching" tool, the tool class can handle the registration, confirmation, and calling process of the tool uniformly by implementing the defined unified tool interface and implementing three methods: obtaining the tool name, constructing the display content, and executing the tool operation. This eliminates the need for additional processing based on whether the tool is a local Java method or a remote RPC service.
[0018] S20: Through dependency injection, scan and load all utility class instances that implement the unified utility interface when the container starts, and obtain the utility identifier of each utility class instance by calling the first method, and store each utility class instance and its corresponding utility identifier in the memory registry in the form of key-value pairs.
[0019] In this embodiment, a dependency injection mechanism is needed to automatically scan and load all utility class instances implementing the unified utility interface when the container starts. Additionally, by calling a first method, the utility identifier of each utility class instance is obtained, and each utility class instance and its corresponding utility identifier are stored in a memory registry as key-value pairs. Dependency injection is a core mechanism of the Spring framework, and the container is responsible for managing object creation and lifecycle.
[0020] With this mechanism, when adding a new tool, developers only need to add annotations such as @Component to the tool class, and the container will automatically complete the registration when it starts, without having to manually write any registration code or modify the configuration file.
[0021] For example, when a developer adds a "node deployment" utility class to a project, implements a unified utility interface, and adds the @Component annotation, the container will automatically scan for the class when it starts, call its method to get the utility name and obtain "node_enable" as the key, store the utility instance as the value in the memory registry, and then dynamically obtain and execute the utility instance through "node_enable". The whole process does not require any modification to the framework code or configuration files.
[0022] S30: In response to a tool invocation request, retrieve the target tool instance from the memory registry based on the target tool identifier carried in the tool invocation request, and query the target tool configuration information based on the target tool identifier.
[0023] In this embodiment, upon receiving a tool invocation request, in response to the request, it is necessary to retrieve the target tool instance from the memory registry based on the target tool identifier carried in the request, and then query the target tool configuration information based on the target tool identifier. The tool invocation request can be initiated by the AI Agent via the MCP protocol, carrying the target tool identifier. Querying based on the target tool identifier dynamically retrieves the corresponding target tool instance, achieving dynamic tool lookup with zero configuration. Simultaneously, it is also necessary to query the target tool configuration information based on the target tool identifier. The target tool configuration information includes attributes such as whether confirmation is required and whether it is an external service tool.
[0024] In this way, the dual lookup mechanism separates tool discovery from configuration management, and adding new tools does not require modifying the lookup logic. For example, suppose that after the AI Agent initiates a call request for the "engine_switch" tool, it first retrieves the "engine switching" tool instance from the memory registry with "engine_switch" as the key, and then queries the tool configuration table based on the tool identifier to obtain the tool's "confirmation required" flag value of 1, indicating that confirmation is required, and the "default timeout in seconds" value of 300 seconds, and other configuration information.
[0025] S40: When the target tool configuration information indicates that there is a confirmation requirement, create a confirmation record marked as pending confirmation and set the confirmation deadline. Then, construct the confirmation page and return by calling the second method.
[0026] In this embodiment, when it is determined that the target tool configuration information indicates a confirmation requirement, a confirmation record marked as pending confirmation needs to be created and a confirmation deadline is set. A confirmation page is then constructed and returned by calling a second method. Specifically, whether a confirmation requirement exists can be determined by identifying the confirmation identifier field in the target tool configuration information, and a confirmation deadline is set to form a confirmation record, which is stored in a database.
[0027] Subsequently, the tool's second method for building and displaying content is invoked to generate Markdown page content containing a confirmation button or confirmation link, which is then returned to the AI Agent for the user to confirm. This unifies the persistence of confirmation records, deadline control, and timeout handling into the framework management, avoiding developers from repeatedly writing state machine logic for each sensitive operation.
[0028] For example, assuming the configuration information of the "engine switching" tool indicates that confirmation is required, a confirmation record needs to be created, with the status set to PENDING to indicate pending confirmation. The confirmation deadline is calculated by adding 300 seconds to the current time, for example, if the current time is 15:00:00, the deadline is 15:05:00. The tool name, status, trigger parameter JSON, trigger agent ID and name, and confirmation deadline are written to the database. Then, the tool's method for building display content is called to generate Markdown page content containing session information and a confirmation button link. This content is written back to the display content field of the confirmation record and returned to the AI Agent.
[0029] S50: When a confirmation instruction is received on the confirmation page, an initial verification is performed based on the confirmation record and the deadline. After the verification is passed, permission verification is performed using preset permission rules. After the permission verification is passed, a third method is called to execute the tool operation of the target tool instance, and the status of the confirmation record is updated according to the execution result.
[0030] In this embodiment, when a confirmation instruction is received on the confirmation page, an initial verification is performed based on the confirmation record and the deadline. After successful verification, permission verification is performed using preset permission rules. Following successful permission verification, a third method is invoked to execute the tool operation of the target tool instance, and the status of the confirmation record is updated based on the execution result. This process constitutes the second stage of a two-stage confirmation process. Upon receiving the user's confirmation request, the system sequentially verifies whether the record status is pending confirmation and whether the current time exceeds the confirmation deadline. After successful verification, the permission verification method is invoked to check if the current confirmer has execution permissions. If execution permissions are confirmed, the permission verification is deemed successful, and the tool's third method is invoked to execute the actual business operation. After the operation is completed, the confirmation record status is updated to SUCCESS or FAILED based on the execution result, and the execution result and confirmer information are recorded.
[0031] In this way, the above process can decouple the access control logic from the tool implementation, achieve dynamic access control by matching preset rules with business data, and the second-stage verification can ensure that the same confirmation record will not be executed repeatedly in concurrent scenarios, thus ensuring the idempotency of operations and data consistency.
[0032] For example, suppose two confirmers, A and B, simultaneously click the "Confirm" button on the "Engine Switch" tool. Request A, arriving first, acquires a database row lock, reads the status as PENDING, verifies it, executes the engine switch operation, updates the status to SUCCESS, and commits the transaction to release the lock. Request B, arriving later, is blocked at the lock query stage. After A releases the lock, B reads the status as SUCCESS and returns "Record status cannot be confirmed" in the status check step, thus ensuring that the same confirmation is not executed repeatedly. Regarding permission verification, if the tool is configured with the permission rule "planId=12345," it needs to extract the actual session identifier from the trigger parameters and compare it with 12345, while also checking if the current confirmer is in the confirmer list. Execution is only allowed if both conditions are met.
[0033] In practical applications, in order to implement the technical solutions in the embodiments of this application, the system architecture of the tool management system can be as follows: Figure 2 As shown, the tool management system can adopt a two-layer architecture to integrate the MCP protocol, which is divided into a protocol gateway layer and a tool business logic layer. The AI Agent or LLM (Large Language Model) acts as a client and establishes a long connection with the tool management system through the SSE (Server-Sent Events) protocol. The access format is " / mcp / {mcpName} / sse" of the MCP Protocol endpoint, where {mcpName} is the name of the specific MCP service instance.
[0034] The protocol gateway layer is handled by an independent HTTP API gateway service for the underlying communication of the MCP protocol. McpController receives JSON-RPC request messages sent by the AI Agent, distinguishes the operation type based on the method field (e.g., "tools / list" means to retrieve a list of tools, "tools / call" means to call a tool), and converts the request into an RPC call to the backend business service. The returned result is encapsulated in JSON-RPC response format and pushed to the AI Agent through the SSE channel. The protocol gateway layer also includes McpServerLogic for endpoint management and McpToolLogic for permission management.
[0035] The tool business logic layer provides the gateway layer with two core capabilities through the RPC interface: obtaining the tool list and triggering tool execution. The tools in the tool business logic layer are divided into two categories: local tools and remote service tools. Local tools include specific implementation classes such as EngineSwitch (engine switching), ElasticScale (elastic scaling), and NodeEnable (node deployment). Remote service tools are executed through the Dubbo generic invocation mechanism, relying on the Dubbo Registry to realize service discovery and invocation.
[0036] In addition, the tool management system also interfaces with a Data Layer, using MySQL to store data such as mcp_tool (tool table), mcp_config (configuration table), and mcp_confirmation (confirmation record table). Furthermore, the tool management system implements a dynamic configuration synchronization mechanism. When an administrator modifies the MCP service configuration, the business service writes the configuration to the Redis cache and simultaneously publishes a change notification message to a designated channel through the Redis publish / subscribe mechanism. The gateway layer subscribes to this channel and updates the configuration of its local SSE connection pool in real time upon receiving the notification, thereby achieving dynamic hot updates of the configuration without restarting the service.
[0037] Optionally, in this embodiment of the application, a unified tool interface for the MCP protocol is defined, including: defining an original tool interface, and defining a first method, a second method, and a third method in the original tool interface with reference to the MCP protocol. The first method is a method that returns a tool identifier of type string without input parameters; the second method is a method that receives trigger parameters including business parameters and metadata and returns a structured result including a display content part and a result data part; the third method is a method that receives merged execution parameters and returns an execution result. Simultaneously, an abstract base class implementing preset general logic is defined in the original tool interface, so that the defined original tool interface serves as the unified tool interface. The abstract base class defines the display content construction sub-method in the first method and the second method, and the execution operation sub-method in the third method, as abstract methods.
[0038] In this embodiment, when defining the unified tool interface of the MCP protocol, it is first necessary to define the original tool interface, and define the first method, the second method and the third method in the original tool interface with reference to the MCP protocol, and at the same time define the abstract base class that implements the preset general logic, and use the defined original tool interface as the unified tool interface. The first method is a tool identifier that returns a string without input parameters. The returned tool identifier is in the format of an underscore-separated English string, such as "engine_switch" indicating engine switching and "node_enable" indicating node online. The tool identifier will be used as the key in the hash table in the tool registry and the value of the name field in the tool table in the database for precise matching during tool invocation. The second method is a method that receives trigger parameters including business parameters and metadata and returns a structured result including a display content part and a result data part. The display content is in Markdown format for display on the front-end page or instant messaging group, and the result data is structured business data. For operation-type tools that require confirmation, the tool management system will inject metadata such as confirmation record ID, confirmation deadline, timeout seconds, and confirmation link URL into the trigger parameters before calling the second method. Subclasses use this metadata to generate Markdown content containing a confirmation button or confirmation link. The third method is a method that receives merged execution parameters and returns execution results. The execution parameters include the original parameters of the trigger stage, the user selection parameters of the confirmation stage, and the identity information of the confirmer. Meanwhile, in this embodiment, the abstract base class defines the content display construction sub-method in the first method and the second method, and the execution operation sub-method in the third method as abstract methods, which are implemented by each specific utility subclass. The base class itself provides common logic such as thread-local variable management of display name, default construction logic for confirming page content, and default implementation of permission verification.
[0039] In the concrete implementation of the abstract base class, the first method adopts a thread-local variable priority strategy. That is, it prioritizes retrieving the custom display name of the current request from the thread-local variable. If the thread-local variable has no value, it returns the tool name obtained from the first method. The purpose of designing thread-local variables is to allow the same tool to have different display names in different calling scenarios. For example, the same "engine switching" tool can display as "engine-engine switching" in an engine alarm scenario and as "switching engines" in a regular operation and maintenance scenario. The caller specifies the desired display name by carrying a custom display name field in the trigger parameters. The tool management system writes this value into the thread-local variable before the second method executes and clears it in the finally block after execution, ensuring correct name transmission and isolation in a multi-threaded environment. Furthermore, the second method adopts the template method pattern. Specifically, it first checks whether the trigger parameters contain a custom display name field; if so, it writes it into the thread-local variable. Then, it calls the protected sub-methods for building display content and building result data, encapsulating both into a unified result object and returning it. Finally, it clears the thread-local variable in the finally block. Furthermore, the third method provides default behaviors such as logging the tool name and parameters, calling protected execution sub-methods in exception handling blocks, and returning results with error information on success or failure.
[0040] In this way, through the above design of the abstract base class, tool developers only need to inherit the abstract base class and mark the class as a container management component to create new tools. At a minimum, they only need to implement two sub-methods: getting the tool name and building the display content, or add sub-methods for execution operations on top of that. The tool management system also provides secondary abstract base classes for specific business domains, such as server tool base classes, which encapsulate the common dependency injection and public methods of that business domain, such as getting server information and checking server status, further reducing boilerplate code.
[0041] For example, suppose a developer creates an EngineSwitch class that inherits from the server tool base class. After marking it as a component, the developer only needs to implement the following: get the tool name and return "engine_switch", build the display content to generate a Markdown page containing session information and a confirmation button link, and execute the actual engine switching logic. The framework can automatically complete the registration, confirmation process and execution of the tool without having to worry about cross-cutting concerns such as underlying thread variable management, logging and exception handling. This significantly improves development efficiency and ensures data isolation and security in a multi-threaded environment.
[0042] In this embodiment of the application, optionally, a dependency injection mechanism is used to scan and load all utility class instances implementing the unified tool interface when the container starts, and to obtain the tool identifier of each utility class instance by calling a first method, and to store each utility class instance and its corresponding tool identifier in the memory registry in the form of key-value pairs. This includes: constructing a tool registry class, marking the tool registry class as a container management component, and defining a list parameter of tool interface types in the constructor of the tool registry class; when the container management component starts, scanning and injecting all utility class instances implementing the unified tool interface through a dependency injection mechanism; during the initialization phase of the tool registry class, constructing the memory registry, traversing each utility class instance, sequentially calling the first method of each specific utility class instance to obtain the tool identifier corresponding to each specific utility class instance, and storing the tool identifier of each specific utility class instance as a key and each specific utility class instance as a value in the memory registry in the form of key-value pairs.
[0043] In this embodiment, when implementing automatic tool registration via dependency injection, the tool management system first constructs a tool registry class and marks this class as a container management component, for example, using the `@Component` annotation in the Spring framework, making it a Bean managed by the Spring IoC container. Simultaneously, a list parameter of tool interface types needs to be defined in the constructor of this registry class to receive all Bean instances that implement the unified tool interface.
[0044] When the Spring container starts, it performs component scanning, automatically discovering and instantiating all utility classes annotated with `@Component` and implementing the unified utility interface. Then, through dependency injection, these utility class instances are injected in batches as constructor parameters into the utility registry class. During the initialization phase of the utility registry class, the utility management system constructs an in-memory hash table (e.g., `ConcurrentHashMap`) as the in-memory registry. It iterates through all utility class instances injected via the constructor, calling the first method of each instance to obtain its unique tool identifier. This identifier is then used as the key, and the corresponding utility instance as the value, stored in the in-memory registry as key-value pairs. After initialization, the runtime utility management system only needs to query this in-memory registry based on the tool identifier to dynamically retrieve the corresponding utility instance in constant time complexity, achieving automatic tool discovery and dynamic lookup with zero configuration.
[0045] The key to the mechanism described above is to change the tool registration behavior from manually writing configuration code to being completed automatically by the framework at startup. This fully utilizes the dependency injection and lifecycle management capabilities of the Spring container, so that when tool developers add a new tool, they only need to have the tool class inherit the abstract base class and implement the necessary methods, and mark it as a container-managed component. There is no need to declare any registration information in the configuration file or the core code of the framework. The container will automatically scan, instantiate and register the tool when it starts.
[0046] For example, suppose a new "node deployment" tool needs to be added. The developer creates a NodeEnable class that inherits from the server tool base class, implements a method to get the tool name that returns "node_enable", annotates it with @Component, and after restarting the container, the tool instance is automatically injected into the registry class constructor. During the initialization phase, its name "node_enable" and the instance are stored in the memory registry. When the AI Agent initiates a call request to "node_enable", the tool management system directly retrieves the NodeEnable instance from the memory registry and executes it. The entire process does not require modification of any registration code or configuration files, eliminating the tedious operation of manually modifying the registration list when adding a new tool in the traditional way. This significantly improves the scalability and development efficiency of the tool management system, while also conforming to the open / closed principle, that is, open for extension but closed for modification, enabling the framework to dynamically adapt to changes in the tool set at runtime without modifying existing code.
[0047] In summary, the automatic registration process for tools in this embodiment is as follows: Figure 3 As shown, when the Spring container starts, the tool management system performs a classpath scan using ClassPathBeanScanner, automatically discovering all classes annotated with `@Component`. From these, it filters out utility classes that implement the `IMcpTool` interface, such as `EngineSwitchTool` (engine switching tool), `ElasticNodeScaleTool` (elastic node scaling tool), and `NodeEnableTool` (node deployment tool). Subsequently, the Spring container creates bean instances for these discovered utility classes, completing dependency injection and lifecycle management. After these tool beans are instantiated, the Spring container automatically injects all implementation classes of the `IMcpTool` interface into `McpToolRegistry` (the tool registry class) using the `@Autowired` annotation. The injection method can be a List... <imcptool>The `McpToolRegistry` is a collection that receives all discovered tool instances at once. During initialization, the `init()` method (annotated with `@PostConstruct`) automatically executes, iterating through the injected `toolList`, retrieving each tool instance, and calling the `registerTool(tool)` method for each tool. Inside the `registerTool` method, the `tools.put(name, tool)` operation is executed, storing the tool's identifier as the key and the tool instance as the value in a `ConcurrentHashMap` in memory. After iterating through all elements in `toolList`, the registration process is complete, and N tools are registered in the memory registry, where N is the number of discovered tool implementation classes. During system runtime, when a specific tool is needed, the `getTool("engine_switch")` method is called. This performs a constant-time hash lookup in the memory map based on the key "engine_switch" and returns the corresponding tool instance for subsequent execution.
[0048] Optionally, in this embodiment, when the target tool configuration information indicates a confirmation requirement, a confirmation record marked as pending confirmation is created and a confirmation deadline is set. A confirmation page is constructed and returned by calling a second method, including: identifying whether a confirmation is required and the default timeout duration included in the target tool configuration information; when the confirmation is required indicator, a confirmation record is created, and the status field of the confirmation record is set to pending confirmation; the current time is determined, and the default timeout duration is added to the current time to determine the confirmation deadline; the request trigger information carried by the tool call request is extracted, the target tool identifier and request trigger information are recorded in the confirmation record, and a record identifier for the confirmation record is generated; the confirmation record is labeled with the record identifier and stored in the database, the request trigger information including trigger parameters and triggerer information; the second method is called to pass in the trigger parameters, the second method generates a confirmation page, the confirmation page is associated with the confirmation record, and the record identifier and confirmation page are returned.
[0049] In this embodiment, when the target tool configuration information indicates a confirmation requirement, the tool management system first identifies the confirmation requirement flag and default timeout duration included in the target tool configuration information. Specifically, the tool management system queries the tool configuration table based on the target tool identifier to obtain the confirmation requirement flag and the default timeout duration in seconds. When the flag indicates that confirmation is required, the tool management system immediately enters the first stage of the two-stage confirmation process, namely the triggering stage. A confirmation record is created, the record's status field is set to PENDING to indicate pending confirmation, and the current time is determined. The default timeout duration is added to the current time to calculate the confirmation deadline. For example, if the current time is 15:00:00 and the timeout duration is 300 seconds, the deadline is 15:05:00. Simultaneously, the tool management system extracts the request trigger information carried in the tool call request. This trigger information includes trigger parameters and triggerer information. Trigger parameters can be JSON objects containing business parameters and system-injected metadata; triggerer information can be the triggerer's employee ID and name. The tool management system then records the target tool identifier, the JSON serialized content of the trigger parameters, and the triggerer information in a confirmation record. It also uses an auto-incrementing primary key from the database to generate a unique identifier for the confirmation record, storing this record in the database's confirmation record table. Subsequently, the tool management system calls a second method, passing in the trigger parameters. This second method generates a confirmation page containing a confirmation button or link in Markdown format. The confirmation page content is written back to the `markdown_content` field of the confirmation record, and the record identifier and confirmation page are returned to the AI Agent for display to the end user for confirmation.
[0050] It's important to note that in practical applications, the confirmation records are stored in the database with rich and complete field information to support subsequent status tracking, audit tracing, and concurrency control. Specifically, in addition to the tool identifier (id), mcp_tool_name, status field (status), trigger parameter (trigger_context), confirmation page Markdown content (markdown_content), and confirmation deadline (confirm_deadline) mentioned above, it may also include the triggering worker ID (creator_uid), triggering worker name (creator_name), actual confirmation time (confirm_time), confirmation worker ID (confirm_uid), confirmation worker name (confirm_name), cancellation worker ID (canceller_uid), cancellation worker name (canceller_name), and cancellation time (cancelled_time), as well as the permission configuration snapshot (config_snapshot) at the time of triggering, soft deletion identifier (is_deleted), creation time (created_time), and update time (updated_time). The design of these fields ensures that the entire lifecycle of each confirmation request, from triggering to final completion, is traceable, providing a complete data foundation for security auditing and problem investigation.
[0051] In this way, through the above process, the tool management system integrates the creation of confirmation records, state persistence, timeout calculation, and page generation into the framework management, so that developers do not need to manually write confirmation record tables and timeout logic for each sensitive operation. This can reduce the risk of coding errors and ensure that all confirmation operations are uniformly guaranteed in terms of state consistency, auditability, and automatic timeout processing, significantly enhancing the reliability and maintainability of the tool management system in security-sensitive scenarios.
[0052] For example, when the AI Agent initiates a tool call request, the tool management system queries the tool configuration table based on the tool identifier "engine_switch" to obtain a "Confirmation Required" flag value of 1 and a "Default Timeout in Seconds" value of 300 seconds. The tool management system then creates a confirmation record, sets the initial state to PENDING, adds 300 seconds to the current time 15:00:00 to obtain the deadline 15:05:00, and then writes the tool identifier "engine_switch", trigger parameters, trigger agent ID "zhangsan", name "Zhang San", and deadline to the database. The database automatically generates a unique identifier for this record. Finally, the tool's "Build Result Content" method is called, passing in the trigger parameters. The method generates a Markdown page containing session details and a confirmation button based on the injected confirmation record ID, deadline, confirmation link URL, and other metadata, writes it back to the confirmation record's markdown_content field, and returns the record identifier and confirmation page to the AI Agent.
[0053] In this embodiment, optionally, when a confirmation instruction is received based on the confirmation page, an initial verification is performed based on the confirmation record and the deadline. After the verification passes, permission verification is performed using preset permission rules. After the permission verification passes, a third method is called to execute the tool operation of the target tool instance, and the status of the confirmation record is updated according to the execution result. This includes: when a confirmation instruction is received based on the confirmation page, querying and locking the data row where the confirmation record is located in the database using a database row-level exclusive lock based on the record identifier; reading the status field and confirmation deadline in the confirmation record, verifying whether the status field is pending confirmation and whether the current time has not exceeded the confirmation deadline; when it is verified that the status field is pending confirmation and the current time has not exceeded the confirmation deadline, determining that the initial verification has passed, and obtaining the permissions used to store the preset permission rules. The system retrieves at least one permission configuration record associated with the target tool identifier from the permission configuration table. Each permission configuration record includes a rule expression and a list of confirmers. It extracts the current confirmer identifier from the confirmation command, extracts the trigger parameters from the confirmation record, and performs permission verification using at least one permission configuration record, combined with the current confirmer identifier and the trigger parameters. When the permission verification using any one of the at least one permission configuration record passes, it calls the third method of the target tool instance, passing the trigger parameters and the current confirmer identifier as execution parameters, executes the tool operation, and obtains the execution result. Based on the execution result, it updates the status field of the confirmation record to success or failure, records the current confirmer identifier and the execution result in the confirmation record, and commits the transaction to release the database row-level exclusive lock.
[0054] In this embodiment, when the confirmation page receives a confirmation instruction from the user, the tool management system enters the second stage of the two-stage confirmation process, namely the confirmation stage. Specifically, it first uses a row-level exclusive lock to query and lock the data row containing the confirmation record in the database based on the record identifier of the confirmation record. In this embodiment, the row-level exclusive lock can be used as a SELECT ... FOR UPDATE query. This query locks the corresponding data row within the database transaction, ensuring that only one transaction can read and subsequently update the record at any given time. Other concurrent transactions attempting to query the same row will be blocked and wait until the current transaction is committed or rolled back before continuing. The tool management system then reads the status field and confirmation deadline in the locked confirmation record, verifying whether the status field is PENDING (pending confirmation) and whether the current time has not exceeded the confirmation deadline. If both conditions are met, the initial verification is considered successful. If the status is no longer pending confirmation or has expired, the confirmation request is directly rejected and the corresponding error message is returned.
[0055] After the initial verification passes, the tool management system retrieves the permission configuration table used to store preset permission rules. It then queries the table for at least one permission configuration record associated with the current target tool identifier. Each permission configuration record contains a rule expression and a corresponding list of confirmers. Subsequently, the tool management system extracts the current confirmer identifier (i.e., the user ID who clicked the confirm button) from the confirmation command and extracts trigger parameters from the confirmation record. These trigger parameters include actual data such as the session ID, application ID, and server type from the business dimension. The system then uses all the aforementioned permission configuration records, combined with the current confirmer identifier and trigger parameters, to perform permission verification. Specifically, the tool management system iterates through each permission configuration record, extracting the corresponding business data value from the trigger parameters for each record based on its rule type and comparing it with the target value in the rule. Simultaneously, it checks if the current confirmer identifier is in the list of confirmers specified for that record. If both conditions are met, the permission configuration verification is considered successful. When the permission verification using any one of the permission configuration records in at least one permission configuration passes, the tool management system determines that the current confirmer has the right to execute the tool operation. Then, it calls the third method of the target tool instance, combines the trigger parameter and the current confirmer's identifier as the execution parameter, executes the actual business operation, and obtains the execution result.
[0056] After the operation is completed, the tool management system will update the status field of the confirmation record according to the execution result. The status field is set to SUCCESS when successful and FAILED when unsuccessful. At the same time, the current confirmer's identifier, confirmer's name, actual confirmation time and execution result are recorded in the confirmation record. Finally, the transaction is committed to release the database row-level exclusive lock and the final execution result is returned to the AI Agent.
[0057] In this way, through the process described above, database row locks ensure idempotency in concurrent scenarios, the decoupling of the permission configuration table and trigger parameters allows permission rules to be dynamically adjusted without modifying the tool implementation code, and the complete status tracking and audit fields of the confirmation records provide a complete data foundation for security auditing, thereby significantly improving the security, consistency and maintainability of the tool management system in sensitive operation scenarios.
[0058] For example, suppose two confirmers, A and B, click the confirmation link simultaneously. Request A, arriving first, successfully locks the row containing the confirmation record using SELECT ... FOR UPDATE, reads the status as PENDING, and finds that the current time 15:00:30 has not exceeded the deadline of 15:05:00, thus passing the initial verification. In the subsequent permission verification step, the tool management system queries a rule configured with planId=12345, extracts the appearance ID 12345 from the trigger parameters, and finds a match. Confirmer A is also in the confirmer list for this rule, so permission verification passes. The system then calls the engine switching execution method to complete the operation, updates the status to SUCCESS, and commits the transaction to release the lock. Request B, arriving later, is blocked at the lock query point. After A releases the lock, B reads the status as SUCCESS. In the status verification step, because the status is no longer PENDING, B directly returns a "Record processed" message, thus preventing the same operation from being executed repeatedly.
[0059] In summary, the specific process of the two-stage verification proposed in this application embodiment is as follows: Figure 4 As shown, when the AI Agent initiates a tool call, the tool management system first enters the Trigger phase. Based on the target tool identifier, it queries the target tool configuration information and identifies the require_confirm flag. If the flag is equal to 1, it means that the current tool operation requires user confirmation. The tool management system then creates a confirmation record, sets the status field to PENDING, records the trigger parameters and triggerer information, and sets the confirmation deadline. Afterward, it calls the tool's build page content method to generate a confirmation page and returns it to the AI Agent, which then displays it to the end user for confirmation. Conversely, if the flag is not 1, the tool's execution method can be called directly to perform the actual business operation and return the execution result. Once the user confirms, the tool management system enters the Confirm phase. It queries the corresponding confirmation record based on its unique identifier and uses SELECT ... FOR UPDATE to lock the data row to prevent concurrent conflicts. It then checks if the record status is PENDING and if the current time has exceeded the confirmation deadline. If it has, the confirmation request is rejected and a timeout message is returned. If the status check passes and the timeout does not occur, the tool management system continues with permission verification to check if the user has the authority to execute the tool. If permission verification passes, the tool's execution method is called to perform the actual business operation, and the confirmation record status is updated to success or failure based on the operation result. The final execution result is returned to the AI Agent. If permission verification fails, the confirmation request is also rejected.
[0060] In this embodiment, optionally, permission verification is performed using at least one permission configuration record, combined with the current confirmer identifier and trigger parameters. This includes: traversing at least one permission configuration record; for the currently traversed permission configuration record, parsing the rule expression in the permission configuration record; when the rule expression is a full permission rule, determining whether the current confirmer identifier exists in the confirmer list in the permission configuration record; and if it is determined that the current confirmer identifier exists in the confirmer list in the permission configuration record, then the permission verification is successful; when the rule expression is an identifier rule, extracting a base identifier from the rule expression, extracting a to-be-verified identifier from the trigger parameters, comparing whether the base identifier and the to-be-verified identifier are consistent; if the comparison determines that the base identifier and the to-be-verified identifier are consistent, determining whether the current confirmer identifier exists in the confirmer list in the permission configuration record; and if it is determined that the current confirmer identifier exists in the confirmer list in the permission configuration record, then the permission verification is successful.
[0061] In this embodiment, during the permission verification process, the tool management system iterates through the permission configuration records associated with the tool, parsing and matching each record with rule expressions to determine whether the current confirmer has the necessary execution permissions. Each permission configuration record includes two core fields: a rule expression and a list of confirmers. The rule expression defines the specific permission judgment logic, while the list of confirmers lists the set of personnel authorized to execute the tool's operation. The tool management system extracts the confirmer's identifier from the current confirmation command and the trigger parameters from the confirmation record, using these as input to perform rule-by-rule verification. If any permission configuration record passes verification, the current confirmer is deemed authorized to execute the tool's operation.
[0062] Specifically, when the rule expression in the permission configuration record is a full permission rule (ALL type), the system does not need to compare any business data; it only needs to determine whether the current confirmer's identifier exists in the confirmer list of that configuration record. If the confirmer's identifier is in the list, the permission verification passes; otherwise, it continues to traverse the next permission configuration record. It should be noted that full permission rules are applicable to general operation scenarios that do not distinguish between business dimensions. For example, a system administrator may have unconditional execution permissions for the "node deployment" tool, and can directly operate on the node regardless of which session or application it belongs to.
[0063] When the rule expression is an identifier rule, the system needs to extract the baseline identifier from the rule expression and the identifier to be verified from the trigger parameters, then compare the two for consistency. Identifier rules cover various business dimensions, such as access control by session identifier, control by application identifier, control by server type, and access control matching by multiple identifiers. After the baseline identifier and the identifier to be verified match, the system further checks whether the current confirmer identifier exists in the confirmer list of this access configuration record. Access verification is considered successful only when both conditions are met.
[0064] In this way, through the combined configuration of the above-mentioned full permission rules and various identification rules, the tool management system achieves flexible and scalable fine-grained permission control. The permission rules are stored in the permission configuration table and are completely decoupled from the specific tool implementation code. When the permission requirements of the business dimension change, the administrator only needs to modify the permission configuration record in the database, without having to modify the judgment code in each tool implementation class one by one. At the same time, the permission configuration snapshot is recorded in the confirmation record during the triggering phase, which can ensure the accuracy of the permission rules at the time of confirmation execution and the traceability of subsequent audits. The permission verification mechanism based on rule expressions proposed in this application embodiment enables the tool management system to dynamically adapt to the permission control requirements of multiple dimensions and multiple scenarios, significantly reducing the maintenance cost of permission management while ensuring the security of sensitive operations.
[0065] Taking the "engine switching" tool as an example, suppose the tool management system configures two permission rules for this tool: one is "planId=12345", with the confirmation list containing Zhang San and Li Si; the other is "planId=67890", with the confirmation list containing Wang Wu and Zhao Liu. When the AI Agent initiates an engine switching request, the session ID in the trigger parameter is 12345, and the current confirmation person is Zhang San. The tool management system traverses the permission configuration records and matches the base identifier "12345" of the first rule with the session ID in the trigger parameter, and Zhang San is in the confirmation list, so the permission verification passes and the engine switching operation is allowed. If the current confirmation person is Wang Wu, although the session ID matches, Wang Wu is not in the confirmation list, so the system continues to traverse the second rule. The session ID "12345" does not match "67890", and all rules are not satisfied, so the permission verification fails and execution is refused.
[0066] In this embodiment of the application, optionally, when the rule expression is an identification rule, extracting a baseline identifier from the rule expression, extracting a to-be-verified identifier from the trigger parameters, and comparing whether the to-be-verified identifier is consistent with the baseline identifier includes: when the rule expression is a session-by-session identification rule, extracting a target session identifier from the rule expression as a baseline identifier, extracting an actual session identifier from the trigger parameters as a to-be-verified identifier, and comparing whether the actual session identifier is consistent with the target session identifier; when the rule expression is an application-by-application identification rule, extracting a target application identifier from the rule expression as a baseline identifier, extracting an actual application identifier from the trigger parameters as a to-be-verified identifier, and comparing whether the actual application identifier is consistent with the target session identifier; The system checks whether the identifier matches the target application identifier. If the rule expression is a server type rule, it extracts the target server type from the rule expression as the baseline identifier and extracts the actual server type from the trigger parameters as the identifier to be verified. It then compares whether the actual server type matches the target server type. If the rule expression is a multi-identifier matching rule, it extracts an identifier list separated by a preset identifier from the rule expression. Each identifier in the identifier list is used as a baseline identifier, and the identifier carried in the trigger parameters is used as the identifier to be verified. The system determines whether the identifier to be verified matches the baseline identifier by checking if the identifier to be verified exists among the baseline identifiers included in the identifier list.
[0067] In this embodiment, during the permission verification process, when the rule expression is an identification rule, the tool management system needs to extract the baseline identifier from the rule expression and the identifier to be verified from the trigger parameters, and then compare the consistency of the two. Specifically, identification rules are divided into various business dimension types. The tool management system will automatically identify the type based on the prefix of the rule expression and execute the corresponding extraction and comparison logic. Specifically, when the rule expression is a session-based identification rule, i.e., the prefix is "planId=", the tool management system will extract the target session identifier after the equals sign from the rule string as the baseline identifier, such as "12345" extracting "12345". Simultaneously, it will extract the actual session identifier from the trigger parameters as the identifier to be verified, and compare whether the two are consistent. If they are consistent, the system will proceed to the verification stage of the confirmer list.
[0068] When the rule expression is an application identifier rule, that is, the prefix is "appId=", the tool management system extracts the target application identifier as the base identifier, extracts the actual application identifier from the trigger parameters as the identifier to be verified, and compares whether the two are consistent.
[0069] When the rule expression is a server type rule, i.e., the prefix is "server_type=", the tool management system extracts the target server type as the baseline identifier, extracts the actual server type from the trigger parameters as the identifier to be verified, and compares whether the two are consistent.
[0070] When the rule expression is a multi-identifier matching rule, that is, when the prefix is "ids=", the tool management system extracts a list of identifiers separated by preset identifiers such as commas after the equal sign from the rule string. Each identifier in this list is used as the base identifier, and the identifier carried in the trigger parameter is used as the identifier to be verified. The system determines whether a match exists by judging whether the identifier to be verified exists in the identifier list.
[0071] In this way, through the combination and configuration of the above-mentioned multiple identification rules, the tool management system can flexibly realize fine-grained permission control based on multiple business dimensions such as session, application, server type and specific node ID. The permission rules are stored in the configuration table and decoupled from the tool implementation code. Adding or adjusting permission dimensions only requires adding or deleting configuration records in the database without modifying any tool class code. This enables the system to dynamically adapt to complex and ever-changing enterprise-level permission management needs, significantly improving the flexibility and maintainability of permission management while ensuring the security of sensitive operations.
[0072] Taking the AI Agent calling the "engine switching" tool as an example, suppose the tool management system has configured multiple permission configuration records for this tool to achieve control over different business dimensions. One record is "planId=12345", with the confirmer list being Zhang San and Li Si, which limits the engine switching to only session 12345 and requires the confirmer to be either Zhang San or Li Si. Another record is "appId=1001", with the confirmer list being Wang Wu, which limits the engine switching to only application 1001 and requires the confirmer to be Wang Wu. Yet another record is "server_type=production", with the confirmer list being Zhao Liu, which limits the operation to only production environment servers and requires the confirmer to be Zhao Liu. Finally, there is a record "ids=node001,node002,node003", with the confirmer list being Sun Qi, which limits the tool operation to only these three nodes. Thus, when a trigger request carries the following parameters: actual session identifier "12345", actual application identifier "1001", actual server type "production", and node to be operated "node001", and the current confirmer is Li Si, the tool management system iterates through the permission configuration records one by one: when a planId rule is matched, the actual session identifier in the trigger parameters matches the baseline identifier "12345" and Li Si is in the confirmer list, the permission verification passes immediately, and subsequent rules do not need to be iterated again; if the current confirmer is Wang Wu, the planId rule confirmer list does not match, so the appId rule is matched, the actual application identifier "1001" matches the baseline identifier "1001" and Wang Wu is in the confirmer list, and the permission verification passes.
[0073] In summary, the permission verification process proposed in this application embodiment is as follows: Figure 5 As shown, the `checkConfirmPermission()` method is first called to initiate verification. It loads all permission configuration records associated with the current tool from the `mcp_tool_config` permission configuration table and begins iterating through these permission rules. Permission rules support multiple types, including ALL full permissions, `planId` matching by session ID, `appId` matching by application ID, `ids` matching by ID list, and `server_type` matching by server type. The tool management system extracts the corresponding business data from the trigger parameters based on the type of each rule and compares it with the target value in the rule. When a rule matches successfully, the tool management system checks if the unique identifier of the current confirmer exists in the confirmer list specified by the rule using `confirmers.contains(uid)`. If it exists, the permission verification passes, and `true` is returned, indicating permission is granted, and there is no need to continue iterating through subsequent rules. If the current rule fails to match or the confirmer is not in the list, the system continues to the next rule for judgment. If no rule matches successfully after iterating through all permission rules, `false` is returned, indicating no permission is granted.
[0074] In this embodiment, optionally, the third method of the target tool instance is invoked, passing the trigger parameters and the current confirmer identifier as execution parameters, executing the tool operation and obtaining the execution result. This includes: identifying the target tool configuration information of the target tool instance, identifying whether the interface name field in the target tool configuration information is empty; when it is determined that the interface name field is not empty, determining that the target tool instance is a remote service tool, passing the trigger parameters and the current confirmer identifier as execution parameters to the target tool instance, and executing the passed target tool instance using a generalized invocation mechanism to obtain the execution result; when it is determined that the interface name field is empty, determining that the target tool instance is a local service tool, passing the trigger parameters and the current confirmer identifier as execution parameters to the target tool instance, and invoking the third method of the target tool instance to obtain the execution result.
[0075] In this embodiment, when performing tool operations, the tool management system first identifies the target tool configuration information of the target tool instance. Specifically, it determines the tool type by checking whether the interface name field in the configuration information is empty. If the interface name field is not empty, it indicates that the tool is a remote service tool and needs to be executed using a generic invocation mechanism. That is, the tool management system will pass the trigger parameters and the current confirmer identifier as execution parameters to the target tool instance, and then use the generic invocation mechanism to execute the remote service call to obtain the execution result.
[0076] If the interface name field is empty, it indicates that the tool is a local service tool. The tool management system will directly call its third method, that is, directly pass the trigger parameters and the current confirmer identifier as execution parameters to the target tool instance and call its third method to obtain the execution result.
[0077] In this way, through the combination of a unified interface and a generalized invocation mechanism, local service tools and remote service tools present a consistent invocation method to the upper-layer caller, which can shield the complexity of the underlying remote communication. This eliminates the need for developers to write additional HTTP clients or service discovery logic for remote tools. At the same time, the caching design and passive invalidation strategy of the generalized service reference take into account both invocation efficiency and fault recovery capability, significantly reducing the development cost and operational complexity of remote tool integration.
[0078] Taking the AI Agent calling a remote testing service tool as an example, assuming the tool's interface name field is configured as "com.santicloud.backend.testin.service.ITestinMcpToolService", and is not empty, it indicates that it is a remote service tool. After the tool management system recognizes it, it is executed through a generic invocation mechanism. During generic invocation, the method name is "confirm", the parameter type list is "java.lang.String" and "com.alibaba.fastjson.JSONObject", and the parameter value list is the tool name string and the merged execution parameter object. After the remote execution is completed, a hash table result is returned for the system to restore into a unified result object.
[0079] In this embodiment, optionally, the trigger parameter and the current confirmer identifier are passed as execution parameters to the target tool instance, and the passed target tool instance is executed using a generalized invocation mechanism to obtain the execution result. This includes: creating a generalized service reference, setting the registry center address, generalized invocation mode identifier, start check switch, and timeout period of the generalized service reference; determining the remote service method name of the remote service based on the target tool identifier of the target tool instance, and obtaining the list of method parameter types associated with the remote service method name from the target tool configuration information; assembling the trigger parameter and the current confirmer identifier into a parameter value list, and passing the remote service method name, method parameter type list, and parameter value list through the generalized service reference's generalized invocation method to execute the remote method call and obtain the return result; integrating the status code, execution message, and data fields carried in the return result and converting the format into a preset result object format to obtain the execution result.
[0080] In this embodiment, when executing a remote service tool using a generic invocation mechanism, the tool management system first creates a generic service reference and sets four key configuration parameters: the registry address, the generic invocation mode flag, the startup check switch, and the timeout period. The registry address can be in the format "spring-cloud: / / localhost", indicating that Dubbo uses the Spring Cloud service discovery client to find services, connecting to a uniformly configured Nacos registry center, and supporting multiple addresses separated by commas for high availability. The generic invocation mode flag can be set to true to enable generic invocation; the startup check switch can be set to false to avoid blocking the local service startup when the remote service is not online; and the timeout period can be set to 60 seconds.
[0081] After creation, the tool management system determines the remote service method name based on the target tool instance's target tool identifier. For example, when calling the remote service's method to retrieve tool result content, the method name is "buildResultContent"; when calling the confirmation operation method, the method name is "confirm"; and when calling the external notification service, the method name is "sendToGroup". It then retrieves the list of method parameter types associated with this remote service method name from the target tool's configuration information. This list is a string array, where each element is the fully qualified name of the parameter class, such as "java.lang.String" for string type and "com.alibaba.fastjson.JSONObject" for JSON object type. Subsequently, the tool management system assembles trigger parameters (including business parameters and metadata) and the current confirmer identifier into a parameter value list. This parameter value list is an object array, corresponding sequentially according to the parameter type list. The tool management system then executes the remote method call by passing the remote service method name, the method parameter type list, and the parameter value list through a generic service reference's generalized invocation method, and retrieves the return result. The result returned by the generalized call is a hash table. The tool management system will extract the status code, message and data fields from it through the conversion method and integrate them into a preset unified result object format to obtain a standardized execution result.
[0082] It should be noted that, in this embodiment, regarding the cache design, the tool management system caches the created generic service instances in a thread-safe concurrent hash table. The key format is "fully qualified interface name@service name". The reason why the key does not include the method name and parameters is that the generic service reference is an interface-level proxy object. That is, the same generic service reference instance can execute any method under the interface through the general call method, without needing to create an independent reference for each method. Therefore, the combination of the same interface and service name only needs to create one generic service instance and cache it to support calling all methods under the interface. In addition, in this embodiment, regarding the cache invalidation strategy, the tool management system adopts a call failure-driven passive invalidation strategy, rather than a timed invalidation based on TTL (Time To Live). Under normal circumstances, the generic service instances in the cache are continuously reused and have no expiration time. When a generic call throws an exception, such as a network failure or the remote service being unavailable, the corresponding instance will be immediately removed from the cache, and a new generic service instance will be created for retry. The retry logic is that after the first call fails, the cache is cleared and a retry is immediately performed. If the retry still fails, an error result is returned. Compared to the TTL solution, the passive failure strategy has zero overhead when the service is normal, does not require timers and cache refresh, and can immediately rebuild the connection and restore the calling capability when the service is abnormal, avoiding two wasteful scenarios: "the service has failed before the TTL has expired" and "the service is running normally after the TTL has expired, resulting in unnecessary rebuilding".
[0083] In this way, through the above-mentioned generalized invocation mechanism, local tools and remote tools present a consistent invocation interface to the upper-layer caller. Developers do not need to write HTTP clients for each remote tool or manually configure service discovery logic. At the same time, the caching design also takes into account invocation efficiency and fault recovery capabilities, thereby significantly reducing the development cost and operational complexity of remote tool integration.
[0084] Taking the AI Agent calling an external notification service as an example, the interface name of this remote tool is "com.santicloud.notify.service.INotifyService", the service name is "notify-service", the method name is "sendToGroup", and the parameter type list consists of four "java.lang.String" elements corresponding to the group ID, title, message content, and the notified worker ID, respectively. After the tool management system creates a generic service reference, it caches it in a ConcurrentHashMap with the key "com.santicloud.notify.service.INotifyService@notify-service". When the AI Agent needs to send a test result notification, it passes in the group ID "group_123", the title "Engine switching completed", the message content "Session 12345 Engine successfully switched" and the notified worker ID "zhangsan" as a list of parameter values. The remote call is executed through a general calling method, and the returned hash table result is converted to obtain a unified execution result object.
[0085] Optionally, in this embodiment, the method further includes: creating a service instance table and a tool mapping table. The service instance table includes a service instance identifier, a service name set as a path parameter of the endpoint URL, and an activation status field. The tool mapping table records the association between each tool identifier and the service instance identifier. When a tool list retrieval request is received, the target endpoint URL that initiated the tool list retrieval request is determined, the target service name is extracted from the target endpoint URL, and the corresponding target activation status field is queried in the service instance table based on the target service name. If the target activation status field indicates that the tool is enabled, the target service instance identifier corresponding to the target service name is queried in the service instance table, and multiple specified tool identifiers associated with the target service instance identifier are queried in the tool mapping table. Multiple specified tools indicated by the multiple specified tool identifiers are determined, and the tool name, function description, and parameter pattern definition of each specified tool are queried in batches. The tool name, function description, and parameter pattern definition of each specified tool are assembled into a tool list and returned to the caller that initiated the tool list retrieval request. The parameter pattern definition uses JSON Schema format to describe the name, type, and constraints of the tool input parameters.
[0086] In this embodiment, to enable different AI Agents to use different toolsets in a multi-tenant scenario, a service instance table and a tool mapping table are created in the tool management system. The service instance table stores information about multiple MCP service instances, each corresponding to an AI Agent. This table includes a service instance identifier, a service name set as a path parameter in the endpoint URL, and an enable / disable status field. Specifically, the service instance identifier is an auto-incrementing integer primary key and serves as the unique identifier of the service instance; the service name is a string with a unique constraint, storing the MCP service name, which is also used as a path parameter in the endpoint URL for request routing; the enable / disable status field can be a status field, a string with a value of VALID (enabled) or INVALID (disabled), controlling whether the service instance is accessible. In addition to the fields mentioned above, it may also include a description field that stores a textual description of the MCP service, a remarks field that stores remarks information, a max_connections field that limits the maximum number of concurrent SSE connections for the MCP service and has an integer default value of 50, and an is_deleted field that serves as a soft deletion identifier; furthermore, it may also include audit fields such as last_updated_name, created_time, and updated_time.
[0087] The tool mapping table is used to store the association relationships between service instances and tools. Specifically, it can include fields such as `id` (auto-incrementing primary key), `mcp_id` (foreign key associated with the primary key `id` of the service instance table), `mcp_tool_id` (foreign key associated with the primary key `id` of the tool table), `status` (VALID or INVALID to control whether the mapping is effective), `is_deleted` (soft deletion flag), `last_updated_name`, `created_time`, and `updated_time`. Through the tool mapping table, one MCP service can be associated with multiple tools, and one tool can be referenced by multiple MCP services, forming a many-to-many relationship. When configuring MCP services, administrators can select the associated tool set through the interface. The tool management system automatically maintains the mapping relationships; that is, it checks for duplicates during creation to avoid duplicate associations, and during updates, it adopts a reconstruction strategy of first deleting the old mapping and then inserting the new mapping to ensure data consistency.
[0088] When the AI Agent requests a list of tools through a service endpoint, the tool management system dynamically routes and filters tools based on the service name parameter in the target endpoint URL. Specifically, the AI Agent connects to the MCP service via the SSE endpoint URL, which has the format "{base address} / mcp / {service name} / sse". For example, in the test environment it's "http: / / test.com / v1 / mcp / testin / sse", and in the production environment it's "http: / / production.com / v1 / mcp / rtn / sse". The service name parameter is extracted as a path variable from the URL path, parsed by the gateway service's HTTP routing layer, and passed to the backend business service. Upon receiving a request, the backend service first queries the service instance table based on the extracted service name to retrieve the corresponding record and verifies whether the status field is VALID. If the status is enabled, processing continues; otherwise, an error message is returned. Next, the service instance record's primary key ID is used to query the tool mapping table to retrieve all mapping records with a VALID status that have not been deleted, resulting in multiple specified tool identifiers associated with that service instance. Then, the tool table is queried in batches based on these tool identifiers to obtain detailed information for each tool. This information includes the tool name, function description, and parameter pattern definition. The tool name serves as a unique identifier for subsequent call matching; the function description helps the AI Agent's large language model understand the tool's purpose and determine when to invoke it; and the parameter pattern definition uses JSON Schema format to describe the name, type, and constraints of the tool's input parameters, allowing the AI Agent to automatically generate call parameters. If the parameter pattern field in the tool mapping table is empty, a default empty parameter structure is returned. The empty parameter structure is of type object and has no attributes. The tool management system assembles the tool name, function description, and parameter mode definition of each specified tool into a tool list format specified by the MCP protocol, and returns it to the AI Agent that initiated the request via a JSON-RPC response. Each element of the tool array in the response contains three fields: name, description, and inputSchema.
[0089] In this way, through the combination of the service instance table and the tool mapping table, the tool management system can achieve flexible grouping and dynamic configuration of toolsets. Administrators can assign differentiated tool sets to different AI Agents without modifying the code, which can not only meet the isolation requirements in multi-tenant scenarios, but also simplify the centralized management of tool permissions.
[0090] For example, suppose an MCP service named "rtn" is associated with operation and maintenance tools such as engine switching and node online / offline through mapping relationships. When the AI Agent requests a list of tools through the endpoint "http: / / production.com / v1 / mcp / rtn / sse", the tool management system only returns operation and maintenance tools. On the other hand, an MCP service named "testin" is associated with test-related tools such as test case execution and test report generation. When the AI Agent requests it through the endpoint "http: / / test.com / v1 / mcp / testin / sse", it only returns a set of test tools, thus achieving tool isolation at different tenant levels.
[0091] The method provided in this application defines a unified tool interface and uses a dependency injection mechanism to encapsulate the differences in calling local and remote tools within the interface implementation. Automatic scanning and registration during container startup eliminates the need for the framework to be aware of the underlying protocol type, thereby eliminating core code modifications when adding new tools, improving system scalability, and complying with the open / closed principle. Simultaneously, the confirmation and verification process based on the memory registry and configuration information integrates the maintenance of confirmation record status, deadline control, and idempotency guarantees into the framework management, avoiding developers repeatedly writing error-prone state machines and callback logic for sensitive operations, and reducing concurrency race conditions and consistency issues. Furthermore, permission verification achieves logical decoupling through preset rules and matching with business data, allowing permission changes to dynamically adapt to multi-dimensional permission control needs without modifying each tool implementation class individually, improving development efficiency while enhancing the system's runtime security control capabilities.
[0092] Furthermore, as Figure 1 To specifically implement the method, this application provides a tool execution device based on the MCP protocol, such as... Figure 6 As shown, the device includes: an interface definition module 601, a scanning module 602, a query module 603, a verification module 604, a permission verification module 605, and an execution module 606.
[0093] The interface definition module 601 is used to define a unified tool interface for the MCP protocol. The unified tool interface defines a first method for obtaining the tool identifier, a second method for constructing the display content, and a third method for performing tool operations. The scanning module 602 is used to scan and load all utility class instances that implement the unified tool interface when the container starts through the dependency injection mechanism, and to obtain the tool identifier of each utility class instance by calling the first method, and store each utility class instance and its corresponding tool identifier in the memory registry in the form of key-value pairs; The query module 603 is used to respond to a tool call request, obtain a target tool instance from the memory registry based on the target tool identifier carried in the tool call request, and query the target tool configuration information based on the target tool identifier; The verification module 604 is used to create a confirmation record marked as pending confirmation and set a confirmation deadline when it is determined that the target tool configuration information indicates that there is a confirmation requirement; and to construct a confirmation page and return by calling the second method. The verification module 604 is further configured to perform an initial verification based on the confirmation record and the deadline when a confirmation instruction is received based on the confirmation page; The permission verification module 605 is used to perform permission verification using preset permission rules after the verification is passed. The execution module 606 is used to call the third method to execute the tool operation of the target tool instance after the permission verification is passed, and update the status of the confirmation record according to the execution result.
[0094] In a specific application scenario, the interface definition module 601 is used to define the original tool interface. Referring to the MCP protocol, the first method, the second method, and the third method are defined in the original tool interface. The first method is a method that returns a string-type tool identifier without input parameters. The second method is a method that receives trigger parameters including business parameters and metadata and returns a structured result including a display content portion and a result data portion. The third method is a method that receives merged execution parameters and returns an execution result. Simultaneously, an abstract base class implementing preset general logic is defined in the original tool interface, so that the defined original tool interface serves as the unified tool interface. The abstract base class defines the display content construction sub-method in the first method and the second method, and the execution operation sub-method in the third method, as abstract methods.
[0095] In a specific application scenario, the scanning module 602 is used to construct a tool registry class, mark the tool registry class as a container management component, and define a list parameter of tool interface types in the constructor of the tool registry class; when the container management component starts, it scans and injects all tool class instances that implement the unified tool interface through the dependency injection mechanism; during the initialization phase of the tool registry class, it constructs the memory registry, traverses each tool class instance, sequentially calls the first method of each specific tool class instance to obtain the tool identifier corresponding to each specific tool class instance, and stores the tool identifier of each specific tool class instance as a key and each specific tool class instance as a value in the memory registry in the form of key-value pairs.
[0096] In a specific application scenario, the verification module 604 is used to identify whether a confirmation flag is required and the default timeout duration included in the target tool configuration information; when the confirmation flag indicates that confirmation is required, a confirmation record is created, and the status field of the confirmation record is set to pending confirmation; the current time is determined, and the default timeout duration is added to the current time to determine the confirmation deadline; the request trigger information carried by the tool call request is extracted, the target tool flag and the request trigger information are recorded in the confirmation record, and a record flag of the confirmation record is generated; the confirmation record is labeled with the record flag and stored in the database, the request trigger information including trigger parameters and triggerer information; the second method is called to pass in the trigger parameters, the second method generates the confirmation page, the confirmation page is associated with the confirmation record, and the record flag and the confirmation page are returned.
[0097] In specific application scenarios, the verification module 604 is further configured to, when a confirmation instruction is received based on the confirmation page, query and lock the data row where the confirmation record is located in the database using a database row-level exclusive lock according to the record identifier; read the status field and the confirmation deadline in the confirmation record, verify whether the status field is pending confirmation and whether the current time has not exceeded the confirmation deadline; and determine that the initial verification is successful when it is verified that the status field is pending confirmation and the current time has not exceeded the confirmation deadline. The permission verification module 605 is used to obtain a permission configuration table for storing preset permission rules, query at least one permission configuration record associated with the target tool identifier in the permission configuration table, wherein each permission configuration record includes a rule expression and a list of confirmers; extract the current confirmer identifier from the confirmation instruction, extract the trigger parameter from the confirmation record, and perform permission verification using the at least one permission configuration record, combined with the current confirmer identifier and the trigger parameter; The execution module 606 is configured to, when the permission verification performed using any one of the at least one permission configuration records passes, call the third method of the target tool instance, pass the trigger parameter and the current confirmer identifier as execution parameters, execute the tool operation and obtain the execution result; update the status field of the confirmation record to success or failure according to the execution result, record the current confirmer identifier and the execution result in the confirmation record, and commit the transaction to release the database row-level exclusive lock.
[0098] In a specific application scenario, the permission verification module 605 is used to traverse the at least one permission configuration record. For the currently traversed permission configuration record, it parses the rule expression in the permission configuration record. When the rule expression is a full permission rule, it determines whether the current confirmer identifier exists in the confirmer list in the permission configuration record. If it is determined that the current confirmer identifier exists in the confirmer list in the permission configuration record, then the permission verification is determined to be successful. When the rule expression is an identifier rule, it extracts a base identifier from the rule expression, extracts a to-be-verified identifier from the trigger parameter, and compares whether the base identifier and the to-be-verified identifier are consistent. If it is determined that the base identifier and the to-be-verified identifier are consistent, it determines whether the current confirmer identifier exists in the confirmer list in the permission configuration record. If it is determined that the current confirmer identifier exists in the confirmer list in the permission configuration record, then the permission verification is determined to be successful.
[0099] In specific application scenarios, the permission verification module 605 is used to: extract the target session identifier from the rule expression as the base identifier when the rule expression is a session identifier rule; extract the actual session identifier from the trigger parameters as the identifier to be verified; and compare whether the actual session identifier is consistent with the target session identifier. When the rule expression is an application identifier rule, it extracts the target application identifier from the rule expression as the base identifier; extracts the actual application identifier from the trigger parameters as the identifier to be verified; and compare whether the actual application identifier is consistent with the target application identifier. When the rule expression is a server class rule... In the case of a type-based rule, the target server type is extracted from the rule expression as the baseline identifier, and the actual server type is extracted from the trigger parameter as the identifier to be verified. The actual server type is compared with the target server type to see if they are consistent. In the case of a multi-identifier matching rule, an identifier list separated by a preset identifier is extracted from the rule expression. Each identifier included in the identifier list is used as a baseline identifier, and the identifier carried in the trigger parameter is used as the identifier to be verified. By determining whether the identifier to be verified exists in each of the baseline identifiers included in the identifier list, it is determined whether the identifier to be verified is consistent with the baseline identifier.
[0100] In a specific application scenario, the execution module 606 is used to identify the target tool configuration information of the target tool instance, and to identify whether the interface name field in the target tool configuration information is empty; when it is determined that the interface name field is not empty, the target tool instance is determined to be a remote service tool, the trigger parameter and the current confirmer identifier are passed to the target tool instance as execution parameters, and the passed target tool instance is executed using a generalized invocation mechanism to obtain the execution result; when it is determined that the interface name field is empty, the target tool instance is determined to be a local service tool, the trigger parameter and the current confirmer identifier are passed to the target tool instance as execution parameters, and the third method of the target tool instance is called to obtain the execution result.
[0101] In a specific application scenario, the execution module 606 is used to create a generic service reference, set the registry address, generic invocation mode identifier, start check switch, and timeout period of the generic service reference; determine the remote service method name of the remote service based on the target tool identifier of the target tool instance, and obtain the list of method parameter types associated with the remote service method name from the target tool configuration information; assemble the trigger parameter and the current confirmer identifier into a parameter value list, and pass the remote service method name, the list of method parameter types, and the list of parameter values through the general invocation method of the generic service reference to execute the remote method call and obtain the return result; integrate the status code, execution message, and data fields carried in the return result and convert the format into a preset result object format to obtain the execution result.
[0102] In specific application scenarios, the device further includes: The group management module is used to create a service instance table and a tool mapping table. The service instance table includes a service instance identifier, a service name set as a path parameter of the endpoint URL, and an activation status field. The tool mapping table records the association between each tool identifier and a service instance identifier. When a tool list retrieval request is received, the module determines the target endpoint URL that initiated the request, extracts the target service name from the target endpoint URL, and queries the corresponding target activation status field in the service instance table based on the target service name. If the target activation status field indicates that the service is enabled, the module queries the service instance table for the target service name corresponding to it, and queries the tool mapping table for multiple specified tool identifiers associated with the target service instance identifier. The module determines the multiple specified tools indicated by the multiple specified tool identifiers, and performs batch queries for the tool name, function description, and parameter pattern definition of each specified tool. The module assembles the tool name, function description, and parameter pattern definition of each specified tool into a tool list and returns it to the caller that initiated the tool list retrieval request. The parameter pattern definition uses JSON Schema format to describe the name, type, and constraints of the tool input parameters.
[0103] The apparatus provided in this application defines a unified tool interface and uses a dependency injection mechanism to encapsulate the differences in calling local and remote tools within the interface implementation. Automatic scanning and registration during container startup eliminates the need for the framework to be aware of the underlying protocol type, thereby eliminating the need for core code modifications when adding new tools, improving system scalability, and complying with the open / closed principle. Simultaneously, the confirmation and verification process based on the memory registry and configuration information integrates the maintenance of confirmation record status, deadline control, and idempotency guarantees into the framework management, avoiding developers repeatedly writing error-prone state machines and callback logic for sensitive operations, and reducing concurrency race conditions and consistency issues. Furthermore, permission verification achieves logical decoupling through preset rules and matching with business data, allowing permission changes to dynamically adapt to multi-dimensional permission control needs without modifying each tool implementation class individually, improving development efficiency while enhancing the system's runtime security control capabilities.
[0104] It should be noted that other corresponding descriptions of the functional units involved in the tool execution device based on the MCP protocol provided in this application embodiment can be found in the following references. Figures 1 to 5 The corresponding descriptions in [the document] will not be repeated here.
[0105] It should be noted that the user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, data stored, data displayed, etc.) involved in this application are all information and data authorized by the user or fully authorized by all parties.
[0106] It should be noted that any AI models, software tools, or components not belonging to this company appearing in the embodiments of this application are merely illustrative examples and do not represent actual use. All user personal information involved in the embodiments of this application has been authorized (with the knowledge and consent) by the relevant parties or has been fully authorized by all parties, and the executing entity may obtain it through various legal and compliant means. The collection, storage, use, processing, transmission, provision, and disclosure of the information, data, and signals involved all comply with relevant laws and regulations and do not violate public order and good morals.
[0107] The above embodiments and the technical features in the embodiments can be combined arbitrarily. For the sake of brevity, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.
[0108] The embodiments described above are merely examples of several implementation methods of this application, and while the descriptions are specific and detailed, they should not be construed as limiting the scope of this patent application. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of this application, and these modifications and improvements all fall within the protection scope of this application.
[0109] In an exemplary embodiment, see Figure 7 An electronic device is also provided, comprising a bus 701, a processor 702, a memory 703, and a communication interface 704. It may also include an input / output interface 705 and a display device 706. The various functional units can communicate with each other via the bus. The memory 703 stores a computer program, which, from bottom to top, includes a kernel 7034 that directly manages the hardware, middleware 7033 that provides general services for applications, an application programming interface 7032 that defines calling specifications, and an application 7031 that implements specific business logic. The processor 702 is used to read from the memory 703 via the bus 701 and execute the program stored in the memory, performing the tool execution method based on the MCP protocol described in the above embodiments.
[0110] A computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the steps of the tool execution method based on the MCP protocol.
[0111] Through the above description of the embodiments, those skilled in the art can clearly understand that this application can be implemented in hardware or by using software plus necessary general-purpose hardware platforms. Based on this understanding, the technical solution of this application can be embodied in the form of a software product, which can be stored in a non-volatile storage medium (such as a CD-ROM, USB flash drive, external hard drive, etc.) and includes several instructions to cause a computer device (such as a personal computer, server, or network device, etc.) to execute the methods described in the various embodiments of this application.
[0112] Those skilled in the art will understand that the accompanying drawings are merely schematic diagrams of a preferred embodiment, and the modules or processes shown in the drawings are not necessarily essential for implementing this application.
[0113] Those skilled in the art will understand that the modules in the apparatus of the implementation scenario can be distributed within the apparatus of the implementation scenario as described, or they can be located in one or more apparatuses different from this implementation scenario, with corresponding changes. The modules of the above-described implementation scenario can be combined into one module, or they can be further divided into multiple sub-modules.
[0114] The serial numbers in this application are for descriptive purposes only and do not represent the superiority or inferiority of the implementation scenario.
[0115] The above disclosures are only a few specific implementation scenarios of this application. However, this application is not limited to these. Any variations that can be conceived by those skilled in the art should fall within the protection scope of this application.< / imcptool>
Claims
1. A tool execution method based on the MCP protocol, characterized in that, include: Define a unified tool interface for the MCP protocol, wherein the unified tool interface defines a first method for obtaining the tool identifier, a second method for constructing the display content, and a third method for performing tool operations; By using the dependency injection mechanism, all utility class instances that implement the unified tool interface are scanned and loaded when the container starts. The tool identifier of each utility class instance is obtained by calling the first method, and each utility class instance and its corresponding tool identifier are stored in the memory registry in the form of key-value pairs. In response to a tool invocation request, the target tool instance is retrieved from the memory registry based on the target tool identifier carried in the tool invocation request, and the target tool configuration information is queried based on the target tool identifier; When it is determined that the target tool configuration information indicates a confirmation requirement, a confirmation record marked as pending confirmation is created and a confirmation deadline is set. The confirmation page is then constructed and returned by calling the second method. When a confirmation instruction is received based on the confirmation page, an initial verification is performed based on the confirmation record and the deadline. After the verification is passed, permission verification is performed using preset permission rules. After the permission verification is passed, the third method is called to execute the tool operation of the target tool instance, and the status of the confirmation record is updated according to the execution result.
2. The method according to claim 1, characterized in that, The unified tool interface defining the MCP protocol includes: Define the original tool interface, and define the first method, the second method and the third method in the original tool interface with reference to the MCP protocol. The first method is a method that has no input parameters and returns a tool identifier of type string. The second method is a method that receives trigger parameters including business parameters and metadata and returns a structured result including a display content part and a result data part. The third method is a method that receives merged execution parameters and returns an execution result. Meanwhile, an abstract base class implementing preset general logic is defined in the original tool interface, so that the original tool interface that has been defined can be used as the unified tool interface. The abstract base class defines the content display construction sub-method in the first method, the content display construction sub-method in the second method, and the execution operation sub-method in the third method as abstract methods.
3. The method according to claim 1, characterized in that, The process of scanning and loading all utility class instances implementing the unified utility interface during container startup via dependency injection, and obtaining the utility identifier of each utility class instance by calling the first method, and storing each utility class instance and its corresponding utility identifier in a memory registry as key-value pairs, includes: Construct a tool registry class, mark the tool registry class as a container management component, and define a list parameter of tool interface types in the constructor of the tool registry class; When the container management component starts, it scans and injects all utility class instances that implement the unified tool interface through the dependency injection mechanism. During the initialization phase of the tool registry class, the memory registry is constructed, each tool class instance is traversed, and the first method of each specific tool class instance is called sequentially to obtain the tool identifier corresponding to each specific tool class instance. The tool identifier of each specific tool class instance is used as the key and each specific tool class instance is used as the value, and stored in the memory registry in the form of key-value pairs.
4. The method according to claim 1, characterized in that, When the target tool configuration information indicates a confirmation requirement, the process of creating a confirmation record marked as pending confirmation and setting a confirmation deadline, constructing a confirmation page and returning it by calling the second method, includes: Identify whether a confirmation flag is required and the default timeout duration included in the target tool configuration information; When the confirmation flag indicates that confirmation is required, a confirmation record is created, and the status field of the confirmation record is set to pending confirmation. Determine the current time, and add the default timeout duration to the current time to determine the confirmation deadline; Extract the request trigger information carried in the tool call request, record the target tool identifier and the request trigger information in the confirmation record, generate a record identifier for the confirmation record, and store the confirmation record in the database after annotating it with the record identifier. The request trigger information includes trigger parameters and triggerer information. The second method is invoked to pass in the trigger parameters, the second method generates the confirmation page, the confirmation page is associated with the confirmation record, and the record identifier and the confirmation page are returned.
5. The method according to claim 4, characterized in that, When a confirmation instruction is received based on the confirmation page, an initial verification is performed based on the confirmation record and the deadline. After the verification passes, permission verification is performed using preset permission rules. After the permission verification passes, the third method is invoked to execute the tool operation of the target tool instance, and the status of the confirmation record is updated according to the execution result. This includes: When a confirmation instruction is received based on the confirmation page, the data row containing the confirmation record is queried and locked in the database using a database row-level exclusive lock according to the record identifier; Read the status field and the confirmation deadline from the confirmation record, and verify whether the status field is pending confirmation and whether the current time has not exceeded the confirmation deadline. When the verification determines that the status field is pending confirmation and the current time has not exceeded the confirmation deadline, the initial verification is determined to be successful. A permission configuration table for storing preset permission rules is obtained. At least one permission configuration record associated with the target tool identifier is queried in the permission configuration table. Each permission configuration record includes a rule expression and a list of confirmers. Extract the current confirmer identifier from the confirmation instruction, extract the trigger parameter from the confirmation record, and perform permission verification using the at least one permission configuration record, combined with the current confirmer identifier and the trigger parameter; When the permission verification performed using any one of the at least one permission configuration record passes, the third method of the target tool instance is invoked, and the trigger parameter and the current confirmer identifier are passed in as execution parameters to perform tool operations and obtain the execution result; Update the status field of the confirmation record to success or failure based on the execution result, record the current confirmer's identifier and the execution result in the confirmation record, and commit the transaction to release the database row-level exclusive lock.
6. The method according to claim 5, characterized in that, The permission verification process, which utilizes at least one permission configuration record, combined with the current confirmer identifier and the trigger parameters, includes: Iterate through the at least one permission configuration record, and for the currently iterated permission configuration record, parse the rule expression in the permission configuration record; When the rule expression is a full permission rule, it is determined whether the current confirmer identifier exists in the confirmer list in the permission configuration record. If it is determined that the current confirmer identifier exists in the confirmer list in the permission configuration record, then the permission verification is determined to be successful. When the rule expression is an identifier rule, a baseline identifier is extracted from the rule expression, and a identifier to be verified is extracted from the trigger parameter. The baseline identifier and the identifier to be verified are compared to see if they are consistent. If the comparison determines that the baseline identifier and the identifier to be verified are consistent, it is determined whether the current confirmer identifier exists in the confirmer list in the permission configuration record. If it is determined that the current confirmer identifier exists in the confirmer list in the permission configuration record, then the permission verification is determined to be successful.
7. The method according to claim 6, characterized in that, When the rule expression is an identifier rule, the process of extracting a baseline identifier from the rule expression, extracting a identifier to be verified from the trigger parameters, and comparing whether the identifier to be verified is consistent with the baseline identifier includes: When the rule expression is a rule based on session identifier, the target session identifier is extracted from the rule expression as the baseline identifier, and the actual session identifier is extracted from the trigger parameter as the identifier to be verified. The actual session identifier is then compared with the target session identifier to see if they are consistent. When the rule expression is an application identifier rule, the target application identifier is extracted from the rule expression as the baseline identifier, the actual application identifier is extracted from the trigger parameter as the identifier to be verified, and the actual application identifier is compared with the target application identifier to see if they are consistent. When the rule expression is a server type rule, the target server type is extracted from the rule expression as the baseline identifier, the actual server type is extracted from the trigger parameter as the verification identifier, and the actual server type is compared with the target server type to see if they are consistent. When the rule expression is a multi-identifier matching rule, an identifier list separated by a preset identifier is extracted from the rule expression. Each identifier included in the identifier list is used as a base identifier, and the identifier carried in the trigger parameter is used as the identifier to be verified. By determining whether the identifier to be verified exists in each of the base identifiers included in the identifier list, it is determined whether the identifier to be verified is consistent with the base identifier.
8. The method according to claim 5, characterized in that, The third method for invoking the target tool instance, which passes the trigger parameter and the current confirmer identifier as execution parameters, executes tool operations and obtains the execution result, includes: The target tool configuration information of the target tool instance is identified, and it is determined whether the interface name field in the target tool configuration information is empty; When it is determined that the interface name field is not empty, the target tool instance is determined to be a remote service tool. The trigger parameter and the current confirmer identifier are passed to the target tool instance as execution parameters, and the passed target tool instance is executed using a generalized invocation mechanism to obtain the execution result. When it is determined that the interface name field is empty, the target tool instance is determined to be a local service tool. The trigger parameter and the current confirmer identifier are passed to the target tool instance as execution parameters, and the third method of the target tool instance is called to obtain the execution result.
9. The method according to claim 8, characterized in that, The step of passing the triggering parameter and the current confirmer identifier as execution parameters to the target tool instance, and executing the passed target tool instance using a generalized invocation mechanism to obtain the execution result, includes: Create a generic service reference, and set the registry address, generic invocation mode identifier, start check switch and timeout time for the generic service reference; Based on the target tool identifier of the target tool instance, determine the remote service method name of the remote service, and obtain the list of method parameter types associated with the remote service method name from the target tool configuration information; The triggering parameters and the current confirmer identifier are assembled into a parameter value list, and the remote service method name, the method parameter type list, and the parameter value list are passed through the general calling method of the generalized service reference to execute the remote method call and obtain the return result; The status code, execution message, and data fields carried in the returned result are integrated and converted into a preset result object format to obtain the execution result.
10. The method according to claim 1, characterized in that, The method further includes: Create a service instance table and a tool mapping table. The service instance table includes a service instance identifier, a service name set as a path parameter of the endpoint URL, and an enable status field. The tool mapping table records the association between each tool identifier and the service instance identifier. When a tool list retrieval request is received, the target endpoint URL that initiated the tool list retrieval request is determined, the target service name is extracted from the target endpoint URL, and the corresponding target activation status field is queried in the service instance table based on the target service name. If the target enable status field indicates that it is enabled, query the target service instance identifier corresponding to the target service name in the service instance table, and query multiple specified tool identifiers associated with the target service instance identifier in the tool mapping table; The system identifies multiple specified tools indicated by the specified tool identifiers, and performs batch queries on the tool name, function description, and parameter pattern definition of each specified tool. It then assembles the tool name, function description, and parameter pattern definition of each specified tool into a tool list and returns it to the caller who initiated the request to obtain the tool list. The parameter pattern definition uses JSON Schema format to describe the name, type, and constraints of the tool input parameters.
11. A tool execution device based on the MCP protocol, characterized in that, include: The interface definition module is used to define a unified tool interface for the MCP protocol. The unified tool interface defines a first method for obtaining the tool identifier, a second method for constructing and displaying content, and a third method for performing tool operations. The scanning module is used to scan and load all utility class instances that implement the unified tool interface when the container starts through the dependency injection mechanism, and to obtain the tool identifier of each utility class instance by calling the first method, and store each utility class instance and its corresponding tool identifier in the memory registry in the form of key-value pairs; The query module is used to respond to a tool call request, obtain a target tool instance from the memory registry based on the target tool identifier carried in the tool call request, and query the target tool configuration information based on the target tool identifier; The verification module is used to create a confirmation record marked as pending confirmation and set a confirmation deadline when it is determined that the target tool configuration information indicates that there is a confirmation requirement. It then constructs a confirmation page and returns it by calling the second method. The verification module is also used to perform an initial verification based on the confirmation record and the deadline when a confirmation instruction is received based on the confirmation page; The permission verification module is used to verify permissions using preset permission rules after the verification is passed. The execution module is used to call the third method to execute the tool operation of the target tool instance after the permission verification is passed, and update the status of the confirmation record according to the execution result.
12. A computer device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the computer program, it implements the steps of the method according to any one of claims 1 to 10.
13. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the steps of the method according to any one of claims 1 to 10.
