Multi-path legal inference engine based on MCP protocol

By introducing the Model Context Protocol (MCP) and combining hierarchical training and multi-path reasoning mechanisms, the shortcomings of existing legal intelligent question-answering systems in context management and reasoning consistency are addressed, the logical consistency and explainability of the legal question-answering system are achieved, and the professionalism and credibility of the system in complex legal scenarios are improved.

CN120764667AActive Publication Date: 2025-10-10UNIV OF SCI & TECH OF CHINA

Patent Information

Application Number
CN202510729600.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-06-03
Publication Date
2025-10-10
Estimated Expiration
2045-06-03

AI Technical Summary

Technical Problem

Existing legal intelligent question-answering systems have shortcomings in the construction of complex reasoning chains, the accuracy of legal retrieval, the consistency of article citations, and the explainability of answers. In particular, the context management capabilities are weak in multi-jurisdictional and multi-level legal scenarios, the reasoning process is black-boxed, the results are inconsistent, and there is a lack of traceability.

Method used

The Model Context Protocol (MCP) is introduced to uniformly manage model status, reasoning path and knowledge activation throughout the entire process of model training, reasoning decision-making and result output. Through hierarchical training, Monte Carlo Tree Search (MCTS) and Retrieval Augmented Generation (RAG) mechanisms, the logical consistency and explainability of legal question answering are ensured.

Benefits of technology

It has improved the professionalism, transparency and structured output capabilities of the legal question-and-answer system, achieved structural transparency of the reasoning chain, state controllability of decision-making behavior and contextual consistency of result output, and enhanced the credibility and explainability of the system.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120764667A_ABST
    Figure CN120764667A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of large language models, and discloses a multi-path legal inference engine based on an MCP protocol, which comprises a legal question input module, a legal question answering module and a question and answer result output module, in combination with a Monte Carlo tree search algorithm, a multi-path deduction mechanism, a retrieval enhancement mechanism and a user feedback optimization mechanism, an MCP unified management model internal state and knowledge activation and reasoning path information are relied on, and interpretable legal answers corresponding to legal query questions input by a user are generated. By means of key information flow integrated by the MCP protocol, answers, reasoning chains, reference bases and credibility evaluation are output in a visual mode, and the professionality, the interpretability and the user credibility of the whole legal reasoning process are remarkably improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention belongs to the technical field of the intersection of artificial intelligence and legal technology, and specifically relates to a large language model (LLM) intelligent legal question-answering system that integrates the Model Context Protocol (MCP). This system comprehensively utilizes the language understanding and generation capabilities of the large language model, combines Monte Carlo tree search (MCTS), causal consistency judgment, multi-path deduction mechanism, retrieval enhancement and user feedback optimization, and uses the MCP protocol as the core. It runs through the entire process of model training, reasoning execution and result output, ensuring the contextual consistency, logical traceability and result credibility of legal questions and answers. It is particularly suitable for legal intelligent question-answering scenarios that require high logic, high interpretability and strong professionalism. Background Art

[0002] In recent years, large language models (LLMs) have achieved breakthroughs in natural language processing (NLP). Pre-trained models based on the Transformer architecture (such as the GPT series) have demonstrated strong generalization capabilities in text generation, multi-round question answering, and task transfer. In particular, with the increasing number of parameters, the models have shown broad adaptability in few-shot and zero-shot scenarios. However, traditional LLMs generally face challenges in practical applications, such as opaque reasoning paths, inconsistent outputs, and a lack of controllability. These challenges are particularly evident in high-precision semantic domains such as law.

[0003] To improve the security and preference consistency of large model generation results, academics have proposed alignment paradigms such as RLHF (Reinforcement Learning with Human Feedback) and DPO (Direct Preference Optimization). While DPO provides an efficient training path without relying on explicit reward models, these techniques do not fundamentally address the contextual coherence and reasoning chain integrity issues of large language models in complex contexts.

[0004] At the same time, the continued development of legal artificial intelligence (Legal AI) places higher demands on model capabilities. Tasks such as legal question-answering, regulatory application, and case analysis require not only language comprehension but also the ability to model the legal system, the interpretability of reasoning processes, and the credibility of cited evidence. Current mainstream legal models (such as ChatLaw, Lawformer, and Lawyer LLaMA) generally suffer from the following technical limitations:

[0005] The reasoning process is black-boxed, lacking path transparency and traceability mechanisms;

[0006] Semantic mismatches and frequent version conflicts in legal texts;

[0007] Weak context management capabilities in multi-jurisdictional and multi-level legal scenarios;

[0008] Model training is highly dependent on general corpus and lacks structured legal knowledge and path supervision.

[0009] Even after introducing the Retrieval-Augmented Generation (RAG) framework, existing systems still face the following bottlenecks:

[0010] There is a lack of unified context between retrieval results and model-generated content;

[0011] There is a lack of a unified evaluation and ranking mechanism after multi-path recall, which affects the stability of answers;

[0012] The chain of legal text citations is complex and lacks structured traceability and path basis.

