An agent-oriented data source calling method and related device
By pre-validating data source call requests from intelligent agents and generating structured error responses, combined with aspect-oriented programming and thread-local variable management, the problem of error localization when intelligent agents call data sources is solved. This enables automatic correction of intelligent agents and flexibility in managing multiple data sources, reduces token consumption and server pressure, and improves the robustness of data migration.
Patent Information
- Application Number
- CN202611286101.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-24
- Publication Date
- 2026-11-20
AI Technical Summary
When the agent calls the data source, the generated SQL may have non-standard issues, which the MCP server cannot recognize, and returns the original error response. The agent has difficulty locating the cause of the error and cannot accurately correct the SQL, resulting in a large number of invalid SQL statements. In addition, there are problems such as complex database connection configuration, high dependence on manual intervention for managing multiple data sources, and large token consumption.
The system pre-validates data source call requests from intelligent agents, extracts and generates structured error responses, enabling automated correction of intelligent agents; it employs aspect-oriented programming and thread-local variables to manage dynamic routing of multiple data sources, supporting stateless characteristics; and it provides streamlined metadata and fault tolerance mechanisms to optimize the data migration process.
By effectively filtering out invalid and interfering data, the intelligent agent can accurately locate and correct errors, reduce invalid SQL, lower the pressure on the MCP server, improve the automation of database connections, reduce token consumption, and enhance the flexibility of multi-data source management and the robustness of data migration.
Smart Images

