A method and system for mcp tool invocation

By optimizing the SpringAI framework and dual-mode authentication, and combining aspect-chain security checks, we have implemented security verification and permission management for the MCP tool call system. This solves the problems of seamless transmission of authentication and non-standard exception handling in the MCP protocol, and improves the stability and security of the call process.

CN122153859APending Publication Date: 2026-06-05BEIJING THREATBOOK TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-05-09
Publication Date
2026-06-05

Smart Images

  • Figure CN122153859A_ABST
    Figure CN122153859A_ABST
Patent Text Reader

Abstract

The application discloses an MCP tool calling method and system. The method comprises the following steps: when initiating the MCP tool calling, a client sends a target calling request to a server; the server generates an internal context object according to the received target calling request, performs internal and external dual-mode identity authentication on the internal context object to obtain a first authentication result, generates a target context object according to the first authentication result and the internal context object, performs security authentication on the target context object through an aspect execution chain to obtain a second authentication result, and when it is judged that the target context object passes the security authentication according to the second authentication result, calls a corresponding business tool according to the target context object and executes a corresponding business method. The method can realize the full-link security management and control and identity reliable transmission of the MCP tool calling without invading the original business code, and improves the security, standardization and controllability of the AI tool calling.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of computer technology, specifically to a method and system for calling an MCP tool. Background Technology

[0002] With the rapid development of Large Language Model (LLM) technology, AI agent systems have increasingly relied on external tools to enhance their model capabilities, making this a mainstream architecture. The Model Context Protocol (MCP), as an open standard, defines a standardized communication method between AI models and external tools. In enterprise deployment scenarios, the MCP server typically needs to be exposed to the public internet. However, the existing MCP protocol only defines a JSON-RPC 2.0 message exchange specification and does not provide any standardized authentication mechanism, making it impossible for the server to perform unified and effective identity verification for call requests. Summary of the Invention

[0003] In view of the above problems, this application provides an MCP tool invocation method and system, which can solve the problem that the lack of a unified authentication mechanism in the prior art leads to the server being unable to verify the identity of the invocation request.

[0004] Firstly, this application provides an MCP tool invocation method, which is applied to an MCP tool invocation system. The MCP tool invocation system includes a client and a server, wherein the server utilizes an optimized Spring AI. When the client initiates an MCP tool call, it sends a target call request to the server. The server generates an internal context object based on the received target call request; The server performs dual-mode authentication on the internal context object to obtain a first authentication result; wherein, the dual-mode authentication includes interface key authentication and encryption token authentication. The server generates a target context object based on the first verification result and the internal context object; The server performs security verification on the target context object through the aspect execution chain to obtain a second verification result; When the server determines that the target context object has passed the security verification based on the second verification result, it calls the corresponding business tools and executes the corresponding business methods based on the target context object.

[0005] In the above technical solution, the method can build a security verification process based on the optimized SpringAI, and combine dual-mode authentication and aspect chain security checks to effectively ensure the security and legitimacy of MCP tool calls without intruding on the original business code. At the same time, it can achieve reliable transmission of call identity and permission control, and improve the stability and controllability of the overall AI tool call process.

[0006] In some implementations, when the client initiates an MCP tool call, it sends a target call request to the server, including: When the client initiates an MCP tool call, it obtains the caller's identity information and the initial call request. The client injects the caller identity information into the reactive context; wherein, the reactive context is set by the reactive context holder before the MCP tool is invoked; The client extracts the caller's identity information from the reactive context through a security filter; The client injects the caller's identity information into the request header of the initial call request through the security filter to obtain the target call request; The client sends the target call request to the server.

[0007] In the above technical solution, the method can achieve secure and seamless transmission of the caller's identity based on the context passing mechanism of reactive programming, thereby ensuring that identity information is not lost in asynchronous call scenarios while achieving zero-intrusion transformation.

[0008] In some implementations, the client injects the caller identity information into the request header of the initial call request through the security filter to obtain the target call request, including: The client obtains the user identifier in plaintext based on the caller's identity information; The client performs symmetric encryption on the user identifier to obtain an encryption token. The client injects the user identifier and the encryption token into the request header of the initial call request to obtain the target call request.

[0009] In the above technical solution, the method can effectively improve the security of identity transmission, prevent information impersonation and tampering, and thus provide secure and reliable verification data for dual-mode identity verification on the server side.

[0010] In some implementations, the server generates an internal context object based on the received target call request, including: The server extracts tool invocation information from the received target invocation request using a custom context extractor. The server generates an internal context object based on the tool call information; The custom context extractor is an optimized Spring AI class that is pre-created and injected into the TransportProvider during its construction. The tool invocation information includes at least an interface key, a user identifier in plaintext, an encryption token, and auxiliary information; the auxiliary information includes at least a client address and request language preference data.

[0011] In the above technical solution, the method can query the cache service for the interface key through the server.

[0012] In some implementations, the server performs dual-mode authentication on the internal context object to obtain a first authentication result, including: The server verifies the validity of the interface key by querying the cache service and obtains the interface key verification result; If the server determines that the interface key is valid based on the interface key verification result, it decrypts the encryption token to obtain the decrypted identity identifier. The server performs a consistency verification on the user identifier based on the decrypted identity identifier, and obtains a first verification result; Wherein, when the decrypted identity identifier matches the user identifier, the first verification result is that the user identifier is valid; When the decryption identity identifier does not match the user identifier, the first verification result is that the user identifier is invalid.

[0013] In the above technical solution, the method can quickly verify the interface key through caching and combine it with the consistency verification of the encrypted token to achieve efficient and reliable dual-mode authentication, thereby effectively preventing unauthorized calls and identity spoofing.