[0013] Therefore, a new mechanism is urgently needed to uniformly manage model states, reasoning paths, and knowledge activation, addressing the contextual fragmentation, reasoning jumps, and unreliable results of traditional systems. This paper introduces the Model Context Protocol (MCP), which forms a consistent contextual control structure across the stages of model training, reasoning decision-making, knowledge retrieval, and result output. This improves the system's logical consistency, citation accuracy, and output interpretability in legal question-and-answering, addressing key technical challenges faced by existing legal intelligent question-and-answer systems in terms of professionalism, transparency, and structured output. Summary of the Invention

[0014] In response to the shortcomings of existing legal intelligent question-answering systems in terms of complex reasoning chain construction, legal retrieval accuracy, consistency of article citations, and answer explainability, the present invention proposes a multi-path legal reasoning engine and method based on the MCP protocol to effectively overcome the above technical difficulties and improve the practicality and reliability of the system in professional legal scenarios.

[0015] The core goal of this invention is to build a legal intelligent question-answering system based on the MCP unified context management mechanism, enhancing the comprehensive capabilities of large language models in processing multi-step legal reasoning, regulatory citation paths, context preservation, and entity consistency. MCP serves as the master control protocol throughout the system's training, reasoning, feedback, and output, responsible for unified management of the model's internal state, reasoning path evolution, knowledge activation, and citation basis records, thereby ensuring the logical consistency and explainability of the entire legal question-answering chain. To achieve the above goals, the present invention proposes the following technical solutions:

[0016] According to one aspect of the present invention, a multi-path legal reasoning engine based on the MCP protocol is provided, comprising:

[0017] A legal question input module;

[0018] A legal question answering module;

[0019] A question and answer result output module.

[0020] Wherein:

[0021] The legal question input module is used to receive natural language legal query questions input by a user, and supports uploading legal norm files, case fact materials, etc., to provide the system with identification of user intent and legal context, initialization of MCP upper and lower states, etc.

[0022]

[0023] The legal question answering module is used to call a large language model trained in layers, plan a reasoning path in combination with a Monte Carlo tree search algorithm (MCTS), locate regulation information in combination with a retrieval augmented generation (RAG) mechanism, and realize state continuous tracking and path optimization under the support of the MCP protocol, to finally generate an answer result that matches the query question, has legal effect support, and has reasoning transparency.

[0024]

[0025] The question and answer result output module outputs legal answers, visual reasoning chains, cited

[0026] references, legal provision paths, and system confidence scores based on the unified structure of the MCP protocol, to guarantee the verifiability and traceability of the output content. Further, the legal question answering module comprises:

[0027] A model layered training module: used to construct a two-stage training framework supporting the MCP protocol, to complete basic legal task capability training in the first stage, fine-tune optimization for multi-law domain preferences and legal conflict tasks in the second stage, and introduce DPO and path consistency supervision;

[0028] A decision reasoning module: based on user intent and the current MCP state, adopts an MCTS strategy to plan a path, combines with MCP historical record constraints to constrain reasoning path consistency, and realizes a closed loop of a cause and effect chain.

[0029] A retrieval enhancement module: combines keyword retrieval, semantic similarity, MCP path context, and supervised reordering strategies to realize personalized and accurate positioning of regulation paragraphs.

[0030]

[0031] ​​​ Legal answer generation module: using the state context, legal basis and reasoning track uniformly managed by MCP, driving the large language model to generate professional legal answers.

[0032] Further, the model hierarchical training module comprises the following sub-modules:

[0033] Among them:

[0034] Open source data acquisition module: systematically collect legal data such as regulations, judicial interpretations, and judgment documents, and

[0035] Combine general instruction data to build multi-layer training sets;

[0036] Basic legal task alignment module: structure general legal data into task sets, and use fusion knowledge to maintain and

[0037] The loss function of MCP consistency regularization term trains the model to master the legal language expression, structure analysis and reasoning basic ability;

[0038] Legal task alignment module: based on the Self-Instruct strategy, build SFT and human preference data set, focus on complex tasks such as multi-law domain conflict, article adaptation, and reference tracking, strengthen the model's understanding and judgment ability of legal context, and realize the consistency of context and path memory mechanism in the training process through MCP protocol.

[0039] In the first level training, in order to ensure that the language understanding ability and context consistency expression ability of the basic legal task are effectively mastered, the invention introduces the joint loss function of the fusion knowledge maintenance mechanism and the MCP context protocol consistency constraint, and its expression is:

[0040]

[0041] Among them:

[0042] ·L base Indicates the total loss value of the basic training stage;

[0043] ·x t Indicates the t-th word in the input legal text sequence;

[0044] .θ indicates the model parameter;

[0045] ·L KP is a knowledge maintenance regularization term, which constrains the memory ability of the model to core legal knowledge;

[0046] ●L MCPIt is the MCP protocol consistency item, which is used to measure the consistency between the model-generated content and the context state and path recorded by MCP;

[0047] λ1,λ2 are hyperparameters that adjust the contribution of each loss term.