Figure CN123137984A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of intelligent agent technology, and in particular to a data source invocation method and related apparatus for intelligent agents. Background Technology
[0002] The MCP (Model Context Protocol) is an open protocol specification that can be used to standardize the interaction between intelligent agents and external data sources and tools. It can include MCP clients (intelligent agents) and MCP servers.
[0003] When an agent needs to access a data source, it sends SQL (Structured Query Language) to the MCP server. However, the SQL generated by the agent may contain non-standard elements, causing the MCP server to be unable to recognize the SQL and return a raw error response. Because the raw error response contains a large amount of invalid information such as class names and paths, the agent cannot pinpoint the cause of the SQL error. Therefore, the agent cannot accurately correct the SQL and can only rely on guesswork to repeatedly modify it, resulting in a large number of invalid SQL statements. Summary of the Invention
[0004] In view of the above problems, this application provides a data source invocation method and related apparatus for intelligent agents, so as to enable intelligent agents to obtain sufficient tool capabilities within a limited context window while minimizing token consumption. The specific solution is as follows:
[0005] The first aspect of this application provides a data source invocation method for intelligent agents, the data source invocation method for intelligent agents comprising:
[0006] In response to the data source call request sent by the intelligent agent, the data source call request is verified;
[0007] If the data source call request fails the verification, the error information is extracted, a structured error response is generated based on the error information, and the structured error response is sent to the agent so that the agent can correct the data source call request according to the structured error response and send the corrected data source call request.
[0008] If the data source call request passes the verification, the call object indicated by the data source call request is executed.
[0009] In one possible implementation, the validation of the data source call request includes:
[0010] The existence of the calling object indicated by the data source call request is verified. If the existence verification fails, the verification of the data source call request is deemed to have failed.
[0011] If the existence check is successful, then the execution statement of the data source call request is subjected to syntax check. If the syntax check fails, then the data source call request is determined to have failed the check.
[0012] If the syntax validation is successful, the data source call request is deemed to have passed validation.
[0013] In one possible implementation, the existence check of the calling object indicated by the data source call request includes:
[0014] The original form, all uppercase form, and all lowercase form of the object name of the called object are matched sequentially with the configured data source. If no match is found, it is determined that the called object indicated by the data source call request does not exist, and the existence check is deemed to have failed.
[0015] If at least one of the original form, the all-uppercase form, and the all-lowercase form matches successfully, it is determined that the calling object indicated by the data source call request exists, and the existence verification is successful.
[0016] In one possible implementation, the error message includes an error code;
[0017] The step of extracting error information and generating a structured error response based on the error information includes:
[0018] Extract the generated error codes and classify them;
[0019] Based on the classification results of the error codes, a correction suggestion is generated, an available object list is obtained, and a structured error response containing the correction suggestion and the available object list is generated.
[0020] One possible implementation also includes:
[0021] Before allocating the target thread to carry the current data source call, record the original context of the target thread;
[0022] After the current data source call is completed, the original context of the target thread is restored.
[0023] One possible implementation also includes:
[0024] If the data source call request does not contain a data source indication, the current primary data source will be used as the data source for this call. The current primary data source is either the first registered data source or another data source selected after the first registered data source is deregistered.
[0025] One possible implementation also includes:
[0026] In response to a data source configuration request sent by the intelligent agent, identify the data source configuration information contained in the data source configuration request;
[0027] Generate a data source configuration based on the data source configuration information, and store the data source configuration.
[0028] In one possible implementation, the step of verifying the data source invocation request in response to the data source invocation request sent by the agent includes:
[0029] In response to the data source call request sent by the agent based on the simplified metadata defined by the tool, the data source call request is verified. The simplified metadata is sent to the agent based on the agent's tool registration request.
[0030] One possible implementation also includes:
[0031] In response to a data migration request, data migration is performed on a configured first data source and a configured second data source. The data migration includes exporting data from the first data source, performing character-by-character streaming parsing and classifying and aggregating the exported data, and importing the classified and aggregated data into the second data source in batches.
[0032] Whenever a batch import is successful, the maximum primary key value of the second data source is updated. If the batch import fails, it is switched to a row-by-row import process. The data that failed to be imported row by row is stored and retried for a second import.
[0033] After the data migration is completed, verify whether the migrated data of the second data source is consistent with the migrated data of the first data source.
[0034] A second aspect of this application provides a computer program product including computer-readable instructions that, when executed on an electronic device, cause the electronic device to implement the agent-oriented data source invocation method described in the first aspect or any implementation thereof.
[0035] Based on the above technical solution, this application provides a data source invocation method and related apparatus for intelligent agents. This method pre-validates the data source invocation request of the intelligent agent. If the validation passes, the invocation object indicated by the data source invocation request can be directly executed. If the validation fails, valid error information is actively extracted and a standard structured error response is generated. The structured error response can effectively filter invalid interference data, allowing the intelligent agent to accurately and quickly locate the cause of the error without relying on guesswork and repeatedly modifying the data source invocation request. This effectively guides the intelligent agent to accurately correct the data source invocation request, thereby avoiding the generation of a large number of invalid data source invocation requests and further reducing the operating pressure on the MCP server. Attached Figure Description
[0036] The above and other features, advantages, and aspects of the embodiments of this disclosure will become more apparent from the accompanying drawings and the following detailed description. Throughout the drawings, the same or similar reference numerals denote the same or similar elements. It should be understood that the drawings are schematic, and the originals and elements are not necessarily drawn to scale.
[0037] Figure 1 A flowchart illustrating a data source invocation method for intelligent agents provided in an embodiment of this application;
[0038] Figure 2 This is a schematic diagram of the structure of an MCP service system provided in an embodiment of this application;
[0039] Figure 3 This is a hardware structure block diagram of an electronic device provided in an embodiment of this application. Detailed Implementation
[0040] The embodiments of this application are described below with reference to the accompanying drawings. The terminology used in the implementation section of this application is for explaining specific embodiments only and is not intended to limit the scope of this application.
[0041] As will be known to those skilled in the art, with the development of technology and the emergence of new scenarios, the technical solutions provided in the embodiments of this application are also applicable to similar technical problems.
[0042] The terms "first," "second," etc., used in the specification, claims, and accompanying drawings of this application are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such terms are interchangeable where appropriate; this is merely a way of distinguishing objects with the same attributes in the embodiments of this application. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion, so that a process, method, system, product, or apparatus that comprises a series of elements is not necessarily limited to those elements, but may include other elements not explicitly listed or inherent to those processes, methods, products, or apparatuses.
[0043] When an agent needs to access a data source, it sends SQL (Structured Query Language) to the MCP server. However, the SQL generated by the agent may contain non-standard elements, causing the MCP server to be unable to recognize the SQL and return a raw error response. Because the raw error response contains a large amount of invalid information such as class names and paths, the agent cannot pinpoint the cause of the SQL error. Therefore, the agent cannot accurately correct the SQL and can only rely on guesswork to repeatedly modify it, resulting in a large number of invalid SQL statements.
[0044] In addition, the following issues exist: how to effectively achieve fully automated configuration of agent database connections, dynamic management of multiple data sources, and thread-safe switching to adapt to the stateless characteristics of MCP tool calls and prevent context leakage between calls; under the token budget constraint of the MCP protocol, how to significantly reduce the occupation of the agent context window by the tool definition while retaining the complete tool capabilities, so that the agent can obtain sufficient tool capabilities within a limited context window while minimizing token consumption; how to achieve efficient data migration; and how to set up fault tolerance mechanisms.
[0045] To address the aforementioned problems, this application provides a method for invoking data sources for intelligent agents. The method for invoking data sources for intelligent agents according to this application will be described in detail below with reference to the accompanying drawings.
[0046] Reference Figure 1 , Figure 1 This is a flowchart illustrating a data source invocation method for intelligent agents provided in an embodiment of this application, as shown below. Figure 1 As shown in the figure, the data source invocation method for intelligent agents provided in this application embodiment may include steps S10 to S12, which are described in detail below.
[0047] S10. In response to the data source call request sent by the agent, verify the data source call request.
[0048] In this context, an intelligent agent can refer to an artificial intelligence entity possessing functions such as perceiving the environment, autonomously planning and making decisions, invoking tools to execute actions, and iteratively adjusting its behavior based on feedback results, enabling it to proactively complete various complex tasks. A data source can refer to a backend system instance that provides data storage, retrieval, and management services, such as relational databases or NoSQL databases. A data source invocation request can refer to an instruction message generated by the intelligent agent based on the tool definition in the Model Context Protocol (MCP), used to instruct the database to perform a specific operation, and may include parameters such as the target data source identifier, SQL statement, or stored procedure name.
[0049] Validation can refer to the pre-verification process of a data source call request, specifically including existence verification, syntax verification, permission verification, or business rule matching. Existence verification refers to the step of verifying whether the operation target specified in the request exists on the server side. Syntax verification refers to the step of performing compliance analysis on the lexical structure, keyword usage, and syntactic rules of the request. This embodiment adopts a hierarchical verification strategy, which prioritizes existence checks with lower computational overhead, and only initiates complex syntax parsing after confirming the object's existence. This avoids consuming significant computational resources for invalid syntax analysis when the object does not exist, significantly improving the request processing efficiency of the MCP server.
[0050] In this embodiment, the verification process of the MCP server for the data source call request can be specifically as follows: perform an existence check on the call object indicated by the data source call request. If the existence check fails, it is determined that the verification of the data source call request has failed. If the existence check succeeds, perform a syntax check on the execution statement of the data source call request. If the syntax check fails, it is determined that the verification of the data source call request has failed. If the syntax check succeeds, it is determined that the verification of the data source call request has passed.
[0051] For existence verification, the MCP server can sequentially match the original form, all-uppercase form, and all-lowercase form of the object name of the called object with the configured data source. If none of these match, it is determined that the called object indicated by the data source call request does not exist, and the existence verification fails. If at least one of the original form, all-uppercase form, and all-lowercase form matches successfully, it is determined that the called object indicated by the data source call request exists, and the existence verification succeeds. The original form can refer to the unconverted name text directly provided by the agent in the data source call request; the all-uppercase form can refer to a variant of the original name forcibly converted to all uppercase; and the all-lowercase form can refer to a variant of the original name forcibly converted to all lowercase. Matching multiple forms effectively improves the robustness and fault tolerance of existence verification and can be compatible with the different handling rules of different database management systems regarding the case sensitivity of identifiers.
[0052] For syntax validation, the MCP server can check syntax compatibility based on the database type indicated by the data source call request. For example, Oracle does not support LIMIT / OFFSET syntax (ROWNUM or FETCH FIRST is recommended), and DM recommends not using ROWNUM (LIMIT / OFFSET is recommended). Generally, it checks for unclosed quotation marks and parentheses.
[0053] Furthermore, existence checks can include table existence checks and field existence checks, while syntax checks can specifically be SQL syntax checks. These checks are performed sequentially, following the order of table existence checks, field existence checks, and SQL syntax checks. If a previous check fails, an error response is immediately returned, and subsequent checks are not performed. Specifically, table existence checks refer to the process of determining whether a target table exists in the database. Field existence checks refer to the process of determining whether a specific column (field) exists within a specified table. SQL syntax checks refer to checking whether SQL statements conform to the syntax rules of the corresponding database, including keywords, identifiers, parentheses, operators, and clause order. Specifically, the MCP server can perform table existence checks on data source call requests. If the table existence check fails, subsequent field existence checks and syntax checks will not be performed. If the table existence check passes, field existence checks will be performed on the data source call request. If the field existence check fails, subsequent SQL syntax checks will not be performed. If the field existence check passes, SQL syntax checks will be performed. If the SQL syntax check fails, the data source call request is considered to have failed; if the SQL syntax check succeeds, the data source call request is considered to have passed.
[0054] S11. If the validation of the data source call request fails, extract the error information, generate a structured error response based on the error information, and send the structured error response to the agent so that the agent can correct the data source call request according to the structured error response and send the corrected data source call request.
[0055] S12. If the data source call request passes the verification, then execute the call object indicated by the data source call request.
[0056] In this scenario, when the verification logic determines that the data source call request has a defect, the original exception thrown by the underlying database is natural language text designed for human developers and lacks a machine-parseable semantic structure. Therefore, the agent struggles to extract effective correction information from it. Consequently, the MCP server does not directly feed back the original exception thrown by the underlying database to the agent. Instead, it extracts key error information such as error codes and error types from the verification failure result and encapsulates it into a structured error response. This allows the agent to correct the data source call request based on the structured error response. This structured error response can refer to machine-parseable error data adapted to the agent's cognitive and processing characteristics. In this embodiment, the structured error response can specifically be a feedback data packet containing information such as error codes, error types, correction suggestions, and a list of available objects, conforming to agent-readable specifications. This embodiment transforms the abstract error state into concrete operational guidance, enabling the agent to automatically adjust the data source call request and retry based on a clear correction direction, without relying on human knowledge or blind guessing retries, significantly reducing invalid interaction rounds.
[0057] Specifically, the error information may include error codes. The process of generating this structured error response can be as follows: extracting the generated error codes and classifying them; generating correction suggestions based on the classification results of the error codes; obtaining a list of available objects; and generating a structured error response containing correction suggestions and a list of available objects. In this embodiment, when the MCP server is running, SqlValidator can dynamically generate a structured error response containing errorCode, errorType, message, suggestion, and availableFields based on the actual error.
[0058] Here, error codes can refer to standardized codes that identify error types. Error code classification can refer to the process of mapping technical error codes to semantic categories that the agent can understand. For example, various table missing error codes can be uniformly classified into the table missing category. Optionally, the MCP server can have a built-in error code classification mapping table, which can be used to transform abstract numerical error codes into semantically clear error types. Correction suggestions can refer to natural language prompts or structured operation instructions generated for specific error categories, guiding the agent on how to adjust the request. The list of available objects can refer to the set of database object names that are at the same level as the error object in the current context and can be legally referenced. For example, when a field name is incorrect, all available field names under the table can be listed. The list of available objects can be obtained by real-time querying of database metadata or extracting it from the schema information cached by the MCP server. Schema information can refer to the database metadata, including table structure description information such as databases, tables, fields, indexes, constraints, types, and comments. Furthermore, the MCP server can select the metadata query method according to different databases. For example, Oracle / DM can use the schema metadata query method, while MySQL can use the catalog metadata query method.
[0059] This embodiment reconstructs error information into a structured data format that the agent can understand, enabling the agent to directly read field values in the response and adjust parameters or statements for the next request, thus achieving an automated closed loop of server-side verification and client-side correction.
[0060] Once the data source call request passes validation, the MCP server can execute the call object indicated by the data source call request. The call object can refer to an executable entity such as a database table, view, stored procedure, or SQL statement pointed to by the data source call request.
[0061] Furthermore, this embodiment also sets up a dynamic routing mechanism for multiple data sources adapted to the stateless characteristics of MCP. Specifically, before allocating the target thread to carry the current data source call, the MCP server records the original context of the target thread; after the current data source call is completed, the original context of the target thread is restored.
[0062] Here, the target thread can refer to the worker thread in the MCP server's thread pool used to execute the current data source call request. The original context can refer to the data source identifier, transaction state, or other thread-local variable information bound to the target thread before processing this request. Recovery can refer to forcibly resetting the target thread's state to its original value or clearing temporary bindings after this request is processed, to ensure that the thread returns to its pure initial state.
[0063] Because MCP protocol calls are inherently stateless, each tools / call is logically independent and does not depend on any residual state from the previous call. Therefore, to adapt to this stateless characteristic, this embodiment can specifically use a combination of Aspect-Oriented Programming (AOP) with thread-local variables (ThreadLocal) and finally blocks to achieve the aforementioned automatic context management.
[0064] Specifically, when the interceptor captures a data source call request, it first reads and temporarily stores a snapshot of the current thread's existing context. Then, based on the data source indication in the data source call request or the selection result of the default primary data source, it writes the new data source identifier into the thread's local storage, completing the context switching and setting. Finally, after execution, regardless of whether the execution process returns normally or throws an exception, the MCP server can trigger recovery logic in the finally block to restore the thread context: it checks whether the previously stored original context is null. If it is not null, it resets the thread's local storage to the original context; if it is null, it clears the current value in the thread's local storage.
[0065] Aspect-Oriented Programming (AOP) can refer to a programming paradigm that separates cross-cutting logic from main business logic. Cross-cutting logic can include common functional logic such as logging, permission verification, performance timing, and caching. A finally block can refer to a syntax block in an exception handling mechanism, primarily used for resource release.
[0066] This embodiment avoids the risk of context leakage caused by thread reuse through the above-described context management mechanism, ensuring absolute isolation and security when switching data sources.
[0067] To improve the usability and robustness of the MCP server in complex configuration environments, if the data source call request does not contain a data source indication, the MCP server can use the current main data source as the data source for this call.
[0068] In this context, "data source indicator" can refer to a unique identifier of the target data source explicitly specified in the data source call request. "Current primary data source" can refer to the default operation object automatically determined according to preset election rules when multiple available data sources exist. This can be the first registered data source, or another data source selected after the first registered data source is deregistered. Specifically, regarding the selection of the primary data source, the MCP server can automatically set the first registered data source as the primary data source. If the primary data source is destroyed, the MCP server can automatically elect a new primary data source from the remaining registered data sources, ensuring that the MCP server always has a usable default data source. The first registered data source can refer to the first instance successfully added to the data source registry during the MCP server's startup or runtime, while the other data source can refer to a replacement instance re-elected from the set of remaining available data sources according to preset strategies (such as registration time order, priority weight, or health status) when the original primary data source is removed or becomes invalid.
[0069] The data source registry can maintain a mapping table that supports concurrent access. This mapping table can store all active data sources, and the MCP server can use a ConcurrentHashMap to store data sources. The primary data source identifier is modified with the `volatile` keyword to ensure cross-thread visibility. The MCP server can have multiple threads, using ThreadLocal (thread-local variables) to achieve thread-isolated data source name storage. Furthermore, the MCP server has a dynamic data source router that inherits from SpringAbstractRoutingDataSource. It dynamically selects data sources based on the ThreadLocal context, supporting runtime dynamic addition or removal of data sources. When the ThreadLocal context is empty, the primary data source is used as the default routing target.
[0070] When the data source parameter is omitted in the data source call request initiated by the agent, the MCP server can automatically fall back to the current primary data source for processing. When the primary data source is deregistered, the MCP server can immediately detect and select a new primary data source, ensuring that subsequent data source call requests without a specified data source will not fail due to the lack of a default target. This can improve the flexibility of switching between multiple data sources and effectively solve the problem of excessive reliance on manual intervention in the management of multiple data sources.
[0071] To adapt to the automatic resolution mechanism of data source configuration in the intelligent agent interaction mode, the MCP server can respond to the data source configuration request sent by the intelligent agent when configuring the data source, identify the data source configuration information contained in the data source configuration request, generate the data source configuration based on the data source configuration information, and store the data source configuration.
[0072] Here, a data source configuration request can refer to a command message initiated by an agent or user to add or update a database connection. Data source configuration information can refer to the set of connection parameters carried in the data source configuration request, which may include parameter mappings (MAPs), structured configuration content (such as YAML or Properties text snippets), and configuration file paths (FILEs). Data source configuration can refer to an internal configuration object generated after being parsed and verified by the MCP server, which can be used to establish a physical database connection.
[0073] The MCP server uses a smart configuration file scanner to scan configuration files. This scanner can scan by directory priority, automatically excluding build directories and version control directories, and supports .yml, .yaml, and .properties formats. Build directories can include target / , build / , etc., while version control directories can include .git / . The MCP server's configuration parser supports direct parameter configuration (MAP), structured configuration content parsing (YAML / Properties), and configuration source types loaded from configuration file paths, allowing users to complete data source configuration with minimal parameters when using MCP tools.
[0074] When the MCP server recognizes that the configuration information is in YAML format, it can try four configuration formats in sequence according to preset priority during the parsing of the YAML configuration. These include spring.datasource.*, datasource.{name}.*, root-level direct configuration, and config.* prefix format. This avoids the problem of inconsistent intelligent agent access caused by differences in project configuration specifications. Among them, spring.datasource.* can include Druid sub-configurations, named data sources spring.datasource.{name}.*, etc.; root-level direct configuration can include url (Uniform Resource Locator), username (username), and password (password), etc.
[0075] Specifically, the MCP server first looks for the standard spring.datasource.* prefix configuration. If it does not find it, it tries the custom configuration of datasource.{name}.*, then tries the root-level direct configuration, and finally tries the extended configuration in the config.* prefix format.
[0076] Furthermore, for scenarios where the configuration file contains multiple named data sources, the MCP server can select the default data source according to the priority of main, master, primary, and default, to avoid the agent failing to make a call due to its inability to decide the target data source when faced with a complex configuration file.
[0077] The MCP server automatically detects the database type based on the JDBC URL prefix or driver class name in the connection parameters, constructs a configuration object according to the database type, registers it with the data source registry, and persists it to a local file in JSON format, thus completing the automatic database configuration parsing. The MCP server can automatically load the saved configuration, and automatically synchronize it to the persistent file when adding or deleting data sources at runtime.
[0078] During the initialization phase, the MCP server can send the definitions of all available tools, including tool names, descriptions, and input parameters, to the agent. The tool definitions occupy the agent's context window, and the total capacity of the context window is limited by tokens. This mechanism creates a token budget constraint unique to the MCP protocol. In order to significantly reduce the occupation of the agent's context window by tool definitions while preserving complete tool capabilities under the token budget constraint of the MCP protocol, and to enable the agent to obtain sufficient tool capabilities within the limited context window while minimizing token consumption, the MCP server can send the simplified metadata of the tool definition to the agent based on the agent's tool registration request. Thus, the MCP server can respond to the data source call request sent by the agent based on the simplified metadata of the tool definition and verify the data source call request.
[0079] The tool definition can refer to standardized descriptive data of the tool's functions, input parameter modes, and invocation methods. The simplified metadata refers to the refined tool summary information, retaining the minimum necessary features for the agent to identify and invoke the tool, while removing redundant data such as example code, lengthy documentation, and non-critical attributes. This simplified metadata can be sent to the agent based on a tool registration request. During the initialization phase of the MCP protocol, the agent can send a tool registration request to the MCP server to obtain a list of currently available tools. Upon receiving the tool registration request, the MCP server does not directly return the original complete tool documentation, but instead returns the simplified metadata of the tool definition.
[0080] This embodiment actively generates simplified metadata through the MCP server, enabling the agent to acquire all tool capabilities at once without relying on additional search primitives or middleware routing, thereby significantly reducing the consumption of context resources while retaining full functionality.
[0081] Specifically, the process of generating simplified metadata for tool definitions may include: controlling the length of the description field of the tool definition to not exceed a length threshold; converting the data type of the tool definition's call parameters to a base type, extracting the value enumeration list and parameter description of the tool definition's call parameters, and encapsulating the tool definition's call parameters into a call parameter set; and modifying the tool definition's tool name according to a preset naming format. The aforementioned steps do not have a fixed execution order.
[0082] The description field can refer to the field in the tool definition used to explain the tool's functions, uses, and application scenarios to the agent. The length threshold can refer to the maximum number of characters preset by the MCP server to enforce the size of the description field. In this embodiment, the length threshold can be specifically 80 characters. Of course, this length threshold can be adjusted according to the context window size of the specific agent. When generating concise metadata, the MCP server can semantically extract the original tool definition, retain the core functional summary, remove lengthy usage examples, historical version descriptions, and non-critical background information, and write the refined text into the description field to ensure that the agent can obtain the necessary semantic information for calling the tool with minimal token consumption.
[0083] Basic data types can refer to atomic data structures such as strings, integers, and boolean values. A value enumeration list can refer to a finite set of allowed input values for a parameter. Parameter descriptions can refer to descriptive text explaining the business meaning, format requirements, and constraints of the parameters. A collection of call parameters can refer to a container structure that encapsulates multiple scattered parameter definitions into a single composite object.
[0084] In this embodiment, the parameter schema in the tool definition can be optimized. The parameter schema can refer to a standardized constraint template for the tool, specifying the complete specifications of all input parameters when calling the tool. This constrains the agent to generate standardized input parameters, ensuring that the parameters can be correctly recognized and executed by the tool. The calling parameters in the parameter schema use the simplest basic types, such as string, int, and bool. The enumeration value list and parameter description are separated from the tool definition. The enumeration value list is externalized to the suggestion field of the error response, avoiding expansion of enumeration values in the tool definition. The parameter description is returned as needed during the structured error response (structured ErrorResponse) runtime, avoiding pre-setting all possible error scenario descriptions in the tool definition. All calling parameters in the tool definition are encapsulated into a set of calling parameters, specifically in the form of a single JSON object parameter, avoiding expansion of all subfields in the tool definition. A single JSON object parameter means that the tool only receives a single, complete object as all input parameters, with no scattered independent parameters; all data that needs to be passed in is within this JSON object. Of course, the aforementioned selection of basic types and the externalization method of the enumeration value list and parameter description can be adapted according to the actual protocol specifications.
[0085] A preset naming format can refer to a predefined, concise naming rule that conforms to the semantic cognitive habits of an intelligent agent. Specifically, in this embodiment, the preset naming format can be: db_ prefix + verb + noun. For example, "executeDatabaseQueryOperation" can be changed to "db_query", and "exportUserDataToFile" can be changed to "db_export_data". Here, the db_ prefix can be used to identify the domain category to which the tool belongs, the verb clearly specifies the operation behavior, and the noun refers to the operation object. The naming method in this embodiment not only reduces the length of tool names but also allows intelligent agents to quickly infer tool functions through short names, reducing the additional tokens consumed to understand the purpose of the tool. Of course, the preset naming format can also be set to other formats that have the function of shortening length while maintaining semantic recognizability.
[0086] Furthermore, this embodiment also supports data migration and a fault tolerance mechanism for data migration. Specifically, the MCP server can respond to a data migration request and perform data migration on the configured first data source and the configured second data source. The data migration includes exporting data from the first data source, parsing and classifying the exported data character by character, and then importing the classified and aggregated data into the second data source in batches. Whenever the batch import is successful, the maximum primary key value of the second data source is updated. If the batch import fails, it is converted to a line-by-line import process, and the data that fails to be imported line by line is stored and retried for a second import. After the data migration is completed, it is verified whether the migrated data in the second data source is consistent with the migrated data in the first data source.
[0087] Here, a data migration request can refer to an instruction message that triggers data synchronization or backup across database instances. The first data source can refer to the source database instance of this migration operation, and the second data source can refer to the target database instance of this migration operation.
[0088] This embodiment can use a concurrent data export method to export data from the first data source. Concurrent data export can refer to a data export method that uses multiple threads to pull data in parallel when pulling data from the data source.
[0089] Regarding the parsing of exported data, this embodiment can employ a streaming import method to parse and aggregate the exported data character by character, and then import the aggregated data in batches into a second data source. Streaming import refers to a data import method where data is read and written simultaneously, with the data stream flowing in batches. The multi-state flag parser used in streaming import can employ five Boolean state flags, including the single-quote string flag inSingleQuote, the double-quote identifier flag inDoubleQuote, the line comment flag inLineComment, the block comment flag inBlockComment, and the escape flag escapeNext. Based on the state flags, the script is parsed character by character. Only when a semicolon is encountered in the normal state without flag activation is the statement considered to have ended and execution committed. This avoids the risk of memory overflow caused by loading a large number of SQL scripts, while accurately handling various boundary cases to prevent SQL from being incorrectly truncated or concatenated.
[0090] Specifically, during parsing, the input stream is read character by character. Only when all status flags are inactive and the current character is a semicolon is a complete SQL statement considered finished and submitted to the execution queue. If a single quote or double quote is encountered and is not escaped, the corresponding quote flag is activated. Subsequent semicolons are treated as string content rather than statement separators until a matching quote is encountered again and is not escaped, at which point the flag is deactivated. When a line comment character or block comment start character is encountered, the corresponding comment flag is activated, masking all content within it until the comment end character appears. Escape flags are temporarily activated when a backslash or other escape character is detected, causing the next character to lose its special semantics.
[0091] After parsing the exported data, it is categorized and aggregated, and then the categorized and aggregated data is imported in batches into a second data source. Categorization and aggregation can refer to grouping and caching the parsed INSERT statements according to the target table name for subsequent batch processing. Batch import can refer to using the batch processing interface provided by the database driver to submit multiple write commands at once.
[0092] Specifically, the MCP server can encapsulate the categorized and aggregated INSERT statements according to a preset batch size, add them to the batch processing buffer using `Statement.addBatch`, and then execute `executeBatch` for batch submission. Each time a batch executes successfully, the system queries and updates the maximum primary key value of the corresponding table in the second data source. The maximum primary key value can refer to the maximum value of the primary key field in existing records in the target table, and is used as the starting breakpoint for incremental migration. This maximum primary key value can not only be used to record migration progress but also serve as the basis for breakpoints in subsequent incremental migrations.
[0093] When a batch execution throws an exception, the task is not terminated directly. Instead, the exception is automatically caught, and all statements in the current batch are converted to a line-by-line import processing mode. That is, `executeUpdate` is called repeatedly to execute each INSERT statement individually. Normal data can be written normally, while abnormal data can be identified, serialized, and stored in a local failure log file, along with a detailed record of the error reason. After the main process of the entire migration task is completed, a secondary import retry mechanism can be triggered automatically or manually to read the failure log file and attempt to write again, or the data can be cleaned manually before re-importing.
[0094] The import mechanism described in this embodiment can effectively ensure high-throughput writing of normal data and also ensure that abnormal data will not be lost due to batch rollback, thus maximizing the integrity of data migration.
[0095] To address potential interruptions during data migration, this embodiment implements a breakpoint-based resume mechanism based on the maximum primary key value. The MCP server can use the maximum primary key value of existing records in the data source as a breakpoint, querying records with primary keys greater than the breakpoint from the source data source for incremental writing, thus achieving incremental data migration. Specifically, when incremental migration starts, the MCP server first queries the target table of the data source for the maximum primary key value of existing records as the breakpoint value, then generates the query SQL. After each batch of writes is successful, the breakpoint value is automatically updated to the new maximum primary key value of the target table. Since the maximum primary key value can be updated in real time after each successful batch import, even if the migration process is interrupted due to system crashes, network failures, or human intervention, it can automatically resume data migration from the breakpoint after restarting, without needing to re-transmit the entire dataset from scratch, without relying on external progress logs, and without requiring manual intervention.
[0096] To ensure the accuracy of the data migration results, after the migration is complete, it is necessary to verify whether the migrated data from the second data source is consistent with the migrated data from the first data source. For example, this can be done by comparing the number of records: counting the total number of records within the migrated range in the first data source and checking if they are equal to the number of records actually written in the second data source. Alternatively, content sampling can be used for comparison: randomly selecting a specified number of records based on the primary key and comparing the field values of the source and target ends field by field to ensure complete consistency.
[0097] This embodiment constructs a complete fault-tolerant link that adapts to the large-scale data migration needs under the MCP call scenario through the collaborative work of streaming import, batch degradation, breakpoint resume, and consistency verification, significantly improving the robustness of data operations and user experience.
[0098] like Figure 2 As shown, this embodiment provides a specific MCP service system, including an MCP client layer, an MCP transport layer, an MCP protocol processing layer, a business service layer, a data access layer, and a data storage layer.
[0099] The MCP client layer can send various requests based on the MCP protocol. The MCP transport layer provides the transmission channel for these requests. The MCP protocol processing layer processes these requests, and the business service layer implements various business logics based on the processing results of the MCP protocol processing layer, including tool definition returns, request validation, database configuration, and data migration. The data access layer can be used to manage various data sources, and the data storage layer can be used to store multiple databases and provide caching.
[0100] This application provides a data source invocation method for intelligent agents. This method pre-validates the data source invocation request of the intelligent agent. If the validation passes, the invocation object indicated by the data source invocation request can be executed directly. If the validation fails, valid error information is actively extracted and a standard structured error response is generated. The structured error response can effectively filter invalid interference data, allowing the intelligent agent to accurately and quickly locate the cause of the error without relying on guesswork and repeatedly modifying the data source invocation request. This effectively guides the intelligent agent to accurately correct the data source invocation request, thereby avoiding the generation of a large number of invalid data source invocation requests and further reducing the operating pressure on the MCP server.
[0101] Furthermore, this method can respond to the agent's tool registration request by sending a simplified metadata of the tool definition to the agent, replacing the full definition data of the tool. This significantly reduces the token consumption during the tool registration phase, effectively saving the agent's limited context window resources and allowing more of the agent's token resources to be used for processing user tasks, thus ensuring the agent's response quality and capabilities.
[0102] This application also provides an electronic device in its embodiments. (See reference...) Figure 3 The diagram illustrates a structural schematic of an electronic device suitable for implementing the agent-oriented data source invocation method in the embodiments of this application. The electronic device in the embodiments of this application may include, but is not limited to, fixed terminals such as mobile phones, laptops, PDAs (personal digital assistants), PADs (tablet computers), desktop computers, etc. Figure 3 The electronic device shown is merely an example and should not impose any limitation on the functionality and scope of use of the embodiments of this application.
[0103] like Figure 3 As shown, the electronic device may include a processing unit (e.g., a central processing unit, a graphics processing unit, etc.) 301, which can perform various appropriate actions and processes according to a program stored in a read-only memory (ROM) 302 or a program loaded from a storage device 308 into a random access memory (RAM) 303. When the electronic device is powered on, the RAM 303 also stores various programs and data required for the operation of the electronic device. The processing unit 301, ROM 302, and RAM 303 are interconnected via a bus 304. An input / output (I / O) interface 305 is also connected to the bus 304.
[0104] Typically, the following devices can be connected to I / O interface 305: input devices 306 including, for example, touchscreens, touchpads, keyboards, mice, cameras, microphones, accelerometers, gyroscopes, etc.; output devices 307 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; storage devices 308 including, for example, memory cards, hard drives, etc.; and communication devices 309. Communication device 309 allows electronic devices to communicate wirelessly or wiredly with other devices to exchange data. Although Figure 3 Electronic devices with various devices are shown, but it should be understood that it is not required to implement or have all of the devices shown. More or fewer devices may be implemented or have alternatively.
[0105] This application also provides a computer program product, including computer-readable instructions, which, when executed on an electronic device, cause the electronic device to implement any of the agent-oriented data source invocation methods provided in this application.
[0106] This application also provides a computer-readable storage medium that carries one or more computer programs. When the one or more computer programs are executed by an electronic device, the electronic device can implement any of the agent-oriented data source invocation methods provided in this application.
[0107] It should also be noted that the device embodiments described above are merely illustrative. The units described as separate components may or may not be physically separate, and the components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the modules can be selected to achieve the purpose of this embodiment according to actual needs. In addition, in the device embodiment drawings provided in this application, the connection relationship between modules indicates that they have a communication connection, which can be implemented as one or more communication buses or signal lines.
[0108] Through the above description of the embodiments, those skilled in the art can clearly understand that this application can be implemented by means of software plus necessary general-purpose hardware, or it can be implemented by special-purpose hardware including application-specific integrated circuits, special-purpose CPUs, special-purpose memory, special-purpose components, etc. Generally, any function performed by a computer program can be easily implemented by corresponding hardware, and the specific hardware structure used to implement the same function can also be diverse, such as analog circuits, digital circuits, or special-purpose circuits. However, for this application, software program implementation is more often the preferred implementation method. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product is stored in a readable storage medium, such as a computer floppy disk, USB flash drive, mobile hard disk, ROM, RAM, magnetic disk, or optical disk, etc., and includes several instructions to cause a computer device (which may be a personal computer, training equipment, or network device, etc.) to execute the methods described in the various embodiments of this application.
[0109] In the above embodiments, implementation can be achieved, in whole or in part, through software, hardware, firmware, or any combination thereof. When implemented in software, it can be implemented, in whole or in part, as a computer program product.
[0110] The computer program product includes one or more computer instructions. When the computer program instructions are loaded and executed on a computer, all or part of the processes or functions described in the embodiments of this application are generated. The computer may be a general-purpose computer, a special-purpose computer, a computer network, or other programmable device. The computer instructions may be stored in a computer-readable storage medium or transmitted from one computer-readable storage medium to another. For example, the computer instructions may be transmitted from one website, computer, training device, or data center to another website, computer, training device, or data center via wired (e.g., coaxial cable, fiber optic, digital subscriber line (DSL)) or wireless (e.g., infrared, wireless, microwave, etc.) means. The computer-readable storage medium may be any available medium that a computer can store or a data storage device such as a training device or data center that integrates one or more available media. The available media may be magnetic media (e.g., floppy disks, hard disks, magnetic tapes), optical media (e.g., DVDs), or semiconductor media (e.g., solid-state drives (SSDs)).
[0111] The various embodiments in this specification are described in a related manner. Similar or identical parts between embodiments can be referred to mutually. Each embodiment focuses on describing the differences from other embodiments. In particular, the apparatus embodiments are basically similar to the method embodiments, so the description is relatively simple; relevant parts can be referred to the descriptions of the method embodiments.
[0112] It is understood that before using the technical solutions disclosed in the various embodiments of this disclosure, users should be informed of the types, scope of use, and usage scenarios of the personal information involved in this disclosure in an appropriate manner in accordance with relevant laws and regulations, and user authorization should be obtained.
[0113] The above are merely embodiments of this application and are not intended to limit the scope of this application. Various modifications and variations can be made to this application by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of this application should be included within the protection scope of this application.
Claims
1. An agent-oriented data source invocation method, characterized in that, The agent-oriented data source invocation method includes: In response to the data source call request sent by the intelligent agent, the data source call request is verified; If the data source call request fails the verification, the error information is extracted, a structured error response is generated based on the error information, and the structured error response is sent to the agent so that the agent can correct the data source call request according to the structured error response and send the corrected data source call request. If the data source call request passes the verification, the call object indicated by the data source call request is executed.
2. The agent-oriented data source invocation method of claim 1, wherein, The verification of the data source call request includes: The existence of the calling object indicated by the data source call request is verified. If the existence verification fails, the verification of the data source call request is deemed to have failed. If the existence check is successful, then the execution statement of the data source call request is subjected to syntax check. If the syntax check fails, then the data source call request is determined to have failed the check. If the syntax validation is successful, the data source call request is deemed to have passed validation.
3. The data source invocation method for intelligent agents according to claim 2, characterized in that, The existence verification of the calling object indicated by the data source call request includes: The original form, all uppercase form, and all lowercase form of the object name of the called object are matched sequentially with the configured data source. If no match is found, it is determined that the called object indicated by the data source call request does not exist, and the existence check is deemed to have failed. If at least one of the original form, the all-uppercase form, and the all-lowercase form matches successfully, it is determined that the calling object indicated by the data source call request exists, and the existence verification is successful.
4. The data source invocation method for intelligent agents according to claim 1, characterized in that, The error message includes an error code; The step of extracting error information and generating a structured error response based on the error information includes: Extract the generated error codes and classify them; Based on the classification results of the error codes, a correction suggestion is generated, an available object list is obtained, and a structured error response containing the correction suggestion and the available object list is generated.
5. The data source invocation method for intelligent agents according to claim 1, characterized in that, Also includes: Before allocating the target thread to carry the current data source call, record the original context of the target thread; After the current data source call is completed, the original context of the target thread is restored.
6. The data source invocation method for intelligent agents according to claim 1, characterized in that, Also includes: If the data source call request does not contain a data source indication, the current primary data source will be used as the data source for this call. The current primary data source is either the first registered data source or another data source selected after the first registered data source is deregistered.
7. The data source invocation method for intelligent agents according to claim 1, characterized in that, Also includes: In response to a data source configuration request sent by the intelligent agent, identify the data source configuration information contained in the data source configuration request; Generate a data source configuration based on the data source configuration information, and store the data source configuration.
8. The data source invocation method for intelligent agents according to claim 1, characterized in that, The step of verifying the data source call request in response to the data source call request sent by the intelligent agent includes: In response to the data source call request sent by the agent based on the simplified metadata defined by the tool, the data source call request is verified. The simplified metadata is sent to the agent based on the agent's tool registration request.
9. The data source invocation method for intelligent agents according to claim 1, characterized in that, Also includes: In response to a data migration request, data migration is performed on a configured first data source and a configured second data source. The data migration includes exporting data from the first data source, performing character-by-character streaming parsing and classifying and aggregating the exported data, and importing the classified and aggregated data into the second data source in batches. Whenever a batch import is successful, the maximum primary key value of the second data source is updated. If the batch import fails, it is switched to a row-by-row import process. The data that failed to be imported row by row is stored and retried for a second import. After the data migration is completed, verify whether the migrated data of the second data source is consistent with the migrated data of the first data source.
10. A computer program product, characterized in that, It includes computer-readable instructions that, when executed on an electronic device, cause the electronic device to implement the agent-oriented data source invocation method as described in any one of claims 1 to 9.