[0014] In some implementations, the server generates a target context object based on the first verification result and the internal context object, including: When the first verification result is that the user identifier is invalid, the server adjusts the value of the user identifier in the internal context object to an empty value to obtain the target context object; When the first verification result indicates that the user identifier is valid, the internal context object is determined as the target context object.

[0015] In the above technical solution, the method can automatically clear sensitive identity information when verification fails, effectively isolating illegal requests; at the same time, it can also ensure the integrity and availability of the context of legitimate requests, improving the overall call security.

[0016] In some implementations, the server performs security verification on the target context object through aspect-oriented execution chains to obtain a second verification result, including: The server obtains caller information through the audit log aspect in the aspect execution chain; and generates and stores audit logs based on the caller information. The server obtains the required parameters for the calling tool based on the target call request; The server verifies the required parameters through the parameter validation aspect in the aspect execution chain to obtain the parameter validation result. When the server determines that the required parameter has passed the validation based on the parameter validation result, it determines the calling mode based on the target context object. The server performs permission verification through the permission verification aspect in the aspect execution chain and the invocation mode to obtain a second verification result. Wherein, when the calling mode is an internal call, the second verification result is verification passed; When the invocation mode is an external invocation and the permission service quota corresponding to the target context object meets the quota deduction requirement, the second verification result is verification passed; When the invocation mode is an external invocation and the permission service quota corresponding to the target context object does not meet the quota deduction requirement, the second verification result is verification failure.

[0017] In the above technical solution, the method can achieve full-link security control through audit logs, parameter verification and hierarchical permission verification; at the same time, it can also perform quota control by distinguishing between internal and external call modes, so as to achieve reasonable resource allocation while ensuring call compliance.

[0018] In some implementations, the server determines the invocation pattern based on the target context object, including: When the server detects that the user identifier in the target context object is not empty and the interface key in the target context object belongs to the preset whitelist, it determines that the calling mode is an internal call. When the server detects that the user identifier in the target context object is empty, or the interface key in the target context object does not belong to the preset whitelist, it determines that the calling mode is an external call.

[0019] In the above technical solution, the method can accurately distinguish between internal and external call modes based on user identifiers and key whitelists, thereby providing a reliable basis for subsequent differentiated permissions and quota control.

[0020] In some implementations, the server invokes the corresponding business tools and executes the corresponding business methods based on the target context object, including: The server uses the identity injection aspect in the aspect execution chain to convert the user identifier and interface key in the target context object into a user object that the business system can recognize. The server injects the user object into a thread-local variable; The server invokes the corresponding business tools and executes the corresponding business methods based on the thread-local variables.

[0021] In the above technical solution, the method can achieve standardized conversion and thread-level secure transmission of verified identity information, thereby ensuring that the identity of business calls is trustworthy, the process is stable, and execution is non-intrusive.

[0022] In some embodiments, the method further includes: When the server generates an exception message after the second verification result is a verification failure, or when it detects an exception message during the process of calling the corresponding business tool and executing the corresponding business method, it transforms the exception message into a protocol error object carrying a business status code through the aspect execution chain. The server uses a reactive programming framework to transform the protocol error object into a reactive error signal and propagate it. After the server detects the reactive error signal at the SDK session layer, it extracts the error information encapsulated in the reactive error signal. The server performs standardized processing on the error information to obtain a structured business status code; and sends an error response message including the structured business status code to the client.

[0023] In the above technical solution, the method can uniformly encapsulate and standardize the processing of system exceptions, and rely on the reactive programming framework to transmit exception information in an orderly manner, and finally return standardized and unified structured business status codes to the client, thereby effectively improving the system's fault tolerance and the standardization of interface interaction.

[0024] In some embodiments, the method further includes: After receiving the error response information, the client obtains the structured service status code based on the error response information; The client determines the type of service exception based on the structured service status code; The client outputs corresponding error message information based on the type of business exception.

[0025] In the above technical solution, the method can quickly identify the type of exception based on standardized business status codes and output accurate and easy-to-understand error messages, thereby improving the client interaction experience and the efficiency of problem location.

[0026] Secondly, this application provides an MCP tool invocation system, which includes a client and a server, wherein... The client is used to send a target call request to the server when initiating an MCP tool call; The server is used to generate an internal context object based on the received target call request; The server is also used to perform internal and external dual-mode authentication on the internal context object to obtain a first authentication result; wherein, the internal and external dual-mode authentication includes interface key authentication and encryption token authentication; The server is further configured to generate a target context object based on the first verification result and the internal context object; The server is also used to perform security verification on the target context object through the aspect execution chain to obtain a second verification result; The server is also used to call the corresponding business tools and execute the corresponding business methods based on the target context object when it is determined from the second verification result that the target context object has passed the security verification.

[0027] In the above technical solution, the system can build a security verification process based on the optimized SpringAI, and combine dual-mode authentication and aspect chain security checks to effectively ensure the security and legitimacy of MCP tool calls without intruding on the original business code. At the same time, it can achieve reliable transmission of call identity and permission control, and improve the stability and controllability of the overall AI tool call process.

[0028] The beneficial effects of this application are as follows: It enables transparent identity propagation through reactive context propagation without modifying the Spring AI source code; it also fixes Spring AI's context injection defects and ensures seamless information transmission across the entire chain, achieving end-to-end security enhancement for public network MCP services; furthermore, it enables differentiated permission and quota management for internal and external calls through dual-mode authentication and multi-layered AOP aspect interception, ensuring that security policies do not intrude on business logic; finally, it solves the Spring AI exception swallowing problem by constructing a standardized exception and business status code conversion mechanism, achieving seamless integration of business status codes and the MCP protocol. In summary, this application can significantly improve the overall security, stability, and usability of public network MCP services. Attached Figure Description