[0048] In the second level of training, the system adopts a dual strategy of supervised fine-tuning (SFT) and direct preference optimization (DPO) to improve the model's performance and path rationality in specific legal preference scenarios. The SFT stage still uses the aforementioned joint loss function, while the DPO stage introduces a policy model and a reference model and strengthens the MCP path consistency constraint. The loss function expression is as follows:

[0049]

[0050] in:

[0051] ·L DPO+ Indicates final loss;

[0052] ●(x,y w ,y l ) represents the better and worse responses in the sample input and preference data;

[0053] π θ are the output distributions of the current policy model and the reference model respectively;

[0054] .D consistency is the path logic consistency item;

[0055] .C confidence Answer confidence constraints for the model;

[0056] .R MCP It is the MCP path consistency regularization term, which is used to ensure that the optimized answer is consistent with the reasoning history recorded by MCP in terms of logical structure and state transition;

[0057] β1, β2, β3, and β4 are the weighting coefficients of the loss term.

[0058] Through this structured hierarchical training mechanism, the model can not only master basic language and logical skills, but also establish a stable and clear legal reasoning link under the guidance of the MCP protocol, achieving effective synergy between general capabilities and legal task adaptation capabilities.

[0059] Furthermore, the decision-making reasoning module, supported by the MCP protocol, includes a state space definition module, an action definition module, and a Monte Carlo tree search module, which are used to construct, maintain, and optimize the entire multi-step reasoning path and dynamically update the state, knowledge, and path records in the MCP in a structured manner.

[0060] The state space definition module is used to abstract the legal problem into an initial state. It then combines user intent and context to dynamically generate intermediate states through legal search, context completion, and fact confirmation, ultimately entering a terminal state marked by the MCP (including completion of the solution or reaching reasoning saturation).

[0061] The action definition module is used to define structured reasoning actions, including semantic retrieval of legal databases, adjustment of regulatory priorities, generation of user questions, context expansion, and clarification of regulatory references. The selection and execution of these actions are all controlled by the MCP protocol, with path recording and status maintenance.

[0062] The Monte Carlo tree search module is used to combine states and actions to perform dynamic path generation. It generates multiple candidate paths through a simulated search mechanism and uses the information fed back by MCP to perform consistency evaluation and value scoring on each path.

[0063] The MCTS module execution process includes the following steps:

[0064] 1. Selection phase: Starting from the root node, high-value nodes are prioritized based on improved strategies such as PUCT and the MCP historical status;

[0065] 2. Expansion phase: Call LLM to generate new states and add them to the inference tree, and update the MCP record;

[0066] 3. Simulation phase: Simulate future reasoning processes under the guidance of strategies to generate multi-path structures;

[0067] 4. Feedback phase: transmit the logic information and value signals in the simulation process back to the upper-level node and update the statistics;

[0068] 5. Strategy decision stage: Based on the consistency constraints of the path score and the MCP record, the optimal path is selected as the final reasoning guide.

[0069] By using the MCP protocol throughout the reasoning structure, the system can not only improve the logical integrity of path selection, but also make reasoning behavior visual, traceable, and auditable through structured path control, thereby enhancing the professionalism and credibility of the model output.

[0070] Furthermore, the retrieval enhancement module integrates a retrieval-augmented generation (RAG) mechanism under the unified scheduling of the MCP protocol to quickly, accurately, and controllably locate the regulatory paragraphs relevant to the user's legal query, while ensuring the completeness of the citation chain, consistency of context, and traceability of path information. Its execution process includes the following steps:

[0071] Initial search: The MCP provides the current reasoning state and context labels, guiding the system to perform a preliminary recall in the underlying regulatory database based on the user-entered keywords, entity labels, and task intent. The system then calculates the similarity between the user query vector and the regulatory paragraph vector based on the semantic vector model to obtain a list of candidate paragraphs.

[0072] Multi-strategy recall: Combining BM25, Dense Embedding similarity, and rule constraint matching, multiple strategies are used to perform parallel recall operations. The MCP protocol is used to record the contextual adaptability and historical hit rate of each strategy result, which serves as an important reference for subsequent re-ranking.

[0073] Unified reranking: Through structural mapping between the MCP path context and candidate regulatory paragraphs, the multi-strategy recall results are embedded in a unified vector space. Prioritization is then performed using a reranking model that integrates legal semantics, entity structure, and MCP context consistency, optimizing the logical fit and reasoning interpretability of the regulatory matching results.

[0074] Citation Relation Extraction: MCP calls the citation relation extractor to identify information such as article number jumps and cross-references in the sorted paragraphs, trace the citation source structure, ensure the consistency of the citation chain with the legal context, and update the citation mapping index in MCP.

[0075] Global Information Refinement: For lengthy legal documents, the information refinement module uses the task context and reasoning objectives managed by the MCP protocol to perform noise reduction, retaining only key clauses or sentences that contribute to reasoning, filtering out invalid background information, and forming a legal material collection with greater decision-making value.

