Program semantic understanding-based MCP service automatic generation system and method
By constructing a program semantic knowledge graph and utilizing heterogeneous graph neural networks and cross-modal Transformer models, the problem of insufficient deep logical semantic understanding of program code in existing technologies is solved, generating accurate natural language service descriptions and improving the reliability and security of intelligent agent invocation.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- BEIJING LINGYIGONG SOFT TECHNOLOGY CO LTD
- Filing Date
- 2026-01-29
- Publication Date
- 2026-05-08
AI Technical Summary
Existing technologies struggle to achieve deep logical and semantic understanding of program code, leading to semantic misalignments when automatically generating service interfaces. This can result in logical errors and security vulnerabilities, hindering the healthy development of the intelligent agent ecosystem.
Through modules for data extraction and graph construction, semantic reasoning and symbolization, description generation and alignment, and feedback learning and optimization, a semantic knowledge graph of the program is constructed and natural language descriptions are generated. Cross-level semantic reasoning and alignment are performed using heterogeneous graph neural networks and cross-modal Transformer models, and model parameters are optimized by combining feedback learning.
It achieves a precise understanding of the deep logical semantics of program code, generates accurate and reliable natural language service descriptions, significantly reduces the risk of errors when intelligent agents make calls, and supports the intelligent construction and evolution of the software ecosystem.
Smart Images