[0029] To more clearly illustrate the technical solutions of the embodiments of this application, the accompanying drawings used in the embodiments of this application will be briefly introduced below. It should be understood that the following drawings only show some embodiments of this application and should not be regarded as a limitation of the scope. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort.

[0030] Figure 1 This is a flowchart illustrating the MCP tool invocation method in some embodiments of this application; Figure 2 This is a schematic diagram of the structure of the MCP tool calling system in some embodiments of this application; Figure 3 This is a schematic diagram of the structure of an electronic device in some embodiments of this application. Detailed Implementation

[0031] The embodiments of the technical solution of this application will now be described in detail with reference to the accompanying drawings. These embodiments are only used to more clearly illustrate the technical solution of this application and are therefore merely examples, and should not be used to limit the scope of protection of this application.

[0032] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this application pertains; the terminology used herein is for the purpose of describing particular embodiments only and is not intended to limit the application; the terms “comprising” and “having”, and any variations thereof, in the specification, claims, and foregoing description of the drawings are intended to cover non-exclusive inclusion.

[0033] In the description of the embodiments of this application, technical terms such as "first" and "second" are used only to distinguish different objects and should not be construed as indicating or implying relative importance or implicitly specifying the number, specific order, or primary and secondary relationship of the indicated technical features. In the description of the embodiments of this application, "multiple" means two or more (including two), similarly, "multiple sets" refers to two or more sets (including two sets), and "multiple pieces" refers to two or more pieces (including two pieces) unless otherwise explicitly defined.

[0034] In this document, the term "embodiment" means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of this application. The appearance of this phrase in various places throughout the specification does not necessarily refer to the same embodiment, nor is it a separate or alternative embodiment mutually exclusive with other embodiments. It will be explicitly and implicitly understood by those skilled in the art that the embodiments described herein can be combined with other embodiments.

[0035] In the description of the embodiments in this application, the term "and / or" is merely a description of the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A existing alone, A and B existing simultaneously, and B existing alone. Additionally, the character " / " in this document generally indicates that the preceding and following related objects have an "or" relationship.

[0036] This application addresses the issues of lack of security verification mechanisms, unreliable identity transmission, and non-standard exception handling in MCP services under public network environments by proposing a new method for calling MCP tools.

[0037] This method enables transparent transmission of call identity through reactive context without modifying the underlying framework source code; it uses a dual authentication method on the server side to identify the legitimacy of the call; it completes full-process security control of logs, parameters, permissions, etc. through a layered interception mechanism; and it establishes a unified exception and status code handling system so that business execution results and error information can be returned to the caller in accordance with standard protocols.

[0038] Based on this, the method can achieve secure, controllable, and standardized interaction when calling public network MCP tools.

[0039] like Figure 1 As shown, some embodiments of this application provide an MCP tool invocation method. This MCP tool invocation method is applied to an MCP tool invocation system, which includes a client and a server. The server uses an optimized Spring AI (Spring Artificial Intelligence Framework). S100: When the client initiates an MCP tool call, it sends the target call request to the server.

[0040] In this embodiment, the client initiates an MCP (Model Context Protocol) tool call through the AI ​​Agent.

[0041] In this embodiment, the client completes the extraction and secure encapsulation of identity information during the call initiation phase, so as to send a target call request carrying identity credentials to the server later.

[0042] S200: The server generates an internal context object based on the received target call request.

[0043] In this embodiment, the server extracts identity and security-related information from the target call request and encapsulates it into an internal context object.

[0044] S300: The server performs dual-mode authentication on the internal context object to obtain the first authentication result; the dual-mode authentication includes interface key authentication and encryption token authentication.

[0045] In this embodiment, the server sequentially performs interface key validity verification and encryption token consistency verification to form a dual-mode authentication result.

[0046] S400: The server generates the target context object based on the first verification result and the internal context object.

[0047] In this embodiment, the server adaptively adjusts the internal context based on the authentication result to form a target context object that can be used for business calls.

[0048] S500: The server performs security verification on the target context object through the aspect execution chain and obtains the second verification result.

[0049] In this embodiment, the server completes the full-link security verification of auditing, parameters, permissions and identity in sequence through multiple aspects (i.e., multiple AOP aspects, AOP stands for aspect-oriented programming).

[0050] S600: When the server determines that the target context object has passed the security verification based on the second verification result, it calls the corresponding business tools and executes the corresponding business methods based on the target context object.

[0051] In this embodiment, after all security checks pass, the server completes identity injection and executes the actual business tool logic.

[0052] In the above embodiments, the method can build a security verification process based on the optimized SpringAI, and combine dual-mode authentication and aspect chain security checks to effectively ensure the security and legitimacy of MCP tool calls without intruding on the original business code. At the same time, it can achieve reliable transmission of call identity and permission control, and improve the stability and controllability of the overall AI tool call process.

[0053] In some embodiments, after step S500, the method may further include: S700: When the server generates an exception message after the second verification result is that the verification failed, or when an exception message is detected during the process of calling the corresponding business tool and executing the corresponding business method, the exception message is converted into a protocol error object carrying a business status code through the aspect execution chain.

[0054] In this embodiment, the method uses AOP aspects to uniformly convert various exceptions into McpError (protocol error object) carrying business status codes and internationalization information, while using fallback logic to prevent the leakage of internal exception information.

[0055] In this embodiment, the business code only needs to throw a semantically clear business exception, which is then converted into a protocol error object carrying a status code and internationalized messages by the AOP aspect.

[0056] In this embodiment, the bottom layer ensures that unknown anomalies do not leak internal information, and the final serialization into a standard protocol format is performed by the SDK session layer.

[0057] In this embodiment, the entire conversion process described above is transparent to business developers.