[0076] Reasoning chain-guided filtering: The large language model constructs a causal chain sketch based on the current reasoning path recorded by the MCP, further identifies the subset of regulations most relevant to generating the target answer, extracts key nodes of the path from the candidate regulations, and forms a refined combination of regulatory segments that is finally input into the model to support the output of explanatory legal question answering.

[0077] In addition, the similarity calculation in the preliminary search uses the following fusion expression:

[0078] Similarity final (q,d)=α·CosineSimilarity(q,d)+(1-α)·S(q,d;MCP)

[0079] in:

[0080] q represents the semantic vector of the user's legal query after being processed by the Embedding model;

[0081] ●d represents the embedding representation of the candidate paragraph in the regulatory database;

[0082] · represents the traditional cosine similarity;

[0083] S(q, d; MCP) represents the structural semantic scoring function that combines the legal context, citation path, and historical reasoning state of the MCP protocol record;

[0084] .α is the fusion weight hyperparameter, which controls the trade-off between semantic similarity and context structure adaptation.

[0085] The above similarity score is not only used for the initial screening of text recall, but also realizes personalized reordering and reference chain consistency control through the dynamic participation of MCP, significantly improving the accuracy of legal text matching, contextual completeness, and the professionalism and credibility of the final generated model.

[0086] According to another aspect of the present invention, a legal question-answering method based on a multi-path legal reasoning engine (MCP) is proposed. This method features structured legal reasoning and full-chain interpretability. The MCP protocol coordinates model state, knowledge activation, and path information, maintaining logical consistency and contextual coherence throughout the training, reasoning, and output processes. The method specifically includes the following steps:

[0087] 1. Question input stage: Users enter legal inquiry questions in natural language and can choose to upload relevant legal documents, case background, or factual materials. The system uses MCP to initialize the user context state and analyzes the query target and semantic structure through intent recognition and label extraction modules, providing contextual anchors for subsequent reasoning.

[0088] 2. Intelligent Response Phase: The system utilizes a large language model optimized through embedded training using the MCP protocol. Combined with Monte Carlo Tree Search (MCTS) and a multi-path deduction mechanism, the system gradually expands, filters, and optimizes reasoning paths under MCP control. Simultaneously, the RAG retrieval enhancement mechanism is invoked to precisely locate regulatory paragraphs and citation chains that semantically match and structurally align with the query target. MCP dynamically records reasoning status, path evolution, and knowledge activation, filtering out logical contradictions or path redundancies to achieve a rationally structured, causally clear, and explainable reasoning process.

[0089] 3. Output: Leveraging the state and path management provided by the MCP protocol, the system outputs structured legal answers, including the final answer, corresponding provisions, citation sources, reasoning chain, citation relationship diagram, and credibility score. All output information is based on the context tracking and reasoning trajectory preserved in MCP, enabling transparent reasoning, path visualization, and traceable citations, significantly enhancing user understanding and trust.

[0090] The present invention has the following technical effects and practical values:

[0091] This invention introduces a unified MCP protocol for the first time within an intelligent legal question-answering framework, comprehensively integrating model training, state control, knowledge retrieval, and path output, effectively enhancing the system's ability to model legal contexts and its logical consistency in complex tasks. A two-tiered, hierarchical training mechanism, through foundational capability alignment and preference-based reinforcement learning (including Self-Instruct and Determined Proof of Stake + Path Consistency Optimization), simultaneously ensures the stability and flexibility of semantic learning and reasoning chain construction within the MCP framework.

[0092] 2) By embedding Monte Carlo Tree Search (MCTS) and multi-path deduction mechanism into the MCP protocol framework, the system has the ability to perform multi-step legal logic reasoning for complex queries. It can adjust the strategy path in real time, complete context information, select the optimal logical chain, and rely on MCP to perform path consistency evaluation and historical status comparison, thus achieving structural transparency of the reasoning chain and state controllability of the reasoning behavior.

[0093] 3) The RAG module constructed in this invention, based on the historical knowledge activation trajectory and regulatory citation map provided by MCP, can accurately extract the reference relationships, the mapping structure of upper and lower clauses, and the applicable boundaries from regulatory paragraphs, and dynamically filter high-weight information blocks under the guidance of reasoning. During this process, MCP records all knowledge call behaviors and path switching decisions, thereby improving the system's ability to model and interpret highly complex semantic relationships, demonstrating strong professionalism, explanation, and reliability in scenarios such as judicial consultation, regulatory review, and case reasoning. BRIEF DESCRIPTION OF THE DRAWINGS

[0094] In order to more clearly illustrate the technical solution of the present invention, the accompanying drawings schematically illustrate the relevant modules and processes in the embodiments. Obviously, the following drawings are only for illustrating one or several feasible implementations of the present invention, and those skilled in the art can make equivalent substitutions without creative work.

[0095] Figure 1 : Overall framework diagram of the engine of the present invention;

[0096] Figure 2 :The structure and workflow diagram of the retrieval enhancement module integrating the MCP protocol;

[0097] Figure 3 :Flowchart of intelligent legal question answering method based on MCP;

[0098] Figure 4 : MCTS reasoning path planning and feedback update flowchart integrating MCP. DETAILED DESCRIPTION