Figure CN121996253A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of semantic understanding, and more specifically, to an automatic MCP service generation system and method based on program semantic understanding. Background Technology
[0002] With the rapid development of artificial intelligence technology, intelligent agents centered on large language models are gradually penetrating all levels of the software ecosystem, becoming important interaction and execution intermediaries in operating systems, basic software, and industrial applications. To enable these intelligent agents to securely and reliably call and control existing, massive amounts of software functions, the industry has proposed intermediate layer protocol standards such as Model Context Protocols. Their core vision is to automatically encapsulate and publish legacy binary programs, library functions, or source code modules as callable services with standardized natural language interfaces, thereby building an intelligent bridge connecting intelligent agents and underlying software resources. This process is a key path to achieve the intelligent upgrade of the software ecosystem, especially in the fields of basic software and industrial software with high security and high reliability requirements, such as the integration and invocation of operating system kernel modules and core algorithms for industrial simulation, where there is an urgent application need.
[0003] However, the current implementation of automatic generation from program code to standardized service interfaces faces a fundamental technical bottleneck: a severe lack of understanding of the deep logical semantics of program code. Existing technical solutions mainly rely on two approaches: first, static program analysis tools based on rule-based and symbolic execution, such as the disassembler framework Ghidra, which can perform syntax parsing and control flow analysis on code, but struggles to penetrate complex data flows and indirect calls, and cannot accurately infer the complete intent and side effects of functions; second, code representation models based on statistical learning, such as CodeBERT, which, trained on large amounts of code corpora, can capture lexical and local syntactic patterns, but exhibits significant limitations in understanding complex logical semantics across functions and files, especially when dealing with subtle algorithmic intents, exception handling paths, concurrency synchronization mechanisms, and domain-specific constraints. These methods generally focus on... Lacking the ability to effectively model and reason about the overall functional behavior, state transitions, and deep semantics of the program's interaction with the external environment based solely on the surface syntactic features or local context of the code, the direct consequence is that semantic misalignment is highly likely to occur when automatically generating service interface descriptions. For example, incorrectly summarizing function functions, omitting key preconditions or postconditions, or misunderstanding the data structure and legal value range of parameters. This defect will directly lead to upper-layer intelligent agents making calls based on incorrect service descriptions, which may in turn cause unpredictable logical errors, system-level security vulnerabilities, or service crashes. This seriously restricts the healthy development of the intelligent agent ecosystem and introduces new potential risks to the software supply chain of critical information infrastructure. Therefore, how to achieve deep, accurate, and interpretable semantic understanding of program code, especially complex system code, has become a core problem that urgently needs to be solved in this technical field. Summary of the Invention
[0004] This invention addresses the technical problems existing in the prior art by providing an automatic MCP service generation system and method based on program semantic understanding. It solves the problems mentioned in the background art through a data extraction and graph construction module, a semantic reasoning and symbolization module, a description generation and alignment module, and a feedback learning and optimization module.
[0005] The technical solution of the present invention to solve the above-mentioned technical problems is as follows: an automatic generation system for MCP services based on program semantic understanding, specifically comprising: a data extraction and graph construction module, a semantic reasoning and symbolization module, a description generation and alignment module, and a feedback learning and optimization module connected in sequence, wherein;
[0006] Data extraction and graph construction module: In response to receiving the target program code, the module extracts the syntactic structure information, runtime trajectory information and associated document information of the target program code through a static semantic analyzer, dynamic behavior analyzer and context information collector executed in parallel. The module then integrates these three types of heterogeneous information to construct an original program semantic knowledge graph containing multiple node types and edge relationships.
[0007] Semantic Reasoning and Symbolization Module: By loading the original program semantic knowledge graph generated by the data extraction and graph construction module, and using a cascaded model containing heterogeneous graph neural networks and multi-hop reasoning units, the module performs cross-level message passing and semantic relationship reasoning on the nodes and edges in the original program semantic knowledge graph, identifies the high-level logical units that represent the program's functional intent, and generates an intent symbolization graph with nodes as symbolized intent units.
[0008] Description generation and alignment module: Through a structure-aware cross-modal Transformer model, the intention symbolic graph generated by the semantic reasoning and symbolization module is used as input, and a dual attention alignment mechanism is adopted to generate a natural language description draft corresponding to the symbolic intention units in the intention symbolic graph;
[0009] Feedback Learning and Optimization Module: By deploying a semantic feedback parser and a policy network, it monitors in real time the execution results of the MCP service built based on the initial draft of the natural language description generated by the description generation and alignment module in actual calls, converts it into semantic feedback signals, and adjusts the parameters of the cascaded model in the semantic reasoning and symbolization module and the parameters of the structure-aware cross-modal Transformer model in the description generation and alignment module based on these semantic feedback signals.
[0010] In a preferred embodiment, the data extraction and graph construction module includes the following specific steps for the extraction and preprocessing of three types of heterogeneous information by the static semantic analyzer, dynamic behavior analyzer, and context information collector:
[0011] The static semantic analyzer performs lexical and syntactic analysis on the target program code, generates an abstract syntax tree, and performs data flow and dependency analysis based on the abstract syntax tree to extract a static semantic metadata set consisting of syntactic entities and their structural relationships. The static semantic metadata set contains multiple first elements, each of which represents a syntactic entity and its attributes.
[0012] In an isolated sandbox environment, the dynamic behavior analyzer drives the execution of the target program code through a set of pre-defined test cases, and uses instrumentation techniques to capture function call sequences, parameter passing, return values and exception events, forming a dynamic behavior metadata set that records the program's runtime behavior. The dynamic behavior metadata set contains multiple second elements, each of which represents a runtime event or state snapshot.
[0013] The context information collector scans the project directory and associated version control system of the target program code, extracts build configuration files, dependency library lists, application interface document fragments and version commit logs to form a context semantic metadata set. The context semantic metadata set contains multiple third elements, each of which represents a descriptive text.
[0014] In a preferred embodiment, the process of fusing the three types of heterogeneous information to construct the original program semantic knowledge graph specifically involves:
[0015] First, based on the syntactic entities in the static semantic metadata set, a graph skeleton containing nodes and syntactic relation edges is initialized, where nodes correspond to syntactic entities;
[0016] Subsequently, a fusion algorithm based on evidence theory is adopted to fuse information from the dynamic behavior metadata set and the contextual semantic metadata set as evidence into the graph skeleton. The fusion algorithm calculates a comprehensive confidence score for each node in the graph skeleton. The comprehensive confidence score is jointly determined by the first calculation term and the second calculation term. The calculation process of the first calculation term is as follows: from the dynamic behavior metadata set, a subset of dynamic behavior evidence that supports the current node being judged to have a core functional status is selected. For each dynamic behavior evidence in the subset of evidence, its own weight is multiplied by a correlation strength function value. The above multiplication results of all supporting dynamic behavior evidence are accumulated to obtain the base value of the first calculation term.
[0017] The second calculation term is the average similarity contribution value between the semantic vectors of all context description fragments related to this node and the node vector. The semantic vector is obtained by performing an embedding model transformation on the descriptive text in the context semantic metadata set, and the node vector is obtained by performing the same embedding model transformation on the identifier text of the grammatical entity corresponding to this node. The average similarity contribution value is obtained by calculating the cosine similarity between the node vector and the semantic vector of each related context description fragment and taking the average value.
[0018] The fusion algorithm also sets a total evidence normalization factor, which is used to scale and merge the base value of the first calculation item and the average similarity contribution value of the second calculation item. The overall confidence level is the result after processing by the total evidence normalization factor.
[0019] Finally, the graph skeleton, the comprehensive confidence scores of each node calculated by the fusion algorithm, and the descriptive text extracted from the context semantic metadata set are integrated to generate the original program semantic knowledge graph; wherein, the original program semantic knowledge graph includes:
[0020] A set of nodes whose elements are syntactic entities defined in a static semantic metadata set;
[0021] The edge set consists of connection relationships defined based on structural relationships in the static semantic metadata set, associations in the dynamic behavioral metadata set, and semantic associations.
[0022] The attribute set consists of attribute information attached to the elements in the node set and the edge set. The attribute information includes the overall confidence level, the type of the syntactic entity, and the descriptive text extracted from the context semantic metadata set.
[0023] In a preferred embodiment, the semantic reasoning and symbolization module performs cross-level message passing and semantic relationship reasoning on nodes and edges in the original program's semantic knowledge graph as follows:
[0024] First, the original program semantic knowledge graph is loaded, and for each element in the node set of the original program semantic knowledge graph, i.e. the grammatical entity, an initial feature vector is constructed. The initial feature vector is composed of type information, comprehensive confidence and embedding vector of the descriptive text from the attribute set of the original program semantic knowledge graph corresponding to the grammatical entity.
[0025] Subsequently, a multi-relation graph attention network is used to encode the original program semantic knowledge graph. The multi-relation graph attention network contains a set of learnable parameters, defining independent learnable parameters for each type of edge relation in the original program semantic knowledge graph. The learnable parameters include a linear transformation matrix for feature transformation and an attention vector for calculating attention weights. These learnable parameters are randomly initialized at the beginning of model training and optimized using gradient descent through an optimizer and its hyperparameters during training. During information transmission, for each grammatical entity that serves as the target node, the attention weights of each of its neighboring nodes under different relation types are calculated. The calculation process of the attention weights is as follows: for a neighboring node connected to the target node through a given type of edge relation, the linear transformation matrix corresponding to the type of edge relation is first used to transform the current layer feature vector of the target node and the current layer feature vector of the neighboring node respectively.
[0026] Next, the two transformed feature vectors are concatenated to form a combined vector;
[0027] Then, the dot product of the transpose of the attention vector corresponding to this type of edge relationship and the combined vector is calculated, and the dot product result is input into a non-linear activation function for processing to obtain an original attention score; finally, the original attention score is exponentially normalized relative to the original attention scores of all neighboring nodes connected to the target node through the same type of edge relationship, and the result is the attention weight of the neighboring node to the target node under this relationship type.
[0028] Next, the target node updates its feature representation by weighting and aggregating the feature information of all its neighboring nodes after transformation by the corresponding linear transformation matrix under all relation types according to the attention weight. After multiple iterations, the enhanced semantic representation of each syntactic entity in the original program semantic knowledge graph is obtained by integrating multi-hop and multi-relation context.
[0029] In a preferred embodiment, the process of generating the intention symbolization map specifically includes:
[0030] Based on the enhanced semantic representation, higher-order semantic relations are completed using a multi-hop inference unit. This multi-hop inference unit predefines a set of meta-path templates, which represent the higher-order semantic relation patterns to be inferred. In the original program semantic knowledge graph, path instances matching the conditions are searched for node pairs composed of syntactic entities and meta-path templates. A path inference score is calculated for each found path instance. The calculation process for the path inference score is as follows: For a given path instance connecting a starting node and a target node, the path instance consists of a series of edges and intermediate nodes. First, a semantic compatibility evaluation value between the starting node and the target node is calculated. This value is obtained by using an enhanced semantic representation vector of the starting node and... The enhanced semantic representation vector of the target node is obtained by inputting a function; next, a path support product is calculated, which is performed on each edge in the path instance and the next node it connects to. For each edge, a support value is calculated, which is obtained by inputting a function with the type of the edge and the enhanced semantic representation vector of the node the edge points to. Then, the support values corresponding to all edges in the path instance are multiplied to obtain the path support product; finally, the semantic compatibility evaluation value is multiplied by the path support product to obtain the path inference score; if the path inference score exceeds a preset threshold, a new edge representing the higher-order semantic relationship is added between the corresponding node pairs in the graph.
[0031] Subsequently, the completed graph with the enhanced semantic representation is subjected to intent clustering. The set of syntactic entities that realize a common functional intent is abstracted into symbolic intent units, which are abstract semantic nodes representing high-level functional intents. The clustering process is implemented through a differentiable sparse clustering algorithm, which includes a set of learnable parameters, including a weight matrix and bias vector of a fully connected neural network layer for mapping the enhanced semantic representation vector to the intent space, and multiple prototype vectors representing the center positions of symbolic intent units. The prototype of each syntactic entity is calculated to one or more symbolic intent units according to the following rules. Sparse allocation weights for vectors: For a given syntactic entity, first, obtain the representation vector of the syntactic entity in the intent space; then, calculate the square of the Euclidean distance between the representation vector of the syntactic entity and the prototype vector of each symbolic intent unit; next, multiply the square of each distance by a negative temperature coefficient and take the natural exponential function value to obtain a series of initial allocation values; finally, for the prototype vector of each symbolic intent unit, divide its corresponding initial allocation value by the sum of the initial allocation values corresponding to the prototype vectors of all symbolic intent units, and the result is the sparse allocation weight from the syntactic entity to the symbolic intent unit.
[0032] Finally, based on the sparse allocation weights, the following operations are performed to generate the intent symbolization graph: First, syntactic entities with significant sparse allocation weights are classified into corresponding symbolic intent units, with each symbolic intent unit serving as a node in the intent symbolization graph; then, the feature vector of each symbolic intent unit is aggregated from the enhanced semantic representation vectors of all its member syntactic entities according to their corresponding sparse allocation weights; simultaneously, the weight of the connection edge between two symbolic intent units is obtained by accumulating the strengths of all connections existing in the completed graph between all member syntactic entities belonging to these two symbolic intent units, and then weighting them according to the sparse allocation weights.
[0033] In a preferred embodiment, the process of encoding and fusing the intent symbolization graph using a structure-aware cross-modal Transformer model in the description generation and alignment module specifically includes:
[0034] First, load the intent symbolization graph, obtain the feature vectors of all symbolized intent units in the graph and the connection relationships between units. The feature vectors are the feature vectors corresponding to each symbolized intent unit output from the semantic reasoning and symbolization module.
[0035] Next, node feature enhancement is performed: for each symbolic intent unit in the intent symbolization graph, its feature vector is used as the initial feature. Using the connection relationship between units, it is processed through a graph convolutional network layer, so that the updated feature vector of each symbolic intent unit incorporates the feature information of its directly adjacent units, resulting in the enhanced node feature vector.
[0036] Subsequently, a structural location encoding vector is generated: For the intent symbolization graph, multiple node sequences are generated through random walk sampling, and based on these node sequences, a fixed vector representation, called the structural location encoding vector, is learned for each symbolic intent unit in the intent symbolization graph using a language model training method.
[0037] Next, serialization and vector concatenation are performed: all symbolic intent units are sorted according to preset rules to form an input sequence; for each symbolic intent unit in the input sequence, its enhanced node feature vector, the corresponding structural position encoding vector, and a standard sinusoidal position encoding vector calculated based on the position of the unit in the input sequence are concatenated to construct the final input feature vector of the unit.
[0038] The final input feature vectors of all symbolic intent units arranged in this order are combined to form an input sequence, which is then input into the encoder part of the structure-aware cross-modal Transformer model. The structure-aware cross-modal Transformer model contains a large number of learnable parameters, including the query, key, and value linear transformation matrices of the self-attention and cross-attention modules in each layer of its encoder and decoder, the weight matrix and bias vector of the feedforward neural network, and the weight matrix and bias vector of the learnable alignment-gated linear transformation layer. During the self-attention calculation of the encoder, a structural bias matrix is introduced, and the value of each element is determined according to the following rule: in the intention symbolization graph, the shortest path distance between the two symbolic intent units corresponding to the element is found. The structural bias matrix is used as a bias term in the self-attention score calculation of the encoder, thereby injecting the structural information of the intention symbolization graph into the attention weight allocation, enabling the model to perceive the topological proximity relationship between units and encode a symbolic intent unit representation sequence that incorporates structural semantics.
[0039] In a preferred embodiment, the process of generating a draft natural language description using a dual attention alignment mechanism specifically includes:
[0040] Based on a sequence of symbolic intent unit representations incorporating structural semantics, a draft of a natural language description is generated in an autoregressive manner using the decoder portion of a structure-aware cross-modal Transformer model; at each time step of the decoder, dual attention alignment computation is performed.
[0041] The first layer is intentional cohesive attention, which uses the structural bias matrix in the decoder self-attention layer to correct the original attention score generated in the decoder self-attention calculation.
[0042] The second layer is the description generation alignment attention, which sets a learnable alignment gate value in the decoder cross-attention layer. The learnable alignment gate value is dynamically calculated at each time step according to the following rules: First, obtain the query vector of the decoder at the current time step; simultaneously, obtain the sequence of hidden state representation vectors corresponding to the partially generated description text of the decoder in all previous time steps, and calculate the average of all vectors in the sequence to obtain the context vector of the generated text; next, concatenate the query vector with the context vector of the generated text to form a combined vector; then, input the combined vector into a linear transformation layer for processing, the linear transformation layer contains a learnable weight matrix and bias vector; finally, input the output of the linear transformation layer into a sigmoid function for mapping, constraining the result to between zero and one, and this result is the alignment gate value of the current time step.
[0043] The description generation process utilizes alignment gating values to dynamically blend context vectors from two information sources to generate the vocabulary for the current time step: the first information source is a first context vector obtained by cross-attention calculation based on a sequence of symbolic intent unit representations that incorporate structural semantics; the second information source is a second context vector obtained by cross-attention calculation based on a sequence of hidden state representation vectors from the generated partial description text; the blended context vector used for the final vocabulary generation is equal to the alignment gating value multiplied by the first context vector, plus a result of subtracting the alignment gating value and multiplying by the second context vector; the decoder predicts the vocabulary for the current time step based on the blended context vector and adds it to the end of the generated sequence, repeating this process until a complete end marker is generated, at which point the complete vocabulary sequence is the initial draft of the natural language description;
[0044] The entire generation process is trained and optimized by minimizing a combined loss function, called the total loss. The value of the combined loss function is the sum of a standard sequence generation loss and a semantic alignment constraint loss multiplied by a preset positive weighting coefficient.
[0045] In a preferred embodiment, the process by which the semantic feedback parser transforms the actual execution result of the MCP service call into a semantic feedback signal in the feedback learning and optimization module specifically includes:
[0046] Real-time monitoring is performed on every call to the MCP service constructed based on the initial draft of the natural language description, recording its complete execution trajectory information. Based on the recorded execution trajectory information, a multi-dimensional, fine-grained semantic feedback signal vector is constructed. Each dimension of this vector corresponds to a preset semantic feedback type, and its value is calculated according to the evaluation rules of the corresponding semantic feedback type. The semantic feedback type includes functional correctness dimension, parameter matching degree dimension, abnormal semantic relevance dimension, and performance degradation dimension. The final generated semantic feedback signal vector serves as the input for subsequent credit allocation and optimization strategies.
[0047] In a preferred embodiment, the process of adjusting the parameters of the cascaded model in the semantic reasoning and symbolization module and the parameters of the structure-aware cross-modal Transformer model in the description generation and alignment module based on this signal specifically includes:
[0048] First, the semantic feedback signal vector is input into a credit allocation network. This network takes as input the intermediate representations of the original program semantic knowledge graph and intent symbolic graph upon which the currently invoked MCP service is based, and outputs a two-dimensional credit allocation vector. Simultaneously, the semantic feedback signal vector is combined into a scalar reward value using a preset reward function. The calculation process of the reward function is as follows: First, the semantic feedback signal vector is processed by a nonlinear transformation function, which maps the various components of the vector to a uniform numerical range. Then, the transformed vector is multiplied by a preset weight vector; the result of the dot product is the scalar reward value.
[0049] Next, based on the credit allocation vector, the scalar reward value is decomposed into two hierarchical reward values corresponding to the semantic reasoning and symbolization module and the description generation and alignment module, respectively. The specific calculation of the decomposition is as follows: multiply the scalar reward value by the first element of the credit allocation vector to obtain the hierarchical reward value corresponding to the semantic reasoning and symbolization module; multiply the scalar reward value by the second element of the credit allocation vector to obtain the hierarchical reward value corresponding to the description generation and alignment module.
[0050] Then, the semantic feedback signal vector, the historical statistical information of the hierarchical reward value, and the gradient statistics of the cascaded model and the structure-aware cross-modal Transformer model during recent training are input into the policy network. These inputs together constitute the context on which the policy network makes decisions, i.e., the current state information of the system. The policy network is trained using a proximal policy optimization algorithm, the output of which is a suggestion for adjusting the hyperparameters of the optimizer of the cascaded model and the structure-aware cross-modal Transformer model. The proximal policy optimization algorithm updates the learnable parameters of the policy network by minimizing an alternative objective function.
[0051] Finally, a progressive knowledge distillation strategy is employed to apply adjustment suggestions to update the learnable parameters within the cascaded model and the structure-aware cross-modal Transformer model. The implementation process of the progressive knowledge distillation strategy is as follows: First, a teacher model and a student model are defined. The teacher model refers to the currently deployed online system comprised of the cascaded model in the semantic reasoning and symbolization module and the structure-aware cross-modal Transformer model in the description generation and alignment module. The student model is a structurally complete copy of the teacher model, with its initial and internal learnable parameters entirely replicated from the teacher model's current learnable parameters. Next, based on the adjustment suggestions output by the policy network, the learnable parameters of the student model are optimized offline in multiple steps by minimizing a combined loss function. The combined loss function is tailored to the specific learning parameters of the teacher model. The semantic reasoning and symbolization module and the description generation and alignment module are calculated and optimized independently. Specifically, the combined loss function for the semantic reasoning and symbolization module is obtained by weighted summing of a first loss term (the negative value corresponding to the hierarchical reward value of the semantic reasoning and symbolization module) and a second loss term (KL divergence, which measures the difference in output distributions between the cascaded models in the student model and the corresponding models in the teacher model under the same input conditions). Similarly, the combined loss function for the description generation and alignment module is obtained by weighted summing of a first loss term (the negative value corresponding to the hierarchical reward value of the description generation and alignment module) and a second loss term (KL divergence, which measures the difference in output distributions between the structure-aware cross-modal Transformer model in the student model and the corresponding model in the teacher model under the same input conditions).
[0052] In each optimization iteration, based on the numerical value of the responsibility ratio in the credit allocation vector, the above knowledge distillation optimization is performed on the semantic reasoning and symbolization module or the description generation and alignment module; in the combined loss function, the first loss term is multiplied by a first balance coefficient, and the second loss term is multiplied by a second balance coefficient.
[0053] The learnable parameters of the optimized and stable student model are then synchronized back to the corresponding cascaded model and the structure-aware cross-modal Transformer model in the online teacher model, thereby completing the stable adjustment of the learnable parameters of the cascaded model and the structure-aware cross-modal Transformer model.
[0054] This application also provides a method for automatically generating MCP services based on program semantic understanding, which specifically includes the following steps:
[0055] Step S1: In response to receiving the target program code, extract and fuse three types of heterogeneous metadata by parallel analysis of its static, dynamic and contextual semantics, and construct the original program semantic knowledge graph.
[0056] Step S2: Based on the original program semantic knowledge graph, cross-level semantic reasoning and intent abstraction are performed through cascaded heterogeneous graph neural networks and multi-hop reasoning units to generate an intent symbolization graph with symbolized intent units as nodes.
[0057] Step S3: Using the intent symbolization graph as input, generate a corresponding natural language description draft through a structure-aware cross-modal Transformer model and a dual attention alignment mechanism;
[0058] Step S4: Monitor the results of the MCP service built based on the initial description in actual calls, convert it into semantic feedback signals, and optimize the learnable parameters of the cascaded model and the cross-modal Transformer model based on these signals through a progressive knowledge distillation strategy.
[0059] The beneficial effects of this invention are: it can achieve accurate understanding and reasoning of the deep logical semantics of program code, automatically transform complex code into accurate and reliable natural language service descriptions, significantly improve the semantic fidelity and reliability of generated service interfaces by integrating multi-dimensional evidence and continuous online feedback optimization, effectively reduce the risk of errors when intelligent agents call, and form a closed loop with self-improvement capabilities, thereby intelligently supporting the construction and evolution of the software ecosystem. Attached Figure Description
[0060] Figure 1 This is a flowchart of the method of the present invention;
[0061] Figure 2 This is a block diagram of the system structure of the present invention. Detailed Implementation
[0062] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, and not all embodiments. Based on the embodiments of this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
[0063] In the description of this application, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of indicated technical features. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of the stated features. In the description of this application, "multiple" means two or more, unless otherwise explicitly specified.
[0064] In the description of this application, the term "for example" is used to mean "used as an example, illustration, or description." Any embodiment described as "for example" in this application is not necessarily to be construed as being more preferred or advantageous than other embodiments. The following description is provided to enable any person skilled in the art to make and use the invention. Details are set forth in the following description for purposes of explanation. It should be understood that those skilled in the art will recognize that the invention can be made without using these specific details. In other instances, well-known structures and processes will not be described in detail to avoid obscuring the description of the invention with unnecessary detail. Therefore, the invention is not intended to be limited to the embodiments shown, but is consistent with the broadest scope of the principles and features disclosed in this application.
[0065] Example 1
[0066] This embodiment provides, for example Figure 1 This paper presents an automatic MCP service generation method based on program semantic understanding, which specifically includes the following steps:
[0067] Step S1: In response to receiving the target program code, extract and fuse three types of heterogeneous metadata by parallel analysis of its static, dynamic and contextual semantics, and construct the original program semantic knowledge graph.
[0068] Step S2: Based on the original program semantic knowledge graph, cross-level semantic reasoning and intent abstraction are performed through cascaded heterogeneous graph neural networks and multi-hop reasoning units to generate an intent symbolization graph with symbolized intent units as nodes.
[0069] Step S3: Using the intent symbolization graph as input, generate the corresponding natural language description draft through the structure-aware cross-modal Transformer model and dual attention alignment mechanism;
[0070] Step S4: Monitor the results of the MCP service built based on the initial description draft in actual calls, convert it into semantic feedback signals, and optimize the learnable parameters of the cascaded model and the cross-modal Transformer model based on these signals through a progressive knowledge distillation strategy.
[0071] Example 2
[0072] This embodiment provides, for example Figure 2 The system illustrates an automatic MCP service generation system based on program semantic understanding, specifically comprising: a data extraction and graph construction module, a semantic reasoning and symbolization module, a description generation and alignment module, and a feedback learning and optimization module connected sequentially; wherein;
[0073] Data extraction and graph construction module: In response to receiving the target program code, the module extracts the syntactic structure information, runtime trajectory information and associated document information of the target program code through a static semantic analyzer, dynamic behavior analyzer and context information collector executed in parallel. The module then integrates these three types of heterogeneous information to construct an original program semantic knowledge graph containing multiple node types and edge relationships.
[0074] Semantic Reasoning and Symbolization Module: By loading the original program semantic knowledge graph generated by the data extraction and graph construction module, and using a cascaded model containing heterogeneous graph neural networks and multi-hop reasoning units, the module performs cross-level message passing and semantic relationship reasoning on the nodes and edges in the original program semantic knowledge graph, identifies the high-level logical units that represent the program's functional intent, and generates an intent symbolization graph with nodes as symbolized intent units.
[0075] Description generation and alignment module: Through a structure-aware cross-modal Transformer model, the intention symbolic graph generated by the semantic reasoning and symbolization module is used as input, and a dual attention alignment mechanism is adopted to generate a natural language description draft corresponding to the symbolic intention units in the intention symbolic graph;
[0076] Feedback Learning and Optimization Module: By deploying a semantic feedback parser and a policy network, it monitors in real time the execution results of the MCP service built based on the initial natural language description generated by the description generation and alignment module in actual calls, converts it into semantic feedback signals, and adjusts the parameters of the cascaded model in the semantic reasoning and symbolization module and the parameters of the structure-aware cross-modal Transformer model in the description generation and alignment module based on these semantic feedback signals.
[0077] In this embodiment, it is specifically necessary to explain that the extraction and preprocessing process of the three types of heterogeneous information by the static semantic analyzer, dynamic behavior analyzer, and context information collector in the data extraction and graph construction module includes:
[0078] The static semantic analyzer performs lexical and syntactic analysis on the target program code, generating an abstract syntax tree (AST). Based on the AST, it performs data flow and dependency analysis, extracting a static semantic metadata set composed of syntactic entities and their structural relationships. The static semantic metadata set contains multiple first elements, each representing a syntactic entity and its attributes. Lexical and syntactic analysis can be performed using parser generation tools such as ANTLR, generating corresponding lexical and syntactic analyzers according to the syntactic specifications of the target program language. Data flow and dependency analysis is based on the generated AST, constructing control flow graphs, control dependency graphs, and data dependency graphs using analysis frameworks such as Soot, WALA, or custom frameworks to extract syntactic entities such as functions, variables, classes, and methods, as well as structural relationships such as "call," "containment," "inheritance," and "data flow."
[0079] In an isolated sandbox environment, the dynamic behavior analyzer drives the execution of target program code through a pre-defined test case set. It uses instrumentation techniques to capture function call sequences, parameter passing, return values, and exception events, forming a dynamic behavior metadata set that records the program's runtime behavior. This set contains multiple second elements, each representing a runtime event or state snapshot. The pre-defined test case set can be generated using code coverage-guided fuzzing techniques, such as using AFL or LibFuzzer to fuzz the program entry point to explore diverse execution paths. The instrumentation technique specifically employs dynamic binary instrumentation tools, such as IntelPin or DynamoRIO, which inject probe code into function entry / exit points, conditional branches, and memory access points during target program code execution. This non-intrusive recording of function call sequences, parameter values, return values, exception types, and stack information is achieved through this process.
[0080] The context information collector scans the project directory and associated version control system of the target program code, extracting build configuration files, dependency lists, application interface document fragments, and version commit logs to form a context semantic metadata set. This set contains multiple third elements, each representing a descriptive text or a configuration item. The scanned project directory is defined as the root directory containing the target program code and all its subdirectories. Extraction rules include: identifying and parsing build configuration files such as Makefile, CMakeLists.txt, pom.xml, and package.json to obtain dependency information; reading or crawling README.md, .md documents, and document files with .dox or .rst extensions from the code repository; and extracting commit information and a list of changed files from the most recent N (e.g., 50) commits by calling commands or APIs of version control systems such as Git, using the parts of the commit information related to the current target program code file as descriptive text.
[0081] The static semantic metadata set, the dynamic behavioral metadata set, and the contextual semantic metadata set serve as input sources for subsequent fusion operations;
[0082] The process of fusing three types of heterogeneous information to construct a semantic knowledge graph of the original program is as follows:
[0083] First, based on the syntactic entities in the static semantic metadata set, a graph skeleton containing nodes and syntactic relation edges is initialized, where nodes correspond to syntactic entities;
[0084] Subsequently, a fusion algorithm based on evidence theory is employed to fuse information from the dynamic behavior metadata set and the contextual semantic metadata set as evidence into the graph skeleton. The fusion algorithm calculates a comprehensive confidence score for each node in the graph skeleton. The comprehensive confidence score is jointly determined by a first calculation term and a second calculation term. The calculation process for the first calculation term is as follows: from the dynamic behavior metadata set, a subset of dynamic behavior evidence supporting the current node's determination of having a core functional position is selected. The selection criteria include: the function involved in the dynamic behavior evidence is directly related to the syntactic entity represented by the current node; for example, the evidence records a call to the function corresponding to the node, or a state transition caused by the execution of the function; and the frequency of occurrence of this evidence must be higher than a preset first frequency threshold, for example, appearing in all test case executions. If the number of occurrences exceeds 5, for each dynamic behavior evidence in the subset of evidence, its own weight is multiplied by a correlation strength function value. The weight is dynamically determined based on the frequency of occurrence of the dynamic behavior evidence and the uniqueness of the corresponding execution path. Specifically, it can be calculated and normalized using the formula: Weight = (Frequency of occurrence / Total number of executions) * log(1 + Number of unique execution paths). The correlation strength function value represents the logical correlation between the dynamic behavior evidence and the current node. The correlation strength function can be predefined in a mapping table according to the evidence type. For example, the correlation strength of a direct function call is 1.0, the correlation strength of indirect influence through parameters is 0.7, and the correlation strength of occurrence in the same exception stack is 0.5. The above product results of all supporting dynamic behavior evidence are accumulated to obtain the base value of the first calculation term.
[0085] The second calculation term is the average similarity contribution between the semantic vectors of all contextual description fragments related to this node and the node vector. The semantic vectors are obtained by embedding the descriptive text in the context semantic metadata set. The embedding model can be a pre-trained language model, such as the text embedding model of Sentence-BERT or BGE. The node vectors are obtained by embedding the identifier text of the grammatical entity corresponding to this node using the same embedding model. The average similarity contribution is obtained by calculating the cosine similarity between the node vector and the semantic vector of each related contextual description fragment and taking the average value. Before taking the average value, a second similarity threshold can be set, for example, 0.6, to retain only description fragments with a cosine similarity higher than this threshold for participating in the average value calculation, so as to filter out low-relevance noise text.
[0086] The fusion algorithm also sets a total evidence normalization factor, which is used to scale and merge the base value of the first calculation item and the average similarity contribution value of the second calculation item. The total evidence normalization factor can be the reciprocal of the sum of the two values, or it can be linearly adjusted by a learnable scaling parameter and bias parameter to ensure that the overall confidence falls within the [0,1] interval. The overall confidence is the result after processing by the total evidence normalization factor.
[0087] Finally, the graph skeleton, the comprehensive confidence scores of each node calculated by the fusion algorithm, and the descriptive text extracted from the context semantic metadata set are integrated to generate the original program semantic knowledge graph; wherein, the original program semantic knowledge graph includes:
[0088] A set of nodes whose elements are syntactic entities defined in a static semantic metadata set;
[0089] The edge set consists of connection relationships defined based on structural relationships in the static semantic metadata set, associations in the dynamic behavioral metadata set, and semantic associations.
[0090] The attribute set consists of attribute information attached to the elements in the node set and the edge set. The attribute information includes the overall confidence level, the type of the syntactic entity, and the descriptive text extracted from the context semantic metadata set. This graph serves as a unified intermediate representation, providing a structured input that can be directly processed for subsequent semantic reasoning and symbolization modules.
[0091] In this embodiment, it is specifically necessary to explain that the process of cross-level message passing and semantic relationship reasoning of nodes and edges in the original program's semantic knowledge graph in the semantic reasoning and symbolization module is as follows:
[0092] First, the original program semantic knowledge graph is loaded, and for each element in the node set of the original program semantic knowledge graph, i.e., the syntactic entity, its corresponding initial feature vector is constructed. The initial feature vector is composed of type information, comprehensive confidence, and embedding vector of the descriptive text from the attribute set of the original program semantic knowledge graph corresponding to the syntactic entity. Among them, type information is converted into type vector through a learnable embedding table; comprehensive confidence is directly used as scalar feature; descriptive text is converted into fixed-dimensional text vector through a pre-trained text embedding model, such as Sentence-BERT; the concatenation operation connects the above three vectors in dimensional order to form the initial feature vector of each syntactic entity.
[0093] Subsequently, a multi-relation graph attention network is used to encode the original program semantic knowledge graph. The multi-relation graph attention network contains a set of learnable parameters, defining independent learnable parameters for each type of edge relation in the original program semantic knowledge graph. The learnable parameters include a linear transformation matrix for feature transformation and an attention vector for calculating attention weights. These learnable parameters are randomly initialized at the beginning of model training and optimized during training using gradient descent with an optimizer and its hyperparameters (such as the learning rate). During information transmission, for each grammatical entity that serves as the target node, the attention weights of each of its neighboring nodes (i.e., other grammatical entities connected to it via edges) under different relation types are calculated. The calculation process of attention weights is as follows: for a neighboring node connected to the target node via a given type of edge relation, the linear transformation matrix corresponding to the type of edge relation is first used to transform the current layer feature vector of the target node and the current layer feature vector of the neighboring node respectively. The dimension of the linear transformation matrix is determined according to the input feature dimension and the preset hidden layer dimension.
[0094] Next, the two transformed feature vectors are concatenated to form a combined vector;
[0095] Then, the dot product of the transpose of the attention vector and the combined vector corresponding to this type of edge relationship is calculated, and the dot product result is input into a nonlinear activation function for processing to obtain an original attention score; the nonlinear activation function is the LeakyReLU function, whose negative slope coefficient is usually set to 0.2; finally, this original attention score is exponentially normalized relative to the original attention scores of all neighboring nodes connected to the target node through the same type of edge relationship, and the result is the attention weight of the neighboring node to the target node under this relationship type; the "linear transformation matrix" is used to map the feature vector of the node to the feature subspace associated with the given type of edge relationship; the "attention vector" is used to map the feature vector of the node to the feature subspace associated with the given type of edge relationship; "Quantity" is a parameter vector corresponding to the given type of edge relation, used to evaluate the interaction strength between node pairs in the context of that relation; "Nonlinear activation function" is the LeakyReLU function; attention weight is used to characterize the importance of the neighbor node's semantic contribution to the target node through the given type of edge relation; "Exponential normalization processing" means: first, take the natural exponential function value of the original attention score corresponding to each neighbor node of the target node under the given type of edge relation, and then divide the exponential result of the current neighbor node by the sum of the exponential results of all neighbor nodes; "Current layer feature vector" is the initial feature vector in the first iteration, and the feature vector obtained after the previous iteration in subsequent iterations;
[0096] Next, the target node updates its feature representation by weighted aggregation of the feature information of all its neighboring nodes after transformation by the corresponding linear transformation matrix under all relation types, based on attention weights. The specific operation of "weighted aggregation" is as follows: For each edge relation type defined in the original program semantic knowledge graph, a first summation operation is performed. The first summation operation is to multiply the feature vector of each neighboring node of the target node under that edge relation type after transformation by the corresponding linear transformation matrix of that edge relation type by the attention weight of that neighboring node to the target node under that relation type, and then add all such product results to obtain the first summation result under that edge relation type; then, a second accumulation operation is performed. The second accumulation operation is to accumulate the first summation results calculated for each edge relation type defined in the original program semantic knowledge graph to obtain a comprehensive aggregation vector.
[0097] Finally, the aggregated vector is input into the exponential linear unit activation function to obtain a new feature representation of the target node. After multiple iterations, usually 2 to 4 layers, an enhanced semantic representation of each syntactic entity in the original program semantic knowledge graph is obtained, which incorporates multi-hop and multi-relation context.
[0098] The process of generating an intention symbolic map specifically includes:
[0099] Based on enhanced semantic representation, a multi-hop inference unit is used to complete higher-order semantic relations. The multi-hop inference unit predefines a set of meta-path templates, such as "function A → (call) → function B → (trigger) → exception C", or "variable X ← (defined in) - function Y → (data flow) → variable Z". The meta-path templates represent the higher-order semantic relation patterns to be inferred (such as "indirectly triggering exceptions" or "data from the same source"). In the original program semantic knowledge graph, path instances that meet the conditions are searched for node pairs composed of syntactic entities and meta-path templates, and a path inference score is calculated for each found path instance. The path inference score calculation process is as follows: For a given path instance connecting a starting node and a target node, the path instance consists of a series of edges and intermediate nodes. First, a semantic compatibility evaluation value between the starting node and the target node is calculated. This value is obtained by using an enhanced semantic representation vector of the starting node and the target node. The enhanced semantic representation vector is obtained as input to a function, which can be the dot product of vectors or a multilayer perceptron. Next, a path support product is calculated for each edge in the path instance and its next connected node. For each edge, a support value is calculated, obtained from a function that takes the edge type and the enhanced semantic representation vector of the node it points to as input. This function can be calculated by querying a predefined relation type weight table and combining it with the dot product of node vectors. Then, the support values corresponding to all edges in the path instance are multiplied to obtain the path support product. Finally, the semantic compatibility evaluation value is multiplied by the path support product to obtain the path inference score. If the path inference score exceeds a preset threshold, such as 0.7 (which can be adjusted on the validation set), a new edge representing the higher-order semantic relation is added between the corresponding node pairs in the graph.
[0100] Subsequently, the completed graph with enhanced semantic representation is subjected to intent clustering. The set of syntactic entities realizing a common functional intent is abstracted into symbolic intent units, which are abstract semantic nodes representing high-level functional intents. The clustering process is implemented using a differentiable sparse clustering algorithm. This algorithm includes a set of learnable parameters, including a weight matrix and bias vector of a fully connected neural network layer for mapping the enhanced semantic representation vector to the intent space, and multiple prototype vectors representing the center positions of the symbolic intent units. The algorithm calculates sparse weights for each syntactic entity to one or more prototype vectors of symbolic intent units according to the following rules: For a given syntactic entity, first, the representation vector of the syntactic entity in the intent space is obtained; then, the squared Euclidean distance between the syntactic entity's representation vector and the prototype vector of each symbolic intent unit is calculated; finally, the weights of each distance are... Multiplying the square of the distance by a negative temperature coefficient and taking the natural exponential function value yields a series of initial assignment values. The temperature coefficient β is a positive-zero adjustable hyperparameter, which can also be set as a learnable parameter. A typical initial value can be set to 1.0, and it can be learned during training or manually adjusted to control the clustering granularity. The larger the β value, the sparser the generated assignment weights. Finally, for the prototype vector of each symbolic intent unit, its corresponding initial assignment value is divided by the sum of the initial assignment values corresponding to the prototype vectors of all symbolic intent units. The result is the sparse assignment weight from the grammatical entity to the symbolic intent unit. The prototype vector of the symbolic intent unit is a learnable parameter vector, and each prototype vector corresponds to a symbolic intent unit to be abstracted. The temperature coefficient is a positive-zero adjustable parameter used to control the sparsity of the assignment weights. The larger its value, the more the calculated assignment weights tend to concentrate on a single symbolic intent unit.
[0101] Finally, based on the sparse allocation weights, the following operations are performed to generate the intent symbolization graph: First, syntactic entities with significant sparse allocation weights are classified into their corresponding symbolic intent units. Typically, syntactic entities with a maximum allocation weight greater than 0.5 are considered to belong to that intent unit, and each symbolic intent unit serves as a node in the intent symbolization graph. Then, the feature vector of each symbolic intent unit is formed by weighting and aggregating the enhanced semantic representation vectors of all its member syntactic entities according to their corresponding sparse allocation weights, i.e., by weighted averaging. Simultaneously, the weight of the connection edge between two symbolic intent units is obtained by accumulating the strengths of all connections between all member syntactic entities belonging to these two symbolic intent units in the completed graph, and then weighting them according to the sparse allocation weights.
[0102] In this embodiment, it is specifically necessary to describe the process by which the structure-aware cross-modal Transformer model encodes and fuses the intent symbolic graph in the generation and alignment module, which includes:
[0103] First, load the intent symbolization graph, obtain the feature vectors of all symbolized intent units in the graph and the connection relationships between units. The feature vectors are the feature vectors corresponding to each symbolized intent unit output from the semantic reasoning and symbolization module.
[0104] Next, node feature enhancement is performed: For each symbolic intent unit in the intent symbolization graph, its feature vector is used as the initial feature. Utilizing the connections between units, it is processed through a graph convolutional network layer, so that the updated feature vector of each symbolic intent unit incorporates the feature information of its directly neighboring units, resulting in an enhanced node feature vector. The graph convolutional network contains learnable parameters, such as the weight matrix of the graph convolutional kernel. The graph convolutional network can be implemented using a single layer of a graph convolutional network or a graph attention network, and its aggregation function is the mean or weighted sum of the feature vectors of neighboring nodes.
[0105] Subsequently, a structural location encoding vector is generated: For the intent symbolization graph, multiple node sequences are generated through random walk sampling. Based on these node sequences, a fixed vector representation is learned for each symbolic intent unit in the intent symbolization graph using a language model training method. This vector representation captures the role of the corresponding symbolic intent unit in the overall topological structure of the intent symbolization graph and is called the structural location encoding vector. The parameters of the random walk sampling include the walk length and the number of walks starting from each node. For example, the walk length is set to 40, and each node is walked 10 times. The language model training method can use the Skip-gram model.
[0106] Next, serialization and vector concatenation are performed: all symbolic intent units are sorted according to a preset rule; the preset rule can be sorting in descending order based on the magnitude of the feature vector of the symbolic intent unit, or sorting according to the topology of the graph, to form an input sequence; for each symbolic intent unit in the input sequence, its enhanced node feature vector, the corresponding structural position encoding vector, and a standard sine position encoding vector calculated based on the position of the unit in the input sequence are concatenated to construct the final input feature vector of the unit;
[0107] The final input feature vectors of all symbolic intent units arranged in this order are combined to form an input sequence, which is then input into the encoder part of the structure-aware cross-modal Transformer model. The structure-aware cross-modal Transformer model contains a large number of learnable parameters, including the query, key, and value linear transformation matrices of the self-attention and cross-attention modules in each layer of its encoder and decoder, the weight matrix and bias vector of the feedforward neural network, and the weight matrix and bias vector of the learnable alignment-gated linear transformation layer. During the self-attention calculation process of the encoder, a structural bias matrix is introduced. The dimension of the structural bias matrix corresponds to the number of symbolic intent units in the input sequence, and the value of each element is determined according to the following rule: In the symbolic intent graph, find the shortest path distance between the two symbolic intent units corresponding to that element; determine the shortest path distance... Whether the path distance is less than or equal to a preset maximum perceptual distance, which is usually set to 2 or 3; if yes, the value of this element is equal to the common logarithm of the result obtained by adding one to the reciprocal of the shortest path distance; if no, the value of this element is set to a special value representing negative infinity; "shortest path distance" refers to the minimum number of connecting edges required to reach one symbolic intent unit node from another in the topological structure of the intent symbolization graph; "maximum perceptual distance" is a preset positive integer threshold used to limit the range of structure perception; the structure bias matrix is added as a bias term in the encoder's self-attention score calculation, thereby injecting structural information of the intent symbolization graph into the attention weight allocation, enabling the model to perceive the topological proximity relationship between units and encode a symbolic intent unit representation sequence that incorporates structural semantics;
[0108] The process of generating a draft of a natural language description using a dual attention alignment mechanism specifically includes:
[0109] Based on a sequence of symbolic intent unit representations incorporating structural semantics, a draft of a natural language description is generated in an autoregressive manner using the decoder portion of a structure-aware cross-modal Transformer model; at each time step of the decoder, dual attention alignment computation is performed.
[0110] The first layer is intent cohesive attention, which, within the decoder's self-attention layer, uses a structural bias matrix to correct the original attention score generated during the decoder's self-attention calculation. The original attention score is calculated from the decoder's query vector and key vector, ensuring that when generating descriptions, the model gives higher attention weight to topologically similar symbolic intent units in the graph, thus maintaining the consistency between the logical structure of the description text and the graph structure. This mechanism effectively prevents serious misalignment between the generated description paragraph order and the functional flow of the graph.
[0111] The second layer is the description-generation alignment attention, which sets a learnable alignment gate value in the decoder's cross-attention layer. This learnable alignment gate value is dynamically calculated at each time step according to the following rules: First, obtain the query vector of the decoder at the current time step; simultaneously, obtain the sequence of hidden state representation vectors corresponding to the partially generated descriptive text in all previous time steps, and calculate the average of all vectors in this sequence to obtain the context vector of the generated text; next, concatenate the query vector with the context vector of the generated text to form a combined vector; then, input the combined vector into a linear transformation layer for processing, which contains a learnable weight matrix and bias vector; finally, input the output of the linear transformation layer into a Sigmoid function for mapping, constraining the result to between zero and one. This result is the alignment gate value for the current time step; the Sigmoid function ensures that the gate value has a clear probabilistic interpretation, facilitating optimization during training.
[0112] The description generation process utilizes an alignment gating value to dynamically mix context vectors from two information sources to generate the vocabulary for the current time step: the first information source is a first context vector obtained by cross-attention calculation based on a sequence of symbolic intent unit representations that incorporate structural semantics; the second information source is a second context vector obtained by cross-attention calculation based on a sequence of hidden state representation vectors of the generated partial description text; the mixed context vector used for the final vocabulary generation is equal to the alignment gating value multiplied by the first context vector, plus a result of subtracting the alignment gating value and multiplying by the second context vector; the decoder predicts the vocabulary for the current time step based on the mixed context vector and adds it to the end of the generated sequence, repeating this process until a complete end marker is generated, at which point the complete vocabulary sequence is the initial draft of the natural language description; the autoregressive generation process can use a bundle search algorithm, with the bundle width set to 4 to 8;
[0113] The entire generation process is trained and optimized by minimizing a combined loss function, called the total loss. This combined loss function is the sum of a standard sequence generation loss and a semantic alignment constraint loss multiplied by a preset positive weighting coefficient. The positive weighting coefficient balances the contributions of the two losses and can be set through cross-validation, for example, to 0.5. The standard sequence generation loss is the negative log-likelihood loss of word prediction during autoregressive generation. The semantic alignment constraint loss is calculated according to the following rules: First, a pre-trained language model is used to process the text identifiers of each symbolic intent unit in the natural language description draft and the intent symbolization graph, respectively, to obtain the corresponding overall description semantic vector and multiple symbolic intent unit semantic vectors. The pre-trained language model can be BERT, Sentence-BERT, or a similar model. The text identifier is the name or key attribute text of the symbolic intent unit. Next, the cosine similarity between the overall description semantic vector and the semantic vector of each symbolic intent unit is calculated. Then, for each symbolic intent unit in the intent symbolization graph, a contrastive loss term is calculated, which is the ratio of the overall description semantic vector to the semantic vector of that symbolic intent unit. The cosine similarity between the semantic vectors is divided by a temperature coefficient (greater than zero) as a natural exponential function value. The temperature coefficient controls the smoothness of the probability distribution and is typically set to a decimal between 0.05 and 0.1. This is then divided by a summation, which is the sum of the natural exponential function values of the cosine similarity between the overall semantic vector and the semantic vector of the symbolic intent unit, as well as between the overall semantic vector and each semantic vector in a negative sample semantic vector set, divided by the temperature coefficient. Finally, the negative natural logarithm of this ratio is taken. The negative sample semantic vector set consists of other intention symbolic graphs within the same training batch, excluding the current intention symbolic graph. The semantic vectors of the symbolic intent units are used to construct the semantics. This contrastive loss makes the overall semantics of the generated description closer to the correct intent unit and more distant from other irrelevant intent units in the batch. Finally, the contrastive loss terms of all symbolic intent units are summed to obtain the semantic alignment constraint loss. In the model inference stage, in addition to the parameters obtained by training the loss function, the statistical features of the alignment gating value (such as the average gating value when describing key terms) can also be used as a soft indicator. In the cluster search, candidate sequences with higher gating values in the key term generation step are given priority to further ensure the fidelity of the description to the graph semantics.
[0114] In this embodiment, it is specifically necessary to explain that in the feedback learning and optimization module, the process by which the semantic feedback parser transforms the actual execution result of the MCP service call into a semantic feedback signal includes:
[0115] Real-time monitoring is performed on every call to the MCP service, constructed based on the initial draft of the natural language description. The complete execution trajectory information is recorded, including at least the returned functional result, the actual values of the input parameters, whether any exceptions were triggered during the call and the exception information text, and the execution time. Based on the recorded execution trajectory information, a multi-dimensional, fine-grained semantic feedback signal vector is constructed. Each dimension of this vector corresponds to a preset semantic feedback type, and its value is calculated according to the evaluation rules of the corresponding semantic feedback type. The semantic feedback types include functional correctness dimension, parameter matching degree dimension, exception semantic relevance dimension, and performance degradation dimension. The value of the functional correctness dimension is determined by comparing the actual returned functional result with the expected correct result based on the target program code. Its value is 1 or 0, representing functional correctness and error, respectively. The expected correct result can be obtained in advance by running the target program code in an isolated environment and verifying the output, or through formal verification, test case libraries, etc. The value of the parameter matching degree dimension is determined by analyzing the compatibility between the actual value type of the input parameters and the parameter types declared by the corresponding interface of the target program code. The value is a real number between 0 and 1; compatibility calculation can be based on a type system, for example, a perfect match is 1.0, a safe implicit type conversion (such as integer to floating-point) is 0.7, and type incompatibility is 0; the value of the anomaly semantic relevance dimension is obtained by calculating the negative semantic similarity between the anomaly information text and the functional intent described in the initial draft of the natural language description, and its value is a non-positive real number; specifically, a pre-trained sentence embedding model (such as Sentence-BERT) is used to encode the anomaly information text and the functional intent description text to obtain vectors, and the two are calculated. The cosine similarity is negative, with lower similarity (less relevant) resulting in a more negative value, indicating that the anomaly may not match the description or that the description is misleading. The performance degradation dimension is determined by comparing the actual call time with a preset baseline time threshold. Its value is a non-negative real number representing the proportion by which the actual time exceeds the baseline threshold. The baseline time threshold can be determined based on the historical average execution time of the target program code in a standard test environment or through performance profiling, for example, set to 1.2 times the historical average time. The final generated semantic feedback signal vector serves as the input for subsequent credit allocation and optimization strategies.
[0116] The specific process of adjusting the parameters of the cascaded model in the semantic reasoning and symbolization module and the parameters of the structure-aware cross-modal Transformer model in the description generation and alignment module based on this signal is as follows:
[0117] First, the semantic feedback signal vector is input into a credit allocation network. This network takes as input the intermediate representations of the original program semantic knowledge graph and intent symbolization graph upon which the currently invoked MCP service is based, and outputs a two-dimensional credit allocation vector. This credit allocation vector contains two elements, both of which are non-negative real numbers and sum to one. The first element represents the proportion of responsibility attributable to the semantic reasoning and symbolization modules for the current feedback signal, and the second element represents the proportion of responsibility attributable to the description generation and alignment modules. The credit allocation network is typically a multilayer perceptron, whose input is the aggregated features of the intermediate graph representation (such as the global average pooling features of the graph), and the output layer uses a Softmax activation function to ensure that the sum of the two elements is one. Simultaneously, the semantic feedback signal vector... A scalar reward value is synthesized through a pre-defined reward function. The calculation process of the reward function is as follows: First, the semantic feedback signal vector is input into a non-linear transformation function for processing. The non-linear transformation function is used to map each component of the vector to a uniform numerical range. For example, the Tanh function is used to map each dimension to the interval [-1, 1]. Then, the transformed vector is subjected to a dot product operation with a pre-defined weight vector. Each component of the weight vector corresponds to a dimension of the semantic feedback signal vector, representing the importance of the feedback type in that dimension. This weight vector can be pre-defined based on domain knowledge (e.g., functional correctness has the highest weight) or can be adjusted during training as a learnable parameter. The result of the dot product operation is the scalar reward value, which is constrained within a pre-defined bounded interval, such as between -1 and +1.
[0118] Next, based on the credit allocation vector, the scalar reward value is decomposed into two hierarchical reward values corresponding to the semantic reasoning and symbolization module and the description generation and alignment module, respectively. The specific calculation of the decomposition is as follows: multiply the scalar reward value by the value of the first element of the credit allocation vector to obtain the hierarchical reward value corresponding to the semantic reasoning and symbolization module; multiply the scalar reward value by the value of the second element of the credit allocation vector to obtain the hierarchical reward value corresponding to the description generation and alignment module.
[0119] Then, the semantic feedback signal vector, historical statistics of hierarchical reward values, and gradient statistics of the cascaded model and the structure-aware cross-modal Transformer model during recent training are input into the policy network. These inputs together constitute the context upon which the policy network bases its decisions, i.e., the current state information of the system. Historical statistics may include the moving average of the hierarchical reward values of each module obtained from the past N (e.g., 100) calls. Gradient statistics may include the mean or variance of the L2 norm of the gradients of the model parameters in recent training steps. The policy network is trained using a proximal policy optimization algorithm, whose output is a suggestion for adjusting the hyperparameters of the optimizer for the cascaded model and the structure-aware cross-modal Transformer model. The adjustment suggestion is a specific parameter adjustment amount or proportion, such as a scaling factor for the learning rate. The scaling factor can be set between [0.5, 2.0]. The proximal policy optimization algorithm updates the learnable parameters of the policy network by minimizing an alternative objective function. The calculation rules for the alternative objective function are as follows: First, a probability ratio is calculated, which is the conditional probability of the policy network outputting adjustment suggestions under the current learnable parameters and given system state information, and the probability ratio of the policy network outputting adjustment suggestions. Given previously learnable parameters, the conditional probability of outputting the same adjustment suggestion under the same state is calculated as the ratio of the two. Next, an advantage function estimate is obtained, which evaluates the additional expected cumulative reward of taking the adjustment suggestion relative to taking the average action in a given state. The advantage function estimate is typically calculated from a series of reward values using a generalized advantage estimation algorithm. Then, two product terms are calculated: the first is the product of the probability ratio and the advantage function estimate, and the second is the product of a pruned probability ratio and the advantage function estimate. The pruning operation restricts the probability ratio to a lower bound and a lower limit. Within the closed interval defined by the upper limit, the lower limit is 1 minus a small positive hyperparameter, and the upper limit is 1 plus that small positive hyperparameter. The small positive hyperparameter ε is usually set to a value between 0.1 and 0.3, such as 0.2. Then, the smaller value between the first product term and the second product term is taken. Finally, the expectation of this smaller value is calculated from the data obtained from multiple interactions, and this expectation value is the value of the substitute objective function. The algorithm updates the learnable parameters of the policy network by minimizing the negative value of this substitute objective function, so as to encourage the exploration of new adjustment policies while strictly limiting the magnitude of a single learnable parameter update, thus ensuring the stability of the training process.
[0120] Finally, a progressive knowledge distillation strategy is employed to apply the adjustment suggestions, thereby stably updating the learnable parameters within the cascaded model and the structure-aware cross-modal Transformer model. The implementation process of the progressive knowledge distillation strategy is as follows: First, a teacher model and a student model are defined. The teacher model refers to the currently deployed online model, consisting of the cascaded model in the semantic reasoning and symbolization module and the structure-aware cross-modal Transformer model in the description generation and alignment module. The student model is a structurally complete copy of the teacher model, and its initial, internal learnable parameters (including the linear transformation matrix, attention vector, and prototype vector in the cascaded model, and the weight matrix, bias vector, and gating parameters in the structure-aware cross-modal Transformer model) are completely copied from the teacher model's current learnable parameters. Next, on the student model, based on the adjustment suggestions output by the policy network, its learnable parameters are optimized offline in multiple steps by minimizing a combined loss function. The combined loss function is independent for both the semantic reasoning and symbolization module and the description generation and alignment module. The calculation and optimization process involves the following steps: For the combined loss function of the semantic reasoning and symbolization modules, the value is obtained by weighted summation of the first loss term (the negative value corresponding to the hierarchical reward value of the semantic reasoning and symbolization modules) and the second loss term (a KL divergence measure for the difference in output distribution between the cascaded models in the student model and the corresponding models in the teacher model under the same input conditions). "Given the same input conditions" typically refers to using the same target program code as input. For the combined loss function of the description generation and alignment modules, the value is obtained by weighted summation of the first loss term (the negative value corresponding to the hierarchical reward value of the description generation and alignment modules) and the second loss term (a KL divergence measure for the difference in output distribution between the structure-aware cross-modal Transformer model in the student model and the corresponding model in the teacher model under the same input conditions). The output distribution differences of the two modules are calculated in their respective output spaces. For example, the output of the cascaded model is the node features of the intent symbolization graph, while the output of the Transformer model is the vocabulary probability distribution of the initial draft of the natural language description.
[0121] In each optimization iteration, based on the numerical value of the responsibility ratio in the credit allocation vector, the semantic reasoning and symbolization module or the description generation and alignment module are selected to perform the above knowledge distillation optimization. Specifically, a responsibility ratio threshold (e.g., 0.6) is set. When the responsibility ratio of a certain module exceeds the threshold, the distillation optimization of the current round is performed preferentially or only on that module. If neither exceeds the threshold, optimization can be performed simultaneously or alternately. In the combined loss function, the first loss term is multiplied by a first balancing coefficient, and the second loss term is multiplied by a second balancing coefficient. Both the first and second balancing coefficients are adjustable hyperparameters with a value greater than zero, used to control the relative importance between feedback reward-driven optimization and the preservation of original knowledge. The typical initial values of the first and second balancing coefficients can be set to 1.0 and 0.1, respectively, and can be adjusted during training based on the performance of the validation set.
[0122] Then, the learnable parameters of the optimized and stable student model are synchronized back to the corresponding cascaded model and structure-aware cross-modal Transformer model in the online teacher model, thereby completing the stable adjustment of the learnable parameters of the cascaded model and structure-aware cross-modal Transformer model; the stability criterion can be that the evaluation indicators of the student model on the retained validation set (such as the service call success rate) no longer decrease or begin to increase.
[0123] It should be noted that the descriptions of each embodiment in the above embodiments have different focuses. For parts that are not described in detail in a certain embodiment, please refer to the relevant descriptions in other embodiments.
[0124] Those skilled in the art will understand that embodiments of the present invention can be provided as methods, systems, or computer program products. Therefore, the present invention can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, the present invention can take the form of a computer program product embodied on one or more computer-usable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0125] This invention is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of the invention. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded computer, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart illustrations. Figure 1 One or more processes and / or boxes Figure 1A device that provides the functions specified in one or more boxes.
[0126] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0127] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0128] Although preferred embodiments of the invention have been described, those skilled in the art, upon learning the basic inventive concept, can make other changes and modifications to these embodiments. Therefore, the appended claims are intended to be interpreted as including both the preferred embodiments and all changes and modifications falling within the scope of the invention.
[0129] Obviously, those skilled in the art can make various modifications and variations to this invention without departing from its spirit and scope. Therefore, if these modifications and variations fall within the scope of the claims of this invention and their equivalents, this invention also intends to include these modifications and variations.
Claims
1. An automatic MCP service generation system based on program semantic understanding, characterized in that, Specifically, it includes: The module is sequentially connected to the data extraction and graph construction module, the semantic reasoning and symbolization module, the description generation and alignment module, and the feedback learning and optimization module, among which; Data extraction and graph construction module: In response to receiving the target program code, the module extracts the syntactic structure information, runtime trajectory information and associated document information of the target program code through a static semantic analyzer, dynamic behavior analyzer and context information collector executed in parallel. The module then integrates these three types of heterogeneous information to construct an original program semantic knowledge graph containing multiple node types and edge relationships. Semantic Reasoning and Symbolization Module: By loading the original program semantic knowledge graph generated by the data extraction and graph construction module, and using a cascaded model containing heterogeneous graph neural networks and multi-hop reasoning units, the module performs cross-level message passing and semantic relationship reasoning on the nodes and edges in the original program semantic knowledge graph, identifies the high-level logical units that represent the program's functional intent, and generates an intent symbolization graph with nodes as symbolized intent units. Description generation and alignment module: Through a structure-aware cross-modal Transformer model, the intention symbolic graph generated by the semantic reasoning and symbolization module is used as input, and a dual attention alignment mechanism is adopted to generate a natural language description draft corresponding to the symbolic intention units in the intention symbolic graph; Feedback Learning and Optimization Module: By deploying a semantic feedback parser and a policy network, it monitors in real time the execution results of the MCP service built based on the initial natural language description generated by the description generation and alignment module in actual calls, converts it into semantic feedback signals, and adjusts the parameters of the cascaded model in the semantic reasoning and symbolization module and the parameters of the structure-aware cross-modal Transformer model in the description generation and alignment module based on these semantic feedback signals.
2. The MCP service automatic generation system based on program semantic understanding according to claim 1, characterized in that: In the data extraction and graph construction module, the extraction and preprocessing of three types of heterogeneous information by the static semantic analyzer, dynamic behavior analyzer, and context information collector specifically includes: The static semantic analyzer performs lexical and syntactic analysis on the target program code, generates an abstract syntax tree, and performs data flow and dependency analysis based on the abstract syntax tree to extract a static semantic metadata set consisting of syntactic entities and their structural relationships. The static semantic metadata set contains multiple first elements, each of which represents a syntactic entity and its attributes. In an isolated sandbox environment, the dynamic behavior analyzer drives the execution of the target program code through a set of pre-defined test cases, and uses instrumentation techniques to capture function call sequences, parameter passing, return values and exception events, forming a dynamic behavior metadata set that records the program's runtime behavior. The dynamic behavior metadata set contains multiple second elements, each of which represents a runtime event or state snapshot. The context information collector scans the project directory and associated version control system of the target program code, extracts build configuration files, dependency library lists, application interface document fragments and version commit logs to form a context semantic metadata set. The context semantic metadata set contains multiple third elements, each of which represents a descriptive text.
3. The MCP service automatic generation system based on program semantic understanding according to claim 2, characterized in that: The process of fusing three types of heterogeneous information to construct an original program semantic knowledge graph is as follows: First, based on the syntactic entities in the static semantic metadata set, a graph skeleton containing nodes and syntactic relation edges is initialized, where nodes correspond to syntactic entities; Subsequently, a fusion algorithm based on evidence theory was adopted to fuse information from the dynamic behavior metadata set and the context semantic metadata set into the graph skeleton as evidence. The fusion algorithm calculates a comprehensive confidence score for each node in the graph skeleton. The comprehensive confidence score is jointly determined by the first calculation term and the second calculation term. The calculation process of the first calculation term is as follows: From the dynamic behavior metadata set, a subset of dynamic behavior evidence that supports the current node being judged to have a core functional status is selected. For each dynamic behavior evidence in the subset of evidence, its own weight is multiplied by a correlation strength function value. The above multiplication results of all supporting dynamic behavior evidence are accumulated to obtain the base value of the first calculation term. The second calculation term is the average similarity contribution value between the semantic vectors of all context description fragments related to this node and the node vector. The semantic vector is obtained by performing an embedding model transformation on the descriptive text in the context semantic metadata set, and the node vector is obtained by performing the same embedding model transformation on the identifier text of the grammatical entity corresponding to this node. The average similarity contribution value is obtained by calculating the cosine similarity between the node vector and the semantic vector of each related context description fragment and taking the average value. The fusion algorithm also sets a total evidence normalization factor, which is used to scale and merge the base value of the first calculation item and the average similarity contribution value of the second calculation item. The overall confidence level is the result after processing by the total evidence normalization factor. Finally, the graph skeleton, the comprehensive confidence scores of each node calculated by the fusion algorithm, and the descriptive text extracted from the context semantic metadata set are integrated to generate the original program semantic knowledge graph; wherein, the original program semantic knowledge graph includes: A set of nodes whose elements are syntactic entities defined in a static semantic metadata set; The edge set consists of connection relationships defined based on structural relationships in the static semantic metadata set, associations in the dynamic behavioral metadata set, and semantic associations. The attribute set consists of attribute information attached to the elements in the node set and the edge set. The attribute information includes the overall confidence level, the type of the syntactic entity, and the descriptive text extracted from the context semantic metadata set.
4. The MCP service automatic generation system based on program semantic understanding according to claim 3, characterized in that: In the semantic reasoning and symbolization module, the process of cross-level message passing and semantic relationship reasoning of nodes and edges in the original program's semantic knowledge graph is as follows: First, the original program semantic knowledge graph is loaded, and for each element in the node set of the original program semantic knowledge graph, i.e. the grammatical entity, an initial feature vector is constructed. The initial feature vector is composed of type information, comprehensive confidence and embedding vector of the descriptive text from the attribute set of the original program semantic knowledge graph corresponding to the grammatical entity. Subsequently, a multi-relation graph attention network is used to encode the original program semantic knowledge graph. The multi-relation graph attention network contains a set of learnable parameters, defining independent learnable parameters for each type of edge relation in the original program semantic knowledge graph. The learnable parameters include a linear transformation matrix for feature transformation and an attention vector for calculating attention weights. These learnable parameters are randomly initialized at the beginning of model training and optimized using gradient descent through an optimizer and its hyperparameters during training. During information transmission, for each grammatical entity that serves as the target node, the attention weights of each of its neighboring nodes under different relation types are calculated. The calculation process of the attention weights is as follows: for a neighboring node connected to the target node through a given type of edge relation, the linear transformation matrix corresponding to the type of edge relation is first used to transform the current layer feature vector of the target node and the current layer feature vector of the neighboring node respectively. Next, the two transformed feature vectors are concatenated to form a combined vector; Then, the dot product of the transpose of the attention vector corresponding to this type of edge relationship and the combined vector is calculated, and the dot product result is input into a non-linear activation function for processing to obtain an original attention score; finally, the original attention score is exponentially normalized relative to the original attention scores of all neighboring nodes connected to the target node through the same type of edge relationship, and the result is the attention weight of the neighboring node to the target node under this relationship type. Next, the target node updates its feature representation by weighting and aggregating the feature information of all its neighboring nodes after transformation by the corresponding linear transformation matrix under all relation types according to the attention weight. After multiple iterations, the enhanced semantic representation of each syntactic entity in the original program semantic knowledge graph is obtained by integrating multi-hop and multi-relation context.
5. The MCP service automatic generation system based on program semantic understanding according to claim 4, characterized in that: The process of generating the intention symbolic map specifically includes: Based on the enhanced semantic representation, higher-order semantic relations are completed using a multi-hop inference unit. This multi-hop inference unit predefines a set of meta-path templates, which represent the higher-order semantic relation patterns to be inferred. In the original program semantic knowledge graph, path instances matching the conditions are searched for node pairs composed of syntactic entities and meta-path templates. A path inference score is calculated for each found path instance. The calculation process for the path inference score is as follows: For a given path instance connecting a starting node and a target node, the path instance consists of a series of edges and intermediate nodes. First, a semantic compatibility evaluation value between the starting node and the target node is calculated. This value is obtained by using an enhanced semantic representation vector of the starting node and... The enhanced semantic representation vector of the target node is obtained by inputting a function; next, a path support product is calculated, which is performed on each edge in the path instance and the next node it connects to. For each edge, a support value is calculated, which is obtained by inputting a function with the type of the edge and the enhanced semantic representation vector of the node the edge points to. Then, the support values corresponding to all edges in the path instance are multiplied to obtain the path support product; finally, the semantic compatibility evaluation value is multiplied by the path support product to obtain the path inference score; if the path inference score exceeds a preset threshold, a new edge representing the higher-order semantic relationship is added between the corresponding node pairs in the graph. Subsequently, the completed graph with the enhanced semantic representation is subjected to intent clustering. The set of syntactic entities that realize a common functional intent is abstracted into symbolic intent units, which are abstract semantic nodes representing high-level functional intents. The clustering process is implemented through a differentiable sparse clustering algorithm, which includes a set of learnable parameters, including a weight matrix and bias vector of a fully connected neural network layer for mapping the enhanced semantic representation vector to the intent space, and multiple prototype vectors representing the center positions of symbolic intent units. The prototype of each syntactic entity is calculated to one or more symbolic intent units according to the following rules. Sparse allocation weights for vectors: For a given syntactic entity, first, obtain the representation vector of the syntactic entity in the intent space; then, calculate the square of the Euclidean distance between the representation vector of the syntactic entity and the prototype vector of each symbolic intent unit; next, multiply the square of each distance by a negative temperature coefficient and take the natural exponential function value to obtain a series of initial allocation values; finally, for the prototype vector of each symbolic intent unit, divide its corresponding initial allocation value by the sum of the initial allocation values corresponding to the prototype vectors of all symbolic intent units, and the result is the sparse allocation weight from the syntactic entity to the symbolic intent unit. Finally, based on the sparse allocation weights, the following operations are performed to generate the intent symbolization graph: First, syntactic entities with significant sparse allocation weights are classified into corresponding symbolic intent units, with each symbolic intent unit serving as a node in the intent symbolization graph; then, the feature vector of each symbolic intent unit is aggregated from the enhanced semantic representation vectors of all its member syntactic entities according to their corresponding sparse allocation weights; simultaneously, the weight of the connection edge between two symbolic intent units is obtained by accumulating the strengths of all connections existing in the completed graph between all member syntactic entities belonging to these two symbolic intent units, and then weighting them according to the sparse allocation weights.
6. The MCP service automatic generation system based on program semantic understanding according to claim 5, characterized in that: In the description generation and alignment module, the process of encoding and fusing the intent symbolization graph by the structure-aware cross-modal Transformer model specifically includes: First, load the intent symbolization graph, obtain the feature vectors of all symbolized intent units in the graph and the connection relationships between units. The feature vectors are the feature vectors corresponding to each symbolized intent unit output from the semantic reasoning and symbolization module. Next, node feature enhancement is performed: for each symbolic intent unit in the intent symbolization graph, its feature vector is used as the initial feature. Using the connection relationship between units, it is processed through a graph convolutional network layer, so that the updated feature vector of each symbolic intent unit incorporates the feature information of its directly adjacent units, resulting in the enhanced node feature vector. Subsequently, a structural location encoding vector is generated: For the intent symbolization graph, multiple node sequences are generated through random walk sampling, and based on these node sequences, a fixed vector representation, called the structural location encoding vector, is learned for each symbolic intent unit in the intent symbolization graph using a language model training method. Next, serialization and vector concatenation are performed: all symbolic intent units are sorted according to preset rules to form an input sequence; for each symbolic intent unit in the input sequence, its enhanced node feature vector, the corresponding structural position encoding vector, and a standard sinusoidal position encoding vector calculated based on the position of the unit in the input sequence are concatenated to construct the final input feature vector of the unit. The final input feature vectors of all symbolic intent units arranged in this order are combined to form an input sequence, which is then input into the encoder part of the structure-aware cross-modal Transformer model. The structure-aware cross-modal Transformer model contains a large number of learnable parameters, including the query, key, and value linear transformation matrices of the self-attention and cross-attention modules in each layer of its encoder and decoder, the weight matrix and bias vector of the feedforward neural network, and the weight matrix and bias vector of the learnable alignment-gated linear transformation layer. During the self-attention calculation of the encoder, a structural bias matrix is introduced, and the value of each element is determined according to the following rule: in the intention symbolization graph, the shortest path distance between the two symbolic intent units corresponding to the element is found. The structural bias matrix is used as a bias term in the self-attention score calculation of the encoder, thereby injecting the structural information of the intention symbolization graph into the attention weight allocation, enabling the model to perceive the topological proximity relationship between units and encode a symbolic intent unit representation sequence that incorporates structural semantics.
7. The MCP service automatic generation system based on program semantic understanding according to claim 6, characterized in that: The process of generating the initial draft of the natural language description using a dual attention alignment mechanism specifically includes: Based on a sequence of symbolic intent unit representations incorporating structural semantics, a draft of a natural language description is generated in an autoregressive manner using the decoder portion of a structure-aware cross-modal Transformer model; at each time step of the decoder, dual attention alignment computation is performed. The first layer is intentional cohesive attention, which uses the structural bias matrix in the decoder self-attention layer to correct the original attention score generated in the decoder self-attention calculation. The second layer is the description generation alignment attention, which sets a learnable alignment gate value in the decoder cross-attention layer. The learnable alignment gate value is dynamically calculated at each time step according to the following rules: First, obtain the query vector of the decoder at the current time step; simultaneously, obtain the sequence of hidden state representation vectors corresponding to the partially generated description text of the decoder in all previous time steps, and calculate the average of all vectors in the sequence to obtain the context vector of the generated text; next, concatenate the query vector with the context vector of the generated text to form a combined vector; then, input the combined vector into a linear transformation layer for processing, the linear transformation layer contains a learnable weight matrix and bias vector; finally, input the output of the linear transformation layer into a sigmoid function for mapping, constraining the result to between zero and one, and this result is the alignment gate value of the current time step. The description generation process utilizes alignment gating values to dynamically blend context vectors from two information sources to generate the vocabulary for the current time step: the first information source is a first context vector obtained by cross-attention calculation based on a sequence of symbolic intent unit representations that incorporate structural semantics; the second information source is a second context vector obtained by cross-attention calculation based on a sequence of hidden state representation vectors from the generated partial description text; the blended context vector used for the final vocabulary generation is equal to the alignment gating value multiplied by the first context vector, plus a result of subtracting the alignment gating value and multiplying by the second context vector; the decoder predicts the vocabulary for the current time step based on the blended context vector and adds it to the end of the generated sequence, repeating this process until a complete end marker is generated, at which point the complete vocabulary sequence is the initial draft of the natural language description; The entire generation process is trained and optimized by minimizing a combined loss function, called the total loss. The value of the combined loss function is the sum of a standard sequence generation loss and a semantic alignment constraint loss multiplied by a preset positive weighting coefficient.
8. The MCP service automatic generation system based on program semantic understanding according to claim 7, characterized in that: In the feedback learning and optimization module, the process by which the semantic feedback parser transforms the actual execution result of the MCP service call into a semantic feedback signal specifically includes: Real-time monitoring is performed on every call to the MCP service constructed based on the initial draft of the natural language description, recording its complete execution trajectory information. Based on the recorded execution trajectory information, a multi-dimensional, fine-grained semantic feedback signal vector is constructed. Each dimension of this vector corresponds to a preset semantic feedback type, and its value is calculated according to the evaluation rules of the corresponding semantic feedback type. The semantic feedback type includes functional correctness dimension, parameter matching degree dimension, abnormal semantic relevance dimension, and performance degradation dimension. The final generated semantic feedback signal vector serves as the input for subsequent credit allocation and optimization strategies.
9. The MCP service automatic generation system based on program semantic understanding according to claim 8, characterized in that: The specific process of adjusting the parameters of the cascaded model in the semantic reasoning and symbolization module and the parameters of the structure-aware cross-modal Transformer model in the description generation and alignment module based on this signal is as follows: First, the semantic feedback signal vector is input into a credit allocation network. This network takes as input the intermediate representations of the original program semantic knowledge graph and intent symbolic graph upon which the currently invoked MCP service is based, and outputs a two-dimensional credit allocation vector. Simultaneously, the semantic feedback signal vector is combined into a scalar reward value using a preset reward function. The calculation process of the reward function is as follows: First, the semantic feedback signal vector is processed by a nonlinear transformation function, which maps the various components of the vector to a uniform numerical range. Then, the transformed vector is multiplied by a preset weight vector; the result of the dot product is the scalar reward value. Next, based on the credit allocation vector, the scalar reward value is decomposed into two hierarchical reward values corresponding to the semantic reasoning and symbolization module and the description generation and alignment module, respectively. The specific calculation of the decomposition is as follows: multiply the scalar reward value by the first element of the credit allocation vector to obtain the hierarchical reward value corresponding to the semantic reasoning and symbolization module; multiply the scalar reward value by the second element of the credit allocation vector to obtain the hierarchical reward value corresponding to the description generation and alignment module. Then, the semantic feedback signal vector, the historical statistical information of the hierarchical reward value, and the gradient statistics of the cascaded model and the structure-aware cross-modal Transformer model during recent training are input into the policy network. These inputs together constitute the context on which the policy network makes decisions, i.e., the current state information of the system. The policy network is trained using a proximal policy optimization algorithm, the output of which is a suggestion for adjusting the hyperparameters of the optimizer of the cascaded model and the structure-aware cross-modal Transformer model. The proximal policy optimization algorithm updates the learnable parameters of the policy network by minimizing an alternative objective function. Finally, a progressive knowledge distillation strategy is employed to apply adjustment suggestions to update the learnable parameters within the cascaded model and the structure-aware cross-modal Transformer model. The implementation process of the progressive knowledge distillation strategy is as follows: First, a teacher model and a student model are defined. The teacher model refers to the currently deployed online system comprised of the cascaded model in the semantic reasoning and symbolization module and the structure-aware cross-modal Transformer model in the description generation and alignment module. The student model is a structurally complete copy of the teacher model, with its initial and internal learnable parameters entirely replicated from the teacher model's current learnable parameters. Next, based on the adjustment suggestions output by the policy network, the learnable parameters of the student model are optimized offline in multiple steps by minimizing a combined loss function. The combined loss function is tailored to the specific learning parameters of the teacher model. The semantic reasoning and symbolization module and the description generation and alignment module are calculated and optimized independently. Specifically, the combined loss function for the semantic reasoning and symbolization module is obtained by weighted summing of a first loss term (the negative value corresponding to the hierarchical reward value of the semantic reasoning and symbolization module) and a second loss term (KL divergence, which measures the difference in output distributions between the cascaded models in the student model and the corresponding models in the teacher model under the same input conditions). Similarly, the combined loss function for the description generation and alignment module is obtained by weighted summing of a first loss term (the negative value corresponding to the hierarchical reward value of the description generation and alignment module) and a second loss term (KL divergence, which measures the difference in output distributions between the structure-aware cross-modal Transformer model in the student model and the corresponding model in the teacher model under the same input conditions). In each optimization iteration, based on the numerical value of the responsibility ratio in the credit allocation vector, the above knowledge distillation optimization is performed on the semantic reasoning and symbolization module or the description generation and alignment module; in the combined loss function, the first loss term is multiplied by a first balance coefficient, and the second loss term is multiplied by a second balance coefficient. The learnable parameters of the optimized and stable student model are then synchronized back to the corresponding cascaded model and the structure-aware cross-modal Transformer model in the online teacher model, thereby completing the stable adjustment of the learnable parameters of the cascaded model and the structure-aware cross-modal Transformer model.
10. A method for automatically generating MCP services based on program semantic understanding, applied to an MCP service automatic generation system based on program semantic understanding as described in any one of claims 1-9, characterized in that: Specifically, the following steps are included: Step S1: In response to receiving the target program code, extract and fuse three types of heterogeneous metadata by parallel analysis of its static, dynamic and contextual semantics, and construct the original program semantic knowledge graph. Step S2: Based on the original program semantic knowledge graph, cross-level semantic reasoning and intent abstraction are performed through cascaded heterogeneous graph neural networks and multi-hop reasoning units to generate an intent symbolization graph with symbolized intent units as nodes. Step S3: Using the intent symbolization graph as input, generate a corresponding natural language description draft through a structure-aware cross-modal Transformer model and a dual attention alignment mechanism; Step S4: Monitor the results of the MCP service built based on the initial description in actual calls, convert it into semantic feedback signals, and optimize the learnable parameters of the cascaded model and the cross-modal Transformer model based on these signals through a progressive knowledge distillation strategy.