[0058] The S800 server uses a reactive programming framework to transform protocol error objects into reactive error signals and propagate them.

[0059] In this embodiment, the method replaces the default converter of SpringAI SDK (SpringAI Software Development Kit) with a custom configuration class, and uses Mono.fromCallable (a reactive programming call wrapper method) to wrap the tool call without using try-catch (an exception handling statement) to make McpError (Model Context Protocol Error) propagate as ReactorError (Reactor Error) signal, ensuring that it can be caught normally downstream.

[0060] In this embodiment, the custom configuration class completely replaces the default StatelessToolCallbackConverterAutoConfiguration configuration class of the SpringAI SDK (SpringAI Software Development Kit), and avoids Bean (component instance) conflicts by excluding the original configuration class in the application configuration.

[0061] The custom configuration reuses the `@Conditional` annotation, ensuring activation only in Stateless transport mode and asynchronous types (the activation condition is exactly the same as the original configuration). Simultaneously, the multi-source aggregation logic for tool callbacks remains unchanged, achieving the effect of modifying only the wrapper method for tool calls.

[0062] After the S900 server detects a reactive error signal at the SDK session layer, it extracts the error information encapsulated in the reactive error signal.

[0063] In this embodiment, McpServerSession (Model Context Protocol server session) captures reactive error signals through onErrorResume (Reactive Error Recovery Method), determines whether it is an McpError (Model Context Protocol Error) instance, and extracts the encapsulated JSON-RPC (JSON Remote Procedure Call) error information; otherwise, it uses the default internal error information.

[0064] S1000: The server standardizes the error information to obtain a structured business status code; and sends an error response message including the structured business status code to the client.

[0065] In this embodiment, the server serializes the error information into the standard JSON-RPC error response format and returns structured error information containing business status codes and internationalization descriptions.

[0066] In this embodiment, the SDK default implementation uses try-catch to wrap toolCallback.call() calls, which will convert all exceptions into CallToolResult text messages and propagate them with Mono's next signal, causing the onErrorResume logic in McpServerSession to fail to trigger. By removing try-catch in this solution, Mono.fromCallable automatically converts McpError into a Reactor error signal, enabling the session layer to capture exceptions correctly and construct a standard JSON-RPC error response to return to the client.

[0067] S1100: After receiving the error response information, the client obtains the structured business status code based on the error response information.

[0068] In this embodiment, the client parses the corresponding business status code from the returned JSON-RPC error response.

[0069] S1200: The client determines the type of business exception based on the structured business status code.

[0070] In this embodiment, the client determines different exception types based on the status code area, such as insufficient allocation quota, invalid parameters, insufficient permissions, and sensitive content.

[0071] S1300: The client outputs corresponding error message information according to the type of business exception.

[0072] In this embodiment, the client provides refined prompts such as recharge prompts, parameter correction prompts, and content adjustment prompts according to the type of anomaly.

[0073] In the above embodiments, the method can uniformly encapsulate and standardize the processing of system anomalies, and rely on the reactive programming framework to transmit anomaly information in an orderly manner, and finally return standardized and unified structured business status codes to the client, thereby effectively improving the system's fault tolerance and the standardization of interface interaction.

[0074] In some embodiments, step S100 may include: S110. When the client initiates an MCP tool call, it obtains the caller's identity information and the initial call request.

[0075] In this embodiment, the client initiates an MCP (Model Context Protocol) tool call on behalf of the user through an AIAgent (AI intelligent agent), and uses a custom tool callback component to extract caller identity information such as user identifier and APIKey (Application Programming Interface Key) from the tool context to form an initial call request.

[0076] In this embodiment, the component automatically enhances all MCP tool callback providers through the Spring BeanPostProcessor mechanism, thereby achieving zero-intrusion extraction of caller identity information without modifying the upper-level code.

[0077] For example, client identity pass-through is implemented using a three-level relay mechanism. The first level is the enhanced tool callback, which automatically detects and wraps all MCP tool callback providers during the container initialization phase through the Spring Bean post-processor, achieving zero-intrusive injection.

[0078] S120. The client injects the caller identity information into the reactive context; the reactive context is set by the reactive context holder before the MCP tool is invoked.

[0079] In this embodiment, the client uses a try-finally (exception handling block) mechanism to manage the lifecycle of the reactive context.

[0080] In this embodiment, the client injects identity information into the ReactorContext (Reactive Programming Context) through a reactive context holder before calling the MCP tool, and clears the context information after the call is completed, regardless of success or exception, to avoid context leakage issues.

[0081] S130. The client extracts the caller's identity information from the reactive context through a security filter.

[0082] In this embodiment, the client uses a WebClient (network request client, i.e., client) security filter as the identity information extraction component. This filter reads the injected caller identity information from the current reactive context using Mono.deferContextual (a reactive deferred context method).

[0083] In this embodiment, the security filter is automatically registered by the custom WebClient customizer, without requiring manual configuration by the developer.

[0084] For example, the second level of the three-level relay mechanism is that the security filter is automatically registered through the WebClient customizer, without requiring manual configuration by the developer.

[0085] S140. The client injects the caller's identity information into the request header of the initial call request through a security filter, thus obtaining the target call request.

[0086] In this embodiment, the security filter writes the extracted caller identity information into the HTTP request header of the initial call request, thereby completing the security enhancement processing of the original request and obtaining the target call request with identity credentials.

[0087] To effectively enhance the security of identity transmission and prevent information impersonation and tampering, step S140 may further include: S141. The client obtains the user identifier in plaintext based on the caller's identity information.

[0088] In this embodiment, the client separates the user identifier in plaintext from the extracted caller identity information for subsequent encryption processing and request header transmission.

[0089] S142. The client performs symmetric encryption on the user identifier to obtain an encryption token.