[0099] To further illustrate the technical solution of the present invention, several specific embodiments are provided in conjunction with the accompanying drawings to assist in explaining the system architecture and method flow. Those skilled in the art can implement equivalent substitutions and modified applications based on the accompanying drawings and descriptions without requiring creative effort.

[0100] Definition of terms

[0101] LLM (Large Language Model): A pre-trained language model based on the Transformer architecture with over 100 million parameters, capable of natural language generation, reasoning, and comprehension. In this paper, LLM refers to a legal-specific language model trained through multi-stage, layered training and integrated with the MCP protocol.

[0102] MCTS (Monte Carlo Tree Search): A search algorithm that follows the “select-expand-simulate-return” principle.

[0103] The four-stage state space exploration is the core mechanism for the system to plan legal logic paths.

[0104] RAG (Retrieval-Augmented Generation): Retrieval-augmented generation technology integrates document recall and language generation modules to effectively improve the factual consistency and regulatory citation accuracy of the model's answers.

[0105] .MCP (Model Context Protocol): Model Context Protocol is a key mechanism proposed in this invention. It runs through the model training, reasoning, and output stages, and is used to uniformly manage model status, knowledge activation, reasoning paths, and contextual information. It is the core supporting component for achieving reasoning explainability, state consistency, and output transparency.

[0106] According to one embodiment of the present invention, Figure 1 and Figure 2 As shown, a multi-path legal reasoning engine based on the MCP protocol is provided, including a legal question input module, a legal question answering module and a question-answering result output module.

[0107] in:

[0108] The Legal Question Input Module receives legal queries entered by users in natural language and supports uploading legal texts, contract documents, factual materials, and other information. The system initializes the user context state based on the MCP for subsequent state management and path scheduling.

[0109] The legal question answering module is the core of the system, which calls the large language model trained and optimized by the MCP protocol, combined with

[0110] The MCTS algorithm constructs a multi-step reasoning path, integrates the RAG mechanism to locate regulatory information, and dynamically adjusts the reasoning strategy with the support of the MCP unified context structure to generate professional and credible legal answers.

[0111] The Q&A result output module, supported by MCP paths and status information, outputs structured legal answers, corresponding provisions, reasoning chain diagrams, citation paths, and credibility scores, ensuring transparency, visualization, and contextual consistency throughout the entire process.

[0112] In the legal question answering module, the model hierarchical training module builds a two-stage training system based on the MCP protocol to achieve the decoupling and alignment of general language skills and legal professional skills.

[0113] Its interior includes:

[0114] Open-source data acquisition module: Systematically collects legal data such as laws and regulations, judgments, and judicial interpretations, and combines it with general task data for training preparation;

[0115] Basic Legal Task Alignment Module (L0): This module trains the model's basic understanding, logical expression, and language generation capabilities through a structured task set. A joint loss function combining knowledge preservation and MCP context consistency is introduced during training to ensure the stability of state transitions and contextual connections during training. The loss function is as follows:

[0116]

[0117] Among them, L KP represents the knowledge retention item, L MCP represents the MCP consistency regularization term.

[0118] Legal Task Alignment Module (L1): This module uses a self-instruct strategy to construct an SFT dataset and a preference dataset, and trains the model on specific legal tasks, focusing on regulatory adaptation, multi-jurisdictional conflicts, article citation, and causal chain reasoning tasks. It uses the MCP-enhanced DPO+ loss function.

[0119]

[0120] Among them, R MCP The regularization term for inference path and state consistency is used to supervise whether the model generation results are consistent with the MCP historical state and path.

[0121] The training in this stage incorporates scenarios such as legal instruction tasks, judicial reasoning, regulatory adaptation, and case analysis into the fine-tuning system. After training, the model is evaluated through multiple legal benchmarks such as LawBench, LexGLUE, and LexEval to verify its professionalism and robustness.

[0122] Guided by the MCP framework, the decision-making and reasoning module employs the MCTS algorithm to complete multi-step path planning for solving legal problems. The system uses state information from the MCP as the foundation of the MCTS state space and dynamically defines initial, intermediate, and final states based on user intent, knowledge activation, and historical reasoning paths. The action set includes semantic retrieval, document tracing, user supplementation, and context expansion. The state sharing mechanism provided by the MCP supports information synchronization between modules.

[0123] In actual implementation, MCTS consists of the following four stages:

[0124] 1) Selection phase: Starting from the current state node defined by MCP, the access frequency and MCP path consistency score are comprehensively considered to select the potential optimal child node;

[0125] 2) Expansion phase: Generate unexplored actions based on LLM, expand intermediate state nodes, and record the new state into MCP;

[0126] 3) Simulation phase: Multiple rounds of simulation are conducted based on the strategy-guided path, and the simulation is carried out to the termination state;

[0127] 4) Feedback phase: Based on the path performance and result credibility, the value is fed back and the state score and path weight in the MCP are updated to improve the quality of subsequent reasoning behavior.