[0090] In this embodiment, the client uses a symmetric encryption algorithm to encrypt the plaintext user identifier to generate an encrypted token.

[0091] In this embodiment, the server will complete decryption and legitimacy verification by holding the same key, thereby preventing external attackers from impersonating the user and making calls simply by forging the identity header.

[0092] S143. The client injects the user identifier and encryption token into the request header of the initial call request through the security filter, and obtains the target call request.

[0093] In this embodiment, the client injects the plaintext user identifier and the encrypted token into different HTTP request header fields of the initial call request, forming a target call request carrying dual security credentials.

[0094] S150, The client sends the target call request to the server.

[0095] In this embodiment, the MCP transport layer uses a WebClient with a security header injected to send the target call request. The transport layer code does not need to be modified in any way to seamlessly complete the encryption and transmission of identity information.

[0096] For example, the third level in the three-level relay mechanism encapsulates the identity information into the HTTP request header and transmits it with the request. The core design of this three-level relay mechanism is that each level only depends on the output of the previous level, and there is no cross-level coupling between levels, making the entire identity transmission link completely transparent.

[0097] In the above embodiments, the method can achieve secure and seamless transmission of the caller's identity based on the context passing mechanism of reactive programming, thereby ensuring that identity information is not lost in asynchronous call scenarios while achieving zero-intrusion transformation.

[0098] In some embodiments, step S200 may include: S210. The server extracts tool call information from the received target call request using a custom context extractor.

[0099] In this embodiment, the server uses a custom context extractor that implements the McpTransportContextExtractor (MCP Transport Context Extractor) interface to extract tool call related information such as APIKey, user identifier, encryption token, client IP, and language preference from the HTTP request header and request parameters, and decrypts the encryption token.

[0100] S220, The server generates an internal context object based on the tool call information.

[0101] In this embodiment, the custom context extractor is injected by the optimized SpringAI through a pre-created custom auto-configuration class when constructing the TransportProvider.

[0102] In this embodiment, the tool call information includes at least auxiliary information such as APIKey, plaintext user identifier, encryption token and client IP, and request language preference.

[0103] In this embodiment, the custom auto-configuration class adapts to three transmission modes: SSE (Server-Side Push Events), StreamableHTTP (Hypertext Transfer Protocol), and Stateless. Simultaneously, the `@AutoConfiguration(before=...)` annotation (auto-configuration priority loading annotation) enables priority loading, thus correcting the defect in the original SDK (Software Development Kit) that prevents the injection of custom extractors.

[0104] For example, in actual configuration, the `@AutoConfiguration(before=...)` annotation can be used to load custom configuration classes before the original SDK configuration classes. Combined with the `@ConditionalOnMissingBean` annotation, after the custom TransportProvider Bean is registered, beans of the same type in the original configuration will automatically become invalid, thus achieving non-intrusive replacement. Furthermore, the same set of repair logic can be used for all three transport modes, ensuring that the context extractor functions correctly in any transport mode.

[0105] In this embodiment, the server encapsulates the verified tool call information into an internal context object, writes it into the reactive context using ReactorcontextWrite, then reads it from McpServerSession and injects it into McpAsyncServerExchange, and finally places it in ToolContext for normal use by AOP aspects.

[0106] In the above embodiments, the method can achieve unified extraction and standardized encapsulation of call information, and further provide a complete and accurate data foundation for subsequent verification through non-intrusive extension.

[0107] In some embodiments, step S300 may include: S310. The server verifies the validity of the APIKey by querying the cache service and obtains the interface key verification result.

[0108] In this embodiment, the caching service can be implemented using a Redis distributed memory cache to quickly verify the validity of the APIKey in the request. Specifically, the server can retrieve the APIKey from the request header and directly query Redis to determine if the key exists, has not expired, and has not been blacklisted, and use the verification result as the interface key verification result.

[0109] In this embodiment, the server intercepts MCP requests through a custom web filter (network filter) at the gateway layer, and verifies the validity of the APIKey in the request through the caching service. If the APIKey is invalid or does not exist, it directly returns 401 (unauthorized status code) and terminates the request process.

[0110] In this embodiment, gateway verification can be implemented through a custom web filter to intercept all MCP endpoint requests and verify the validity of authentication credentials.

[0111] S320. If the server determines that the APIKey is valid based on the interface key verification result, it decrypts the encrypted token to obtain the decrypted identity identifier.

[0112] In this embodiment, after the APIKey is verified, the server uses the same symmetric key as the client to decrypt the encrypted token and obtain the decrypted identity identifier.

[0113] S330. The server performs consistency verification on the user identifier based on the decrypted identity identifier and obtains the first verification result.

[0114] In this embodiment, if the decrypted identity identifier and the plaintext of the user identifier are consistent, the first verification result is that the user identifier is valid; if they are inconsistent, the first verification result is that the user identifier is invalid.

[0115] In this embodiment, when the decryption fails, the token is invalid, or the comparison does not match, the server does not directly reject the request. Instead, it adopts a security degradation strategy to mark the identity as invalid and switches to external call mode.

[0116] For example, the cryptographic token verification logic is integrated into the context extractor to achieve a unified process of "extraction, verification, and downgrading".

[0117] In the above embodiments, the method can quickly verify the APIKey through caching and combine it with the consistency verification of the encrypted token to achieve efficient and reliable dual-mode authentication, thereby effectively preventing unauthorized calls and identity spoofing.

[0118] In some embodiments, step S400 may include: S410. When the first verification result is that the user identifier is invalid, the server adjusts the value of the user identifier in the internal context object to an empty value to obtain the target context object.

[0119] In this embodiment, when the encryption token verification fails, is missing, or decryption is abnormal, the server sets the user identifier in the internal context object to empty, so that the current request is downgraded to an external call, and the subsequent authentication module deducts the quota normally according to the external call rules.

[0120] S420. When the first verification result is that the user identifier is valid, the internal context object is determined as the target context object.

[0121] In this embodiment, after the user's identity verification is successful, the server retains the complete identity information in the internal context object and directly uses it as the target context object to enter the subsequent AOP aspect verification process.

[0122] In the above embodiments, the method can automatically clear sensitive identity information when verification fails, effectively isolating illegal requests; at the same time, it can also ensure the integrity and availability of the context of legitimate requests, improving the overall call security.

[0123] In some embodiments, step S500 may include: S510. The server obtains caller information through the audit log aspect in the aspect execution chain; and generates and stores audit logs based on the caller information.

[0124] In this embodiment, the audit log aspect is the outermost aspect with the highest priority. It prioritizes obtaining caller information such as APIKey, user ID, client IP, tool name, and input parameters, and records the call time, execution result, and exception information to ensure the integrity of the audit log.

[0125] S520: The server obtains the required parameters for the calling tool based on the target call request.

[0126] In this embodiment, the server extracts the required parameters for validity verification from the target call request according to the parameter annotation rules corresponding to the tool method.

[0127] S530: The server validates the required parameters through the parameter validation aspect in the aspect execution chain and obtains the parameter validation result.

[0128] In this embodiment, the parameter validation aspect verifies whether the required parameters are complete and valid according to the annotation rules. If the validation fails, an McpError (MCP protocol error object) is thrown directly. Based on this, the method can capture MCP protocol error objects that are converted to carry internationalization information due to business anomalies.

[0129] S540. When the server determines that the required parameters have passed the validation based on the parameter validation results, it determines the calling mode based on the target context object.

[0130] In this embodiment, after the required parameters pass the validation, the server determines whether the current request is an internal or external call based on the identity information in the target context object.

[0131] To accurately distinguish between internal and external call patterns, step S540 may also include: S541. When the server detects that the user identifier in the target context object is not empty and the APIKey in the target context object belongs to the preset whitelist, it determines that the calling mode is an internal call.

[0132] In this embodiment, the server only determines a request as a trusted internal system call when both the user identifier and the APIKey belong to the internal whitelist are met.

[0133] S542. When the server detects that the user identifier in the target context object is empty, or the APIKey in the target context object does not belong to the preset whitelist, it determines that the calling mode is an external call.

[0134] In this embodiment, when either the user identifier is invalid or the APIKey is not on the internal whitelist, the server will determine the request as an external call and perform quota control.

[0135] S550: The server performs permission verification through the permission verification aspect and call pattern in the aspect execution chain, and obtains the second verification result.

[0136] In this embodiment, if the calling mode is an internal call, the second verification result is directly verified as successful; if it is an external call and the quota is sufficient, the verification is successful; if it is an external call and the quota is insufficient, the verification fails.

[0137] In this embodiment, when the quota is insufficient, the server returns an internationalization error message through the policy pattern.

[0138] In this embodiment, if the permission verification aspect detects a business anomaly after deducting the quota, it will perform quota rollback through an asynchronous message queue to ensure the eventual consistency of quota data in a distributed scenario.

[0139] For example, the four-layer AOP aspects define the execution order through priority annotations, achieving strict nested execution from the outside in, with each aspect having a single responsibility. Specifically, the audit logging layer captures end-to-end information, the parameter validation layer intercepts illegal parameters, the permission verification layer implements internal and external dual-mode traffic splitting and quota management, and the identity injection layer parses and injects user context. Based on this, tool developers only need to add specific annotations to the utility class to automatically obtain all four layers of security capabilities without writing any security-related code.

[0140] In the above embodiments, the method can achieve full-link security control through audit logs, parameter verification and permission hierarchical verification; at the same time, it can also perform quota control by distinguishing between internal and external call modes, so as to achieve reasonable resource allocation while ensuring call compliance.

[0141] In some embodiments, step S600 may include: S610: The server uses the identity injection aspect in the aspect execution chain to convert the user identifier and APIKey in the target context object into a user object that the business system can recognize.

[0142] In this embodiment, the identity injection aspect is the innermost aspect with the lowest priority. It parses the user identifier and API key from the target context object and converts them into a user object that can be recognized by the business system through the query service.

[0143] In this embodiment, the server can first extract the user identifier and API key from the context through the identity injection aspect, then call the internal user service to query the corresponding user data based on this information, and convert the queried user data into a user entity object that conforms to the business system, thereby achieving secure identity injection.

[0144] S620, The server injects the user object into the thread-local variable.

[0145] In this embodiment, the server injects the converted user object into ThreadLocal (thread-local variable), making it easy for business methods to directly obtain and use it, avoiding the need to pass identity parameters layer by layer.

[0146] S630: The server calls the corresponding business tools and executes the corresponding business methods based on the thread-local variables.

[0147] In this embodiment, the business method obtains the user's identity from ThreadLocal (thread-local variable) and executes the corresponding logic.

[0148] In this embodiment, after the business method is executed, the custom tool callback component removes the ThreadLocal data through the finally block to avoid thread-local variable leakage.

[0149] In the above embodiments, the method can achieve standardized conversion and thread-level secure transmission of verified identity information, thereby ensuring that the identity of business calls is trustworthy, the process is stable, and execution is non-intrusive.

[0150] For example, the first stage of this application is the WebClient-side identity pass-through stage, which includes: S1. The Agent initiates an MCP tool call and extracts the caller's identity information (userld, apikey) from the tool context.

[0151] S2. Inject identity information into the Reactor reactive context and use the context propagation mechanism of reactive programming to pass through the identity.