[0128] In summary, the specific implementation of the present invention uniformly manages the context state, reasoning path and knowledge call through the MCP protocol throughout the entire process of model training, reasoning execution and result output, achieving structural transparency of the reasoning chain, state controllable decision-making behavior and contextual consistency of result output, providing high-accuracy, high-interpretability and high-credibility system support for the legal intelligent question-answering system.

[0129] Specifically, it includes the following submodules and reasoning strategies, in which the state management, reasoning path tracking and knowledge call of all modules are uniformly managed by the Model Context Protocol (MCP), achieving state traceability and path transparency of the entire process. State space definition module:

[0130] Initial state: The initial state consists of the natural language question raised by the user and the background information such as the legal text and case facts uploaded by the user. The system initializes and records this state through MCP.

[0131] Intermediate states: These represent state updates formed during the inference process after the model performs actions such as legal retrieval, user-guided questioning, or context expansion. The MCP protocol records the state evolution path and the corresponding context switch.

[0132] .Termination state: The termination state indicates that the system has collected sufficient legal evidence under the current path or reached the preset reasoning depth threshold. MCP locks the path structure here and triggers the state freezing mechanism for result feedback and explainable output.

[0133] Action definition module:

[0134] With the support of MCP, the system defines the following scheduling-type reasoning actions for MCTS to dynamically select and combine for execution:

[0135] 1. Semantic search of the legal database: Based on the contextual tags and knowledge activation status stored in the MCP, the semantic matching mechanism and regulatory structure parser are invoked to accurately extract the most relevant provisions, applicable requirements, and interpretation opinions for the current situation;

[0136] 2. Web-assisted search: Combining user context and MCP preference paths, search for public legal resources to supplement external knowledge fragments such as cases, industry standards, and guidelines;

[0137] 3. User question guidance: When MCP determines that the current path is semantically ambiguous or key elements are missing, it proactively triggers follow-up questioning strategies to help users clarify the boundaries of the question and the scope of the law;

[0138] 4. Contextual Extension: LLM is used to generate associative extensions based on the MCP path, covering relevant legal background, historical cases, or similar case reasoning structures to improve contextual coherence and reasoning coverage.

[0139] Monte Carlo Tree Search Module:

[0140] This module builds a dynamic asymmetric search tree with the support of the MCP protocol and optimizes the reasoning path through multiple rounds of interactive simulation. It includes the following steps:

[0141] 1. Selection: Starting from the root node, based on the improved PUCT strategy, the most promising node is selected in the tree by comprehensively considering the node's MCP context weight, number of visits, and path consistency score;

[0142] 2. Expansion: If the current node does not meet the termination condition, the LLM executes the untried actions in the MCP state space to generate a new state node. This state and path information are written to the MCP in real time to update the inference trajectory.

[0143] 3. Simulation: Perform simulated reasoning along the new extension path, using the policy network and the historical behavior trajectory recorded in the MCP to perform multi-step generation until the termination state is reached;

[0144] 4. Backpropagation: Propagate the result score and reasoning path transparency index of the terminal node from the leaf node upward, update the statistics of all relevant nodes in the search tree, and synchronously write them to the MCP path database;

[0145] 5. Action Decision: Based on the cumulative MCP path score and state credibility of all candidate child nodes,

[0146] The optimal node is selected as the next execution path to improve the rationality of the decision and the causal consistency of the final answer. It is worth noting that the "Legal Library Semantic Retrieval" action in this module is the core part of the RAG (Retrieval Enhancement Generation) strategy under the MCP path constraint. Under the scheduling management of MCP, this action not only accurately matches the provisions, but also adaptively adjusts the breadth and depth of the search based on contextual information. This scheduling mechanism ensures that the execution timing and direction of the RAG module in the path branch are always consistent with the historical status and preferred path, effectively reducing semantic drift and provision citation deviation.

[0147] Under the guidance of MCP, the search enhancement module is responsible for recalling regulatory content, restoring article structure, and refining context. This module achieves content focus and information integration through the following steps:

[0148] 1. In the initial recall phase, the system performs multi-strategy retrieval based on the knowledge tags and legal scope provided by MCP.

[0149] (including BM25, semantic vector similarity, rule triggers, etc.);

[0150] 2. The unified re-ranking phase maps candidate paragraphs to the same semantic space and integrates user preferences, historical call frequency, and other information recorded in the MCP for personalized re-ranking.

[0151] 3. The citation relationship extraction phase identifies the hierarchical citation relationships and cross-article jump structures between regulatory articles, and traces the integrity of the citation chain through the MCP path recorder;

[0152] 4. In the context restoration and information refinement phase, key information nodes are filtered from long texts and noise is eliminated based on MCP path construction and causal chain logic.

[0153] 5. Finally, the RAG module inputs the reordered refined regulatory paragraphs and user questions into the LLM, and generates legal answers that conform to regulatory logic, have consistent citations, and are clearly expressed under the management of the MCP protocol, ensuring the system's interpretability and professionalism in handling complex legal issues.

[0154] Many scenarios in legal question-answering require efficient retrieval and content refinement of extremely long and contextual legal texts. To address this, this embodiment introduces a legal retrieval enhancement module based on the RAG (Retrieval Enhancement Generation) mechanism. This module, combined with a structured LLM trained on the LLM and the MCP that unifies the training and reasoning processes, enables precise legal text location and authoritative answer generation.

[0155] The system's underlying search capabilities are based on a regulatory index database built with ElasticSearch (ES), supporting full-text search, field structured matching, and vectorized semantic queries. The system uses MCP to centrally manage user intent, contextual state, and search history. It integrates vector embedding and rule-based search logic when constructing queries, and combines keyword Boolean search with semantic vector matching in the initial search phase. The similarity between the user query vector q and the regulatory text vector d is calculated as follows:

[0156] In the initial search phase, the system performs a Boolean search based on the keywords in the user's question and fuses the text query results with the vector search results based on the embedding representation. The basic similarity between the user query vector q and the regulatory text vector d is calculated using the following formula:

[0157] Similarity final (q,d)=α·CosineSimilarity(q,d)+(1-α)·S(q,d;MCP)

[0158] To mitigate the differences in scoring dimensions between different recall strategies, this paper uses MCP to integrate historical preferences, contextual relevance, and path scoring information, and uniformly guides the ranking model to aggregate and rank multi-source recall results, ensuring the diversity and pertinence of legal texts. To address the "context truncation" and "information drift" issues that often occur in LLM when processing extremely long legal documents, this paper proposes a three-stage structured retrieval enhancement strategy driven by the MCP protocol:

[0159] 1. Citation relationship extraction stage: Leveraging the citation context and inter-paragraph jump logic of MCP records, the regulatory citation chain is extracted from the reordered text and mapped back to the original document context to achieve a complete restoration of the regulatory network.

[0160] 2. Global information screening stage: The system combines the MCP path context and reference chain information to denoise content with high semantic density but high logical risk, retaining traceable and verifiable legal paragraphs, and optimizing the quality of the context used for generation through a semantic compression module.

[0161] 3. Reasoning chain guidance stage: Based on the user question and the path state diagram maintained by the MCP protocol, the LLM chain of thought mechanism is triggered to dynamically select the clauses and paragraphs that directly support the answer to the question.

[0162] Eliminate redundant content and strengthen the focus and causal consistency of the output.

[0163] The processed content is input into the large language model together with the original user query. The MCP protocol coordinates the loading of historical status, knowledge activation records and reference path information, guiding the model to perform structured fusion reasoning and generate professional answers with clear clause support, legal logic chain and authoritative citations.

[0164] The legal answer generation module, based on the input control and state annotation functions provided by MCP, can automatically load reference evidence, reasoning chain position, and user intention tags during the answer generation process, and ultimately output answer content with a clear causal structure.

[0165] The question-answering result output module uses the knowledge flow and path tracing information managed by MCP to display the final answer in a graphical form, including a legal answer summary, reference article links, reasoning chain diagram, typical case annotations and system confidence score, effectively improving the interpretability of the results and user trust.

[0166] According to another embodiment of the present invention, Figure 3 and Figure 4 As shown, a legal question-answering method of a multi-path legal reasoning engine based on the MCP protocol is provided, comprising the following steps:

[0167] S1: Question input and regulation upload. The user enters a natural language question and uploads relevant regulatory documents. The system initializes the context state and path management structure based on the MCP.

[0168] S2: System Reasoning and Question-Answer Generation. The system uses MCP to construct an inference tree and combines MCTS with dynamic selection retrieval, knowledge activation, context expansion, and feedback collection to gradually build multiple path answer candidates. All path state information and selection processes are tracked by MCP.

[0169] S3: Results Generation and Visualization Output. The system selects the optimal scoring path based on the MCP protocol, schedules the structured generation process, outputs professional answer text, and uses the output module to display the core conclusions, applicable provisions, causal paths, and confidence scores in a graphical structure.

[0170] In summary, the intelligent legal question-answering system and method proposed in this invention innovatively introduce the Model Context Protocol (MCP) to achieve context consistency management, path transparency, and information traceability throughout the entire process from training to reasoning to output, comprehensively improving the accuracy, explainability, and credibility of the system in professional legal task scenarios.

Claims

1. A multi-path legal reasoning engine based on the MCP protocol, characterized by: The engine includes: The legal question input module is used to receive legal queries input by users and upload relevant legal norms documents; The legal question answering module, based on LLM, combines Monte Carlo tree search, multi-path deduction, causal consistency judgment, retrieval enhancement mechanism, and user feedback mechanism to perform legal logic reasoning. This module relies on MCP to uniformly manage the model's internal state, knowledge activation, and reasoning path information, ensuring contextual consistency, information persistence, and path transparency during the reasoning process, thereby generating explainable legal answers corresponding to user input questions. The question-and-answer result output module uses the reasoning path, status information, and knowledge sources integrated by MCP to visually output legal answers, reasoning chains, citation basis, and credibility assessment, enhancing user understanding and trust.