[0152] The S3 and WebClient filters extract identity information from the reactive context, encrypt the identity identifier to generate a token, and inject the identity identifier and encrypted token into the HTTP request header.

[0153] S4 and WebClient send requests transparently, and the MCP transport layer is completely unaware of the identity injection process.

[0154] The second stage of this application is the transport layer context extraction stage, which includes: S5, Server-side transport layer context extraction; a custom ContextExtractor extracts APIKey, identity identifier, encryption token, etc. from HTTP requests; and constructs the transport layer context for use in subsequent steps.

[0155] The third stage of this application is the internal and external dual-mode authentication stage, which includes: S6. Gateway Layer API Key Verification: Verify whether the API Key carried in the request is valid; if invalid, reject the request and end this process; if valid, proceed to S7.

[0156] S7. Encryption Token Verification and Security Degradation: Decrypt the token and compare it with the identity identifier; if the token verification passes, retain the identity identifier (internal call mode); if the token verification fails, degrade the security (downgrade to external call) and clear the identity identifier.

[0157] The fourth stage of this application is the ordered AOP aspect interception stage, which includes: S8, Audit Log Aspect (outermost layer of @Order): Records caller, tool name, parameters, time taken, and result.

[0158] S9, Parameter Validation and Exception Conversion Aspect (@Order Second Layer): Required parameter for the validation tool. If the parameter is valid, execute S10; if the parameter is invalid, convert it to a protocol error object (carrying a business status code) and execute S13.

[0159] S10, Permission Verification Aspect (@Order third layer): Dual-mode permission determination, checks if the identity identifier is not empty and if the API Key is in the whitelist. If yes, it is determined to be an internal call and allowed without deduction; if no, it is determined to be an external call and the quota is deducted (at this time, it is also necessary to check if the quota is sufficient. If it is sufficient, it continues to execute sequentially; if it is insufficient, it throws a protocol error (quota exhausted) and executes S13).

[0160] S11, Identity Injection Aspect (innermost @Order): Parses the identity identifier as a user object and injects ThreadLocal.

[0161] S12. Execute the business utility method and determine whether the execution was successful. If successful, return the result normally and end this process; if the business is abnormal, obtain the protocol error object and asynchronously roll back the deducted quota, then execute S13.

[0162] The fifth stage of this application is the business status code protocol integration stage, which includes: S13. Exceptions are propagated as Reactor error signals; custom configuration removes the SDK's default exception swallowing logic (try-catch); ensures that business status codes are not intercepted and discarded by the SDK.

[0163] S14, SDK session layer captures protocol error objects; extracts business status codes and messages; constructs standard JSON-RPC error response.

[0164] S15. Return to the client with an error response carrying a structured business status code.

[0165] like Figure 2 As shown, some embodiments of this application provide a schematic diagram of the structure of an MCP tool invocation system. It should be understood that this system is related to... Figure 1 The method executed in the middle corresponds to the steps involved in the aforementioned method. The specific functions and effects of the system can be found in the description above. To avoid repetition, detailed descriptions are omitted here.

[0166] The MCP tool calling system includes a client 10 and a server 20, wherein... Client 10 is used to send the target call request to server 20 when initiating an MCP tool call; Server 20 is used to generate an internal context object based on the received target call request; Server 20 is also used to perform dual-mode authentication on the internal context object to obtain the first authentication result; wherein, dual-mode authentication includes interface key authentication and encryption token authentication; Server 20 is also used to generate a target context object based on the first verification result and the internal context object; Server 20 is also used to perform security verification on the target context object through the aspect execution chain to obtain a second verification result; The server 20 is also used to call the corresponding business tools and execute the corresponding business methods based on the target context object when it is determined from the second verification result that the target context object has passed the security verification.

[0167] In some embodiments, the MCP tool can call the client 10 and server 20 in the system to execute the method steps in this embodiment, which will not be described in detail here.

[0168] like Figure 3As shown, this application provides an electronic device 30, which includes a processor 31 and a memory 32. The processor 31 and the memory 32 are interconnected and communicate with each other through a communication bus 33 and / or other forms of connection mechanism (not shown). The memory 32 stores a computer program that can be executed by the processor 31. When the computing device is running, the processor 31 executes the computer program to perform the method steps in the client 10 or server 20 in this embodiment.

[0169] This application provides a computer-readable storage medium storing a computer program, which, when executed by a processor, performs the method steps in the client 10 or server 20 of this embodiment.

[0170] The computer-readable storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as Static Random Access Memory (SRAM), Electrically Erasable Programmable Read-Only Memory (EEPROM), Erasable Programmable Read Only Memory (EPROM), Programmable Red-Only Memory (PROM), Read-Only Memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk.

[0171] This application provides a computer program product, which includes a computer program that, when run by a processor, executes the method in any of the aforementioned optional implementations.

[0172] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of this application, and not to limit them. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features therein. These modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of this application, and they should all be covered within the scope of the claims and specification of this application. In particular, as long as there is no conflict, the various technical features mentioned in the embodiments can be combined in any way. This application is not limited to the specific embodiments disclosed herein, but includes all technical solutions falling within the scope of the claims.

Claims

1. A method for calling an MCP tool, characterized in that, The MCP tool invocation method is applied to the MCP tool invocation system, which includes a client and a server. The server uses an optimized Spring AI. When the client initiates an MCP tool call, it sends a target call request to the server. The server generates an internal context object based on the received target call request; The server performs dual-mode authentication on the internal context object to obtain a first authentication result; wherein, the dual-mode authentication includes interface key authentication and encryption token authentication. The server generates a target context object based on the first verification result and the internal context object; The server performs security verification on the target context object through the aspect execution chain to obtain a second verification result; When the server determines that the target context object has passed the security verification based on the second verification result, it calls the corresponding business tools and executes the corresponding business methods based on the target context object.