2. The engine according to claim 1, characterized in that The legal question answering module includes: A model training framework that embeds the MCP protocol throughout the training process to form a unified context management mechanism, including label awareness and hierarchical training, structured instruction templates, knowledge retention mechanisms, legal conflict simulators, and direct preference optimization strategies, to improve the model's generalization and refinement capabilities across different legal tasks. The inference engine, based on the MCP protocol for inference process management, covers a large language model, core inference mechanism, multi-path deduction module, causal consistency judgment module, retrieval enhancement module, and user feedback optimization module; The MCP protocol component runs through all stages of model training and inference execution, and is used to uniformly manage state transfer, knowledge activation, path tracking, and context sharing.

3. The engine according to claim 2, characterized in that The model training framework includes: Label perception and layered pre-training module; Introducing structured instruction templates and knowledge retention mechanisms into the basic legal task training phase, combined with MCP to manage the consistency of training context; The professional legal task training phase combines the legal conflict simulator and preference optimization strategy under the MCP protocol to achieve in-depth fine-tuning for complex legal contexts.

4. The engine according to claim 3, characterized in that The basic training stage adopts a joint loss function that integrates the knowledge preservation term and the MCP context consistency constraint, which is expressed as: in: ·x t : the tth word in the original legal text sequence; θ: model parameters; ·L KP : knowledge preserving regularization term; ·L MCP : Contextual agreement consistency term, which measures the difference between the prediction result and the MCP historical state consistency; λ1,λ2: Hyperparameters that adjust the weight of the loss term.

5. The engine according to claim 4, characterized in that The improved DPO loss function that integrates the MCP path management mechanism is used in the professional training stage, and its expression is: x: input question; ·y w ,y l : represent better and worse answers respectively; π θ : Current strategy model; π ref : reference model; σ(·): Sigmoid function; β1,β2,β3,β4: weight hyperparameters; ·D consistency : reasoning path consistency item; ·C confidence : Generate answer confidence item; ·R MCP : The reasoning path consistency regularization term based on the MCP protocol is used to constrain the consistency of the answer logic and the historical path records.

6. The engine according to claim 2, characterized in that The MCP component in the inference engine supports the following functions: Reasoning state tracking: Recording the decision state of each step of the model in time series; Knowledge activation mechanism: Dynamically retrieve structured legal knowledge based on the current context; Path recording and scoring: Structural consistency and interpretability scores are performed on each candidate path; State sharing mechanism: enables information sharing between different modules during the reasoning process.

7. The engine according to claim 6, characterized in that Retrieval enhancement mechanisms include: Legal entity semantic correction module; Regulatory conflict warning module; Multi-strategy recall and large language model supervised re-ranking module, combining user context and regulatory preferences stored in MCP to achieve personalized ranking.

8. The engine according to claim 7, characterized in that The similarity score is calculated as follows: Similarity final (q,d)=α·CosineSimilarity(q,d)+(1-α)·S(q,d;MCP) q: vector representation of the user’s query question; d: vector representation of the regulatory paragraph; CosineSimilarity(q,d): cosine similarity; α: Fusion ratio hyperparameter, controlling the relative weight of the two parts. S(q,d;MCP): A weighted scoring function that comprehensively considers legal semantics, regulatory context, and MCP path weights.

9. The engine according to any one of claims 1 to 8, characterized in that The question-answering result output module uses the MCP protocol to structure the reasoning trajectory and visually displays the complete decision logic and credibility of the system in the form of causal chain diagrams, reference basis, knowledge source annotations and state evolution diagrams.

10. A multi-path legal reasoning and legal question answering method based on the MCP protocol, characterized in that: The steps include:

1. Receive legal queries and extract key tags and entities, initializing the MCP context state; 2. Construct a system that integrates the MCP history state and the user prompt input, and calls the large language model for inference; 3. The MCP protocol dynamically maintains the reasoning state, knowledge call records, and path structure; 4. Combine multi-path simulation with causal consistency assessment mechanism to filter low-confidence paths based on MCP context; 5. Use the search enhancement module to retrieve legal provisions and integrate user context for semantic re-ranking; 6. The question-answering output module provides a visual display based on the structured information flow provided by MCP, including the reasoning chain, citation basis, legal answer and credibility score.

Citation Information

Patent Citations

  • All-weather RAG intelligent agent automatic newspaper design method and device and electronic equipment

    CN119476247A

  • Multimodal reasoning method based on Monte Carlo tree and dynamic retrieval

    CN119808941A

  • Dynamic retrieval decision scheme determination method and system based on Monte Carlo tree search

    CN120011413A

  • Enhanced large language model processing method, system and platform based on Monte Carlo tree search and storage medium

    CN120011510A

  • Multi-round knowledge-guided question and answer method and system fusing large language model and knowledge graph

    CN120069068A

Cited By

  • Intelligent question and answer implementation method and system based on MCP protocol

    CN121210630A

  • Secure access and identity authentication method and system for distributed energy storage equipment

    CN121887541A

  • Distributed energy storage device security access and identity authentication method and system

    CN121887541B

  • Weight coefficient dynamic updating-based dual-path generation method, medium and system

    CN121998073A