2. The MCP tool invocation method according to claim 1, characterized in that, When the client initiates an MCP tool call, it sends a target call request to the server, including: When the client initiates an MCP tool call, it obtains the caller's identity information and the initial call request. The client injects the caller identity information into the reactive context; wherein, the reactive context is set by the reactive context holder before the MCP tool is invoked; The client extracts the caller's identity information from the reactive context through a security filter; The client injects the caller's identity information into the request header of the initial call request through the security filter to obtain the target call request; The client sends the target call request to the server.

3. The MCP tool invocation method according to claim 2, characterized in that, The client injects the caller's identity information into the request header of the initial call request through the security filter to obtain the target call request, including: The client obtains the user identifier in plaintext based on the caller's identity information; The client performs symmetric encryption on the user identifier to obtain an encryption token. The client injects the user identifier and the encryption token into the request header of the initial call request through the security filter, thereby obtaining the target call request.

4. The MCP tool invocation method according to claim 1, characterized in that, The server generates an internal context object based on the received target call request, including: The server extracts tool invocation information from the received target invocation request using a custom context extractor. The server generates an internal context object based on the tool call information; The custom context extractor is an optimized Spring AI class that is pre-created and injected into the TransportProvider during its construction. The tool invocation information includes at least an interface key, a user identifier in plaintext, an encryption token, and auxiliary information; the auxiliary information includes at least a client address and request language preference data.

5. The MCP tool invocation method according to claim 4, characterized in that, The server performs dual-mode authentication on the internal context object to obtain a first authentication result, including: The server verifies the validity of the interface key by querying the cache service and obtains the interface key verification result; If the server determines that the interface key is valid based on the interface key verification result, it decrypts the encryption token to obtain the decrypted identity identifier. The server performs a consistency verification on the user identifier based on the decrypted identity identifier, and obtains a first verification result; Wherein, when the decrypted identity identifier matches the user identifier, the first verification result is that the user identifier is valid; When the decryption identity identifier does not match the user identifier, the first verification result is that the user identifier is invalid.

6. The MCP tool invocation method according to claim 1, characterized in that, The server generates a target context object based on the first verification result and the internal context object, including: When the first verification result is that the user identifier is invalid, the server adjusts the value of the user identifier in the internal context object to an empty value to obtain the target context object; When the first verification result indicates that the user identifier is valid, the internal context object is determined as the target context object.

7. The MCP tool invocation method according to claim 1, characterized in that, The server performs security verification on the target context object through the aspect execution chain to obtain a second verification result, including: The server obtains caller information through the audit log aspect in the aspect execution chain; and generates and stores audit logs based on the caller information. The server obtains the required parameters for the calling tool based on the target call request; The server verifies the required parameters through the parameter validation aspect in the aspect execution chain to obtain the parameter validation result. When the server determines that the required parameter has passed the validation based on the parameter validation result, it determines the calling mode based on the target context object. The server performs permission verification through the permission verification aspect in the aspect execution chain and the invocation mode to obtain a second verification result. Wherein, when the calling mode is an internal call, the second verification result is verification passed; When the invocation mode is an external invocation and the permission service quota corresponding to the target context object meets the quota deduction requirement, the second verification result is verification passed; When the invocation mode is an external invocation and the permission service quota corresponding to the target context object does not meet the quota deduction requirement, the second verification result is verification failure.

8. The MCP tool invocation method according to claim 7, characterized in that, The server determines the invocation mode based on the target context object, including: When the server detects that the user identifier in the target context object is not empty and the interface key in the target context object belongs to the preset whitelist, it determines that the calling mode is an internal call. When the server detects that the user identifier in the target context object is empty, or the interface key in the target context object does not belong to the preset whitelist, it determines that the calling mode is an external call.

9. The MCP tool invocation method according to claim 1, characterized in that, The server invokes the corresponding business tools and executes the corresponding business methods based on the target context object, including: The server uses the identity injection aspect in the aspect execution chain to convert the user identifier and interface key in the target context object into a user object that the business system can recognize. The server injects the user object into a thread-local variable; The server invokes the corresponding business tools and executes the corresponding business methods based on the thread-local variables.

10. The MCP tool invocation method according to claim 1, characterized in that, The method further includes: When the server generates an exception message after the second verification result is a verification failure, or when it detects an exception message during the process of calling the corresponding business tool and executing the corresponding business method, it transforms the exception message into a protocol error object carrying a business status code through the aspect execution chain. The server uses a reactive programming framework to transform the protocol error object into a reactive error signal and propagate it. After the server detects the reactive error signal at the SDK session layer, it extracts the error information encapsulated in the reactive error signal. The server performs standardized processing on the error information to obtain a structured business status code; and sends an error response message including the structured business status code to the client.

11. The MCP tool invocation method according to claim 10, characterized in that, The method further includes: After receiving the error response information, the client obtains the structured service status code based on the error response information; The client determines the type of service exception based on the structured service status code; The client outputs corresponding error message information based on the type of business exception.

12. An MCP tool invocation system, characterized in that, The MCP tool invocation system includes a client and a server, wherein, The client is used to send a target call request to the server when initiating an MCP tool call; The server is used to generate an internal context object based on the received target call request; The server is also used to perform internal and external dual-mode authentication on the internal context object to obtain a first authentication result; wherein, the internal and external dual-mode authentication includes interface key authentication and encryption token authentication; The server is further configured to generate a target context object based on the first verification result and the internal context object; The server is also used to perform security verification on the target context object through the aspect execution chain to obtain a second verification result; The server is also used to call the corresponding business tools and execute the corresponding business methods based on the target context object when it is determined from the second verification result that the target context object has passed the security verification.