Mcp protocol-based automatic positioning system, method and medium for browser memory leakage
The browser memory leak automatic location system based on the MCP protocol solves the problems of automation, accurate location and intelligent repair in browser memory leak detection, realizes the closed loop of the whole link from detection to repair, and improves the efficiency of detection and repair.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- BEIJING FENYANG TECH CO LTD
- Filing Date
- 2026-04-23
- Publication Date
- 2026-07-24
AI Technical Summary
Existing technologies lack automation, are difficult to perform incremental analysis, lack source code mapping, and have fragmented toolchains in browser memory leak detection, resulting in low efficiency in memory leak location and repair.
An automatic browser memory leak location system based on the MCP protocol is adopted. The system establishes a connection between the IDE and the browser debugging port through the MCP communication module. Combined with automated testing, heap snapshot collection, incremental analysis, reference chain analysis and source map source code location, it realizes a closed loop of the whole chain from automated detection to intelligent repair.
It achieves fully automated detection of browser memory leaks, with accurate location and intelligent repair, shortening detection time, improving repair efficiency, and ensuring repair effectiveness.
Smart Images

Figure CN122086742B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer software development and testing technology, and in particular to an automatic browser memory leak location system, method and medium based on the MCP (ModelContext Protocol) protocol. Background Technology
[0002] With the rapid development of web front-end technologies, the complexity of Single Page Applications (SPAs) is increasing daily. Mechanisms such as component trees, virtual DOM, closures, and cross-domain communication make memory management extremely complex. Browser memory leaks can cause page lag and crashes, severely impacting user experience.
[0003] In current technologies, developers typically use tools such as Chrome DevTools for memory debugging. However, the existing process has significant drawbacks: 1. Lack of automation: Developers need to manually refresh the page, trigger GC (garbage collection), collect snapshots and download them for comparison, which is cumbersome and makes it difficult to guarantee the consistency of timing.
[0004] 2. Difficulty in incremental analysis: The object IDs in browser heap snapshots are unstable, and the same object cannot be accurately tracked after cross-page refreshes, resulting in low accuracy of multi-round snapshot difference analysis (Diff) and difficulty in identifying real leaks.
[0005] 3. Missing source code mapping: The heap snapshot only shows the location of the compiled code (such as bundle.js) and cannot be directly associated with the source code during development (such as TypeScript / Vue files). Developers need to manually reverse the process using SourceMap.
[0006] 4. Lack of intelligent repair: Existing tools only display data and cannot analyze the root cause of the leak based on the reference chain and provide repair code.
[0007] 5. Fragmented toolchain: The debugging process involves frequent switching between the browser and the IDE, lacking a unified control protocol.
[0008] MCP (Model Context Protocol) is an emerging standardized protocol designed to connect AI models with development tools. However, there is currently no technical solution that uses the MCP protocol to establish a connection between the IDE and the browser's underlying debugging ports to solve the memory leak problem. Summary of the Invention
[0009] This invention aims to solve the above-mentioned technical problems and provides an automatic browser memory leak location system, method and medium based on the MCP protocol, realizing a closed-loop system from automated detection and accurate location to intelligent repair.
[0010] The first aspect of this invention discloses an automatic browser memory leak location system based on the MCP protocol, the system comprising: The MCP communication module, configured in the integrated development environment (IDE), is used to establish a bidirectional communication link with the browser debugging port through the Model Context Protocol (MCP), convert synchronous tool call requests into asynchronous browser debugging protocol (CDP) commands, and manage the session context. The automated test execution module is used to send control commands to the browser through the MCP communication module to execute automated operation sequences, including page navigation, multiple rounds of refresh, and forced garbage collection (GC), and dynamically adjust the test strategy based on intermediate analysis results. The heap snapshot acquisition module is used to collect heap memory snapshots of the browser after each round of operation and GC, and parse the snapshot data structure. The Heap Snapshot Comparison and Incremental Analysis module is used to perform differential calculations on multiple rounds of heap snapshots, identify object increments by matching fingerprints across snapshot objects, and calculate the confidence score of suspected leaked objects. The reference chain analysis module is used to construct the reference path of suspected leaked objects, extract key reference nodes based on the dominance tree algorithm, and filter out non-business logic internal framework nodes. The SourceMap source code location module is used to build a mapping index from runtime script IDs to source code files, mapping the construction location and call stack of leaked objects to the path and row and column numbers of the original code; The intelligent repair suggestion generation module is used to input the pruned reference chain features and source code context into an artificial intelligence (AI) model to generate repair suggestion code; The IDE visualization module is used to interactively display memory trends, reference chain structure, source code location markers, and repair suggestions within the IDE interface, and supports incremental verification.
[0011] Preferably, the MCP communication module includes a protocol conversion adapter, the adapter being configured with: The Promise suspension mechanism is used to maintain a queue of unfinished MCP requests, map synchronous calls of MCP to suspended Promise objects, and resolve the Promise when the corresponding CDP response or event is received. Event-driven synchronization encapsulation is used to subscribe to asynchronous lifecycle events of the browser, encapsulating page load completion, network idle, and GC completion events into waitable synchronous signals; A streaming data aggregator is used to receive chunked heap snapshot data streams, cache them locally, and reassemble them into complete snapshot files.
[0012] Preferably, the heap snapshot comparison and incremental analysis module includes an object fingerprint generation unit, used to generate a unique object fingerprint that remains stable across page refreshes. The object fingerprint is composed of a weighted combination of the following features: Construct stack frame characteristics based on hash values generated from the complete function call chain and script location at the time of object creation; Attribute structure characteristics, a hash value generated based on the set of object's own attribute names and attribute type structure; Constructor signature, based on the normalized hash value of the object's constructor source code; Reference topology features are feature values generated based on the hierarchy and connectivity of objects in the heap memory reference graph; When comparing snapshots from different rounds, the module uses the object fingerprint to perform a one-to-one mapping of objects, rather than relying on unstable memory addresses or temporary IDs.
[0013] Preferably, the heap snapshot comparison and incremental analysis module further includes a leakage confidence scoring unit, used to calculate the confidence score of the suspected leakage object based on multi-dimensional features, wherein the multi-dimensional features include at least: Retained Size growth rate: the average percentage increase in the size of the object's retained memory over the test rounds; The frequency with which the memory size of an object increases across consecutive test rounds; Leakage pattern matching degree, which is the degree to which object characteristics match a preset leakage pattern library, which includes Detached DOM, uncleaned timers, and unbound event listeners; Reference chain characteristics: whether the reference path contains global variables, closures, or specific framework lifecycle objects.
[0014] Preferably, the reference chain analysis module is configured with a reference chain compression algorithm based on the dominator tree, specifically including: Construct a dominator tree for the heap memory graph to identify key node paths that have a dominance relationship with the leaking object; Identify and collapse the internal nodes of the frame in the path, and the internal nodes of the frame are matched by a preset frame feature library; Importance sampling is performed on reference paths that exceed the preset length, retaining GC root nodes, leaked object nodes, and high-weight business logic nodes; The compressed reference paths are converted into structured feature vectors, which serve as the input context for the AI model.
[0015] Preferably, the SourceMap source code location module is configured with a multi-level mapping index cache for pre-building mapping relationships before snapshot collection, wherein the index includes: The ScriptId mapping table stores the correspondence between runtime ScriptIds and the URLs of the bundled files, and dynamically tracks asynchronous chunks generated by code splitting. The Bundle mapping table stores the correspondence between Bundle file URLs and SourceMap files; The location mapping table stores the parsing results of the row and column numbers in the Bundle file to the original source code file path and row and column numbers; When locating, the module first queries the cached index; if no match is found, it parses the SourceMap file in real time and updates the cache.
[0016] Preferably, the automated test execution module has an adaptive test strategy driven by the MCP protocol, specifically including: After the initial test rounds are completed, the incremental analysis module is invoked in real time to obtain intermediate results; Based on the memory growth trend and the number of Detached DOMs in the intermediate results, the subsequent testing strategy is dynamically adjusted through the MCP session context; The adjustment strategies include: automatically increasing the number of test rounds when the growth is not significant; extending the GC wait time and increasing the GC intensity when a large number of DetachedDOMs are detected but memory usage does not increase; and terminating the test early and entering the deep analysis phase when a high-confidence leak is detected.
[0017] Preferably, the IDE visualization module and automated test execution module are further configured with an incremental verification mechanism to verify the repair effect: Listen for file save events in the IDE to identify code changes that involve leaked objects; Triggering browser module hot replacement (HMR) or targeted refresh via the MCP protocol, performing a minimal sequence of operations only on the affected leaked objects; Collect targeted small heap snapshots or object query results, and compare the changes in Retained Size before and after the repair; Update the status of leak diagnostic markers in real time within the IDE editor.
[0018] The second aspect of this invention discloses an automatic browser memory leak location method based on the MCP protocol. The method employs the system described in the first aspect and includes: Step S1: Start the MCP server in the IDE and connect to the browser's debugging port via the WebSocket protocol; Step S2: Send instructions via the MCP protocol to control the browser to load the target page and establish a global index containing the mapping relationship between ScriptId and SourceMap; Step S3: Execute the automated test script to perform multiple rounds of page refresh operations, and force garbage collection and collect heap snapshots after each round of operations; Step S4: Perform incremental analysis on the collected multi-round snapshots, use the object fingerprint algorithm to match objects across rounds, and calculate the leakage confidence score; Step S5: For leaked objects with high confidence, construct a dominance tree and compress the reference chain, and use the SourceMap index to locate the source code location; Step S6: Send the compressed reference chain, source code context, and leakage characteristics to the AI model to generate repair suggestions and display them in the IDE.
[0019] A third aspect of this invention discloses a computer-readable storage medium. The computer-readable storage medium stores a computer program, which, when executed by a processor, implements the steps of the browser memory leak automatic location method based on the MCP protocol according to any one of the first aspects of this disclosure.
[0020] The beneficial effects of this invention are as follows: 1. Full-process automation: By using the MCP protocol to connect the IDE and the browser, the detection time is reduced from hours to minutes.
[0021] 2. Precise positioning: The problem of cross-refresh comparison is solved by object fingerprinting technology, and the SourceMap full-link index achieves millisecond-level source code positioning.
[0022] 3. Intelligent decision-making: Based on reference chain compression and confidence scoring of the dominance tree, AI can understand complex memory graph structures and provide highly available repair suggestions.
[0023] 4. Closed-loop verification: The incremental verification mechanism within the IDE enables "verification upon modification", significantly improving repair efficiency. Attached Figure Description
[0024] To more clearly illustrate the specific embodiments of the present invention or the technical solutions in the prior art, the drawings used in the description of the specific embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.
[0025] Figure 1 This is a diagram showing the overall architecture and data flow of the system of this invention.
[0026] Figure 2 This is a timing and status synchronization diagram for communication between the MCP server and the browser's CDP port.
[0027] Figure 3 This is a flowchart of incremental analysis and matching of heap snapshots based on object fingerprints.
[0028] Figure 4 This is a schematic diagram of reference chain compression and key node extraction based on the dominance tree.
[0029] Figure 5 A diagram illustrating the principles of SourceMap full-link index construction and source code location.
[0030] Figure 6 A flowchart of the IDE incremental verification mechanism.
[0031] Figure 7 This is a flowchart of an automatic browser memory leak location system based on the MCP protocol according to an embodiment of the present invention; Detailed Implementation
[0032] To make the objectives, technical solutions, and advantages of this invention clearer, the technical solutions of the embodiments of this invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of this invention. Based on the embodiments of this invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this invention.
[0033] The first aspect of this invention discloses an automatic browser memory leak location system based on the MCP protocol. Figure 1 This is a flowchart of an automatic browser memory leak location system based on the MCP protocol according to an embodiment of the present invention, as shown below. Figure 1 As shown, the system includes: The MCP communication module, configured in the integrated development environment (IDE), is used to establish a bidirectional communication link with the browser debugging port through the Model Context Protocol (MCP), convert synchronous tool call requests into asynchronous browser debugging protocol (CDP) commands, and manage the session context. The MCP communication module includes a protocol conversion adapter, which is configured with: The Promise suspension mechanism is used to maintain a queue of unfinished MCP requests, map synchronous calls of MCP to suspended Promise objects, and resolve the Promise when the corresponding CDP response or event is received. Event-driven synchronization encapsulation is used to subscribe to asynchronous lifecycle events of the browser, encapsulating page load completion, network idle, and GC completion events into waitable synchronous signals; A streaming data aggregator is used to receive chunked heap snapshot data streams, cache them locally, and reassemble them into complete snapshot files.
[0034] The automated test execution module is used to send control commands to the browser through the MCP communication module to execute automated operation sequences, including page navigation, multiple rounds of refresh, and forced garbage collection (GC), and dynamically adjust the test strategy based on intermediate analysis results. The automated test execution module has an adaptive test strategy driven by the MCP protocol, specifically including: After the initial test rounds are completed, the incremental analysis module is invoked in real time to obtain intermediate results; Based on the memory growth trend and the number of Detached DOMs in the intermediate results, the subsequent testing strategy is dynamically adjusted through the MCP session context; The adjustment strategies include: automatically increasing the number of test rounds when the growth is not significant; extending the GC wait time and increasing the GC intensity when a large number of DetachedDOMs are detected but memory usage does not increase; and terminating the test early and entering the deep analysis phase when a high-confidence leak is detected.
[0035] The specific technical effects are compared in Table 1.
[0036] Table 1 Comparison of Technical Effects
[0037] The dynamic feedback loop mechanism based on the MCP protocol described above is architecturally impossible for traditional static scripting tools because they lack persistent sessions, context sharing, and toolchain composition capabilities. This constitutes a significant inventive step for this invention compared to existing technologies (Puppeteer, MemLab, etc.), specifically including: 1) MCP persistent session: Utilizing the session mechanism of the MCP protocol, context sharing is maintained throughout the detection period, allowing historical data to influence subsequent decisions.
[0038] 2) Real-time analysis and feedback: MCP's analysis tools are invoked immediately after each round of snapshot collection, instead of waiting for the entire process to complete.
[0039] 3) AI strategy decision-making: By calling AI tools through MCP, intelligent decisions are made based on the accumulated session context (adjusting rounds, GC strategies, interaction sequences, etc.).
[0040] 4) Closed-loop optimization: Forming a complete closed loop of "collection → analysis → decision-making → adjustment → re-collection", which cannot be achieved by the unidirectional process of traditional tools.
[0041] 5) Hypothesis-driven testing: Maintain and update leakage hypotheses to guide testing strategies and improve detection targeting.
[0042] 6) Multi-stage adaptive: Automatically switches test stages (baseline testing, in-depth validation, stress testing, early termination) based on confidence level.
[0043] The heap snapshot acquisition module is used to collect heap memory snapshots of the browser after each round of operation and GC, and parse the snapshot data structure. The Heap Snapshot Comparison and Incremental Analysis module is used to perform differential calculations on multiple rounds of heap snapshots, identify object increments by matching fingerprints across snapshot objects, and calculate the confidence score of suspected leaked objects. The heap snapshot comparison and incremental analysis module includes an object fingerprint generation unit, used to generate a unique object fingerprint that remains stable across page refreshes. The object fingerprint is composed of a weighted combination of the following features: Construct stack frame characteristics based on hash values generated from the complete function call chain and script location at the time of object creation; Attribute structure characteristics, a hash value generated based on the set of object's own attribute names and attribute type structure; Constructor signature, based on the normalized hash value of the object's constructor source code; Reference topology features are feature values generated based on the hierarchy and connectivity of objects in the heap memory reference graph; When comparing snapshots from different rounds, the module uses the object fingerprint to perform a one-to-one mapping of objects, rather than relying on unstable memory addresses or temporary IDs.
[0044] Specifically, the heap snapshot comparison and incremental analysis module also includes a leakage confidence scoring unit, used to calculate the confidence score of suspected leakage objects based on multi-dimensional features, wherein the multi-dimensional features include at least: Retained Size growth rate: the average percentage increase in the size of the object's retained memory over the test rounds; The frequency with which the memory size of an object increases across consecutive test rounds; Leakage pattern matching degree, which is the degree to which object characteristics match a preset leakage pattern library, which includes Detached DOM, uncleaned timers, and unbound event listeners; Reference chain characteristics: whether the reference path contains global variables, closures, or specific framework lifecycle objects.
[0045] The design basis for the weighting factors is shown in Table 2. Table 2
[0046] The weight settings should follow these principles: 1) Direct evidence > Indirect evidence: Memory growth rate is direct evidence and has the highest weight.
[0047] 2) Time-based verification > Single observation: Sustained growth is more reliable than a single large increase.
[0048] 3) Determinism > Statistical: Clear leakage patterns (such as Detached DOM) are more reliable than statistical features.
[0049] 4) Structure > Type: Reference chain analysis contains more information than simple type judgment.
[0050] Confidence levels and decision recommendations are shown in Table 3: Table 3
[0051] The algorithm verification experiment is as follows: The validation was performed on 100 known memory leak cases and 50 normal memory growth cases, as shown in Table 4: Table 4
[0052] Compared with existing technologies, the specific comparisons are shown in Table 5: Table 5
[0053] The confidence scoring algorithm in this application is unique in existing technologies, filling a critical gap between "identification" and "judgment" of memory leaks, and significantly improving the reliability and operability of the detection results. Specifically, it includes: 1) Quantitative confidence level: For the first time, a confidence level scoring system for memory leaks is proposed, which transforms subjective judgment into objective scores.
[0054] 2) Multi-dimensional integration: Comprehensively assess the possibility of leakage by integrating the characteristics of 7 dimensions (growth rate, persistence, pattern matching, reference chain, type, stability, and business relevance).
[0055] 3) Explainability: Provides score breakdown and contribution of each dimension, so that developers can understand the scoring criteria.
[0056] 4) Decision support: Based on scores, it provides a 5-level classification and clear remediation suggestions to guide developers to prioritize high-risk leaks.
[0057] 5) Automatic filtering: Low confidence objects (<40 points) are automatically excluded, greatly reducing the workload of manual verification.
[0058] The reference chain analysis module is used to construct the reference path of suspected leaked objects, extract key reference nodes based on the dominance tree algorithm, and filter out non-business logic internal framework nodes. The reference chain analysis module is configured with a reference chain compression algorithm based on the dominator tree, specifically including: Construct a dominator tree for the heap memory graph and identify key node paths that have a dominance relationship with the leaked object; Identify and collapse the internal nodes of the frame in the path, and match the internal nodes of the frame with a preset frame feature library; Importance sampling is performed on reference paths that exceed the preset length, retaining GC root nodes, leaked object nodes, and high-weight business logic nodes; The compressed reference paths are converted into structured feature vectors, which serve as the input context for the AI model.
[0059] The data pruning effect verification is shown in Table 6: Table 6
[0060] These technical points in this application constitute a complete feature engineering pipeline, ensuring that the AI receives concise yet complete leakage information, thereby generating high-quality remediation suggestions, specifically including: 1) Reference path hashing algorithm: achieves cross-snapshot object matching through topological location features.
[0061] 2) Framework node identification rules: Based on a pattern matching blacklist mechanism, it supports mainstream frameworks such as React, Vue, and Angular.
[0062] 3) Node importance scoring model: multi-dimensional integration (business relevance + type salience + location criticality).
[0063] 4) Adaptive Token Budget Management: Dynamically adjust the level of detail of each component based on model constraints.
[0064] 5) Intelligent code block detection: Minimal code context extraction based on AST syntax analysis.
[0065] Table 7 shows a comparison of the actual effects of dominance tree compression: Table 7
[0066] Dominant tree compression is the core algorithm of this application, and it has the following beneficial effects: 1) Application of Dominant Tree Theory: This is the first time that the dominant tree theory in graph theory has been applied to the analysis of reference chains in memory leaks, which theoretically guarantees that the extracted "shortest path" is the "true cause chain" leading to the leak.
[0067] 2) Identification of key bridging nodes: Even if a framework node carries business semantics (such as React's state or Vue's data), it will be preserved to ensure context integrity.
[0068] 3) Intelligent sampling strategy: When the dominant path is still too long, intelligent sampling is performed based on the importance score of nodes, rather than simple equidistant sampling or truncation.
[0069] 4) Retained Size Transmission: Utilize the Retained Size calculation of the dominator tree to accurately identify which nodes make a substantial contribution to the leakage.
[0070] 5) O(n) complexity: The Lengauer-Tarjan algorithm guarantees that even for heap snapshots of millions of objects, the dominance tree can be constructed in seconds.
[0071] The SourceMap source code location module is used to build a mapping index from runtime script IDs to source code files, mapping the construction location and call stack of leaked objects to the path and row and column numbers of the original code; The SourceMap source code location module is configured with a multi-level mapping index cache, used to pre-build mapping relationships before snapshot collection. The index includes: The ScriptId mapping table stores the correspondence between runtime ScriptIds and the URLs of the bundled files, and dynamically tracks asynchronous chunks generated by code splitting. The Bundle mapping table stores the correspondence between Bundle file URLs and SourceMap files; The location mapping table stores the parsing results of the row and column numbers in the Bundle file to the original source code file path and row and column numbers; When locating, the module first queries the cached index; if no match is found, it parses the SourceMap file in real time and updates the cache.
[0072] The intelligent repair suggestion generation module is used to input the pruned reference chain features and source code context into an artificial intelligence (AI) model to generate repair suggestion code; The IDE visualization module is used to interactively display memory trends, reference chain structure, source code location markers, and repair suggestions within the IDE interface, and supports incremental verification.
[0073] The IDE visualization module and automated test execution module are also configured with an incremental verification mechanism to verify the repair effect: Listen for file save events in the IDE to identify code changes that involve leaked objects; Triggering browser module hot replacement (HMR) or targeted refresh via the MCP protocol, performing a minimal sequence of operations only on the affected leaked objects; Collect targeted small heap snapshots or object query results, and compare the changes in Retained Size before and after the repair; Update the status of leak diagnostic markers in real time within the IDE editor.
[0074] According to the above system, in some specific embodiments, the details are as follows: Example 1: System Architecture and MCP Communication Mechanism like Figure 1 As shown, this system includes an MCP server running in an IDE environment and a debugging agent running in a browser.
[0075] MCP communication module, such as Figure 2 As shown, a WebSocket connection is established to port 9222 of the browser. A protocol conversion adapter was designed to address the asynchronous event characteristics of the CDP protocol.
[0076] When the IDE initiates a browser.navigate request, the adapter generates a unique message ID, creates a pending Promise stored in the pendingRequests mapping table, and sends a CDP instruction. The adapter also listens for the Page.loadEventFired and Network.networkIdle events. Only when the page has fully loaded and network silence has exceeded 500ms (configurable) does the adapter resolve the pending Promise and return an MCP response to the IDE. This mechanism solves the problem of traditional scripts struggling to accurately determine when a page is "fully loaded".
[0077] Example 2: Heap Snapshot Incremental Analysis and Object Fingerprinting After obtaining multiple rounds (e.g., 5 rounds) of heap snapshots, traditional methods cannot make comparisons due to object ID reallocation. This embodiment uses an object fingerprint algorithm, such as... Figure 3 As shown: For object A in snapshot S1 and object B in snapshot S2, calculate fingerprints respectively: Fingerprint=Hash(AllocationStack+PropertySchema+ConstructorSource) AllocationStack: Extracts the function call stack at the time of object creation (taking the first 10 frames) and normalizes anonymous function names.
[0078] PropertySchema: Extracts all property names and their types from an object, ignoring volatile property values. ConstructorSource: Extracts the source code hash of the constructor function.
[0079] If Fingerprint(A) = Fingerprint(B), then they are considered to be the same logical object.
[0080] The system calculates the Retained Size of matching objects in each round of snapshots. If the size shows an increasing trend for N consecutive rounds, it is marked as a suspected leak.
[0081] Example 3: Leakage Confidence Scoring To reduce false alarms, the system calculates a confidence score (0-100) for suspected leak targets: Score = w1 × Growth Rate + w2 × Duration Rounds + w3 × Pattern Matching + w4 × Business Relevance Specifically, if the reference chain contains Detached DOM or Closure that has not been released, the pattern matching score is significantly improved; if the object's source code path is outside of node_modules (i.e., business code), the business relevance score is improved. Objects below the threshold (e.g., 60 points) are automatically filtered out.
[0082] Example 4: Reference Chain Analysis Based on Dominator Tree like Figure 4 As shown, the original reference chain may contain 50+ layers of nodes (e.g., Window→App→...→FiberNode→stateNode→...→LeakingObj).
[0083] The reference chain analysis module first constructs a dominance tree to identify the key nodes that dominate leaked objects. For example, although a FiberNode references an object, deleting App.userList is the key to releasing the object, so App.userList is the dominance node.
[0084] The module retains nodes on the dominant path and filters React / Vue internal nodes according to a preset blacklist, ultimately compressing the reference chain to Window→App.userList→User→LeakingObj (length < 10), significantly saving AI context tokens and highlighting business logic.
[0085] Example 5: SourceMap End-to-End Localization like Figure 5 As shown, the positioning module pre-builds an index cache: ScriptId Index: Listens to the Debugger.scriptParsed event, records the mapping between ScriptId and Bundle URL, and handles dynamically loaded Chunks in a special way.
[0086] SourceMap Index: Parse the Bundle URL to obtain the SourceMap address and cache the SourceMap content.
[0087] Location lookup: When an object needs to be located, the ScriptId and row / column number of the object in the snapshot are used to quickly find the 45th line of the original file (such as src / components / List.vue) by indexing, and extract the 5 lines of code before and after it as context.
[0088] Example 6: Intelligent Repair and Incremental Verification The system sends the leak type (e.g., "uncleaned timer"), the compressed reference chain, and the source code context to the AI. The AI then generates fix code (e.g., adding clearInterval in onUnmounted).
[0089] After the developer repairs and saves the file in the IDE application, the system triggers incremental verification, such as... Figure 6 As shown: The IDE notifies the system of file changes.
[0090] The system uses MCP to call Runtime.evaluate or the HMR interface to hot update the module.
[0091] Only the sequence of operations related to the leaked object (such as turning a specific component on / off) will be executed.
[0092] Perform garbage collection and check if the fingerprint of the object still exists in memory.
[0093] In the IDE, red error markers are updated to green fix markers in real time.
[0094] The specific technical effects of the intelligent repair and incremental verification method used in this embodiment are shown in Table 8: Table 8
[0095] In some specific embodiments, the use cases are as follows: Scenario 1: AI Fix Suggestions for Developer Applications 1) The IDE displays a leak warning: "Detached DOM leak at Modal.tsx:45"; 2) When the developer clicks "Application Repair Suggestion," the IDE automatically modifies the code; 3) Developers should press Ctrl+S to save the file; 4) Automatically triggers incremental verification (no manual operation required); 5) After 10 seconds, the IDE displays: "Memory Leak Fixed"; 6) The diagnostic information changes from red error to green success.
[0096] Scenario 2: Quick verification after developers manually fix the issue. 1) The developer manually modified the event listener cleanup code based on the report; 2) After saving the file, a pop-up appears in the lower right corner of the IDE: "Verify memory leak repair... (3 leak points)"; 3) Results will be displayed in 15 seconds: 2 have been fixed; One remains (the retained size is still growing); 4) When the developer clicks "View Details", the IDE jumps to the line of code where the leak still exists; 5) Continue modifying and verifying until all issues are fixed.
[0097] The incremental verification mechanism for IDEs based on the MCP protocol is architecturally impossible for existing tools like MemLab because they lack deep integration with the IDE and bidirectional real-time communication capabilities. This invention establishes a real-time data channel between the IDE and the browser through the MCP protocol, achieving a complete closed loop of "code modification → instant verification → real-time feedback," improving the efficiency of repair verification by tens of times. This constitutes a significant innovation compared to existing technologies (MemLab, Chrome DevTools, etc.), as detailed below: 1) Deep IDE integration: Utilizes the MCP protocol to achieve bidirectional real-time communication between the IDE and the browser, breaking through the limitations of MemLab's "CLI tool + static report" architecture.
[0098] 2) File save trigger: Listen for file save events in the IDE and automatically trigger incremental verification without requiring developers to manually run commands.
[0099] 3) Incremental verification algorithm: Verification is performed only on the leaked objects that have been modified, instead of rerunning the full test, reducing the verification time from minutes to seconds.
[0100] 3) Hot Module Reload (HMR) Exploitation: By leveraging Webpack / Vite's HMR capabilities, the repair effect can be verified without a full page refresh.
[0101] 4) Targeted operation sequence: Generate minimal triggering operations based on the leak type to avoid executing the full test process.
[0102] 5) Real-time diagnostic updates: Verification results are immediately fed back to the IDE's diagnostic system, and error markers are updated in real time (red → green).
[0103] 6) Confidence quantification: Provides confidence scores for validation results, distinguishing between "definite repair", "partial improvement" and "still exist".
[0104] 7) Verification History: Saves a complete record of each verification, supporting the backtracking and analysis of the repair process.
[0105] In summary, this invention achieves "autonomous driving" for browser memory debugging through deep integration with the MCP protocol. In particular, object fingerprinting technology solves the problem of dynamic object tracking, the dominator tree compression algorithm addresses the AI context constraint issue, and the SourceMap index solves the problem of engineering code mapping. Experiments show that this system can reduce memory leak detection time by more than 90%, and the accuracy rate of repair suggestions reaches 90%.
[0106] This invention focuses on the field of front-end browsers, enabling automatic location, analysis, and resolution of memory leaks in front-end browsers. This invention has the following beneficial effects: 1. Link Innovation (MCP-Driven): This is the first time that the MCP protocol has been proposed to connect the debugging ports of the IDE and the browser. Compared with the traditional ChromeDevTools protocol, MCP is more suitable for use in LLM (Large Language Model) driven development environments, improving the ability of AI to take over the debugging process.
[0107] 2. Process Innovation (Automated Consistency): Automated scripts ensure the consistency of the time sequence of "page loading → simulated operation → forced GC → snapshot collection". This solves the problem of "false leaks" caused by incorrect GC timing or inconsistent operation order during manual troubleshooting.
[0108] 3. Application Innovation (Closed-Loop Assisted Repair): Achieves end-to-end automation of "detection → location → mapping → repair". It directly connects to the high-level source code from the underlying reference chain, and finally, AI provides patch suggestions, greatly lowering the barrier to entry for front-end performance tuning.
[0109] The second aspect of this invention discloses an automatic browser memory leak location method based on the MCP protocol. The method employs the automatic browser memory leak location system based on the MCP protocol described in the first aspect, such as... Figure 7 As shown, the method includes: Step S1: Start the MCP server in the IDE and connect to the browser's debugging port via the WebSocket protocol; Step S2: Send instructions via the MCP protocol to control the browser to load the target page and establish a global index containing the mapping relationship between ScriptId and SourceMap; Step S3: Execute the automated test script to perform multiple rounds of page refresh operations, and force garbage collection and collect heap snapshots after each round of operations; Step S4: Perform incremental analysis on the collected multi-round snapshots, use the object fingerprint algorithm to match objects across rounds, and calculate the leakage confidence score; Step S5: For leaked objects with high confidence, construct a dominance tree and compress the reference chain, and use the SourceMap index to locate the source code location; Step S6: Send the compressed reference chain, source code context, and leakage characteristics to the AI model to generate repair suggestions and display them in the IDE.
[0110] A third aspect of this invention discloses a computer-readable storage medium. The computer-readable storage medium stores a computer program, which, when executed by a processor, implements the steps of the browser memory leak automatic location method based on the MCP protocol disclosed in the second aspect of this invention.
[0111] Please note that the technical features of the above embodiments can be combined arbitrarily. For the sake of brevity, not all possible combinations of the technical features in the above embodiments have been described. However, as long as the combination of these technical features does not contradict each other, it should be considered within the scope of this specification. The above embodiments only illustrate several implementation methods of this application, and their descriptions are relatively specific and detailed, but they should not be construed as limiting the scope of the present invention. It should be pointed out that for those skilled in the art, several modifications and improvements can be made without departing from the concept of this application, and these all fall within the protection scope of this application. Therefore, the protection scope of this application should be determined by the appended claims.
Claims
1. An automatic browser memory leak location system based on the MCP protocol, characterized in that, include: The MCP communication module, configured in the integrated development environment (IDE), is used to establish a bidirectional communication link with the browser debugging port through the Model Context Protocol (MCP), convert synchronous tool call requests into asynchronous browser debugging protocol (CDP) commands, and manage the session context. The automated test execution module is used to send control commands to the browser through the MCP communication module to execute automated operation sequences, including page navigation, multiple rounds of refresh, and forced garbage collection (GC), and dynamically adjust the test strategy based on intermediate analysis results. The heap snapshot acquisition module is used to collect heap memory snapshots of the browser after each round of operation and GC, and parse the snapshot data structure. The Heap Snapshot Comparison and Incremental Analysis module is used to perform differential calculations on multiple rounds of heap snapshots. By matching fingerprints across snapshot objects, it identifies object increments and calculates the confidence score of suspected leaked objects. The reference chain analysis module is used to construct the reference path of suspected leaked objects, extract key reference nodes based on the dominance tree algorithm, and filter out non-business logic internal framework nodes. The SourceMap source code location module is used to build a mapping index from runtime script IDs to source code files, mapping the construction location and call stack of leaked objects to the path and row and column numbers of the original code; The intelligent repair suggestion generation module is used to input the pruned reference chain features and source code context into the artificial intelligence model to generate repair suggestion code; The IDE visualization module is used to interactively display memory trends, reference chain structure, source code location markers, and repair suggestions within the IDE interface, and supports incremental verification. The MCP communication module includes a protocol conversion adapter, which is configured with: The Promise suspension mechanism is used to maintain a queue of unfinished MCP requests, map synchronous calls of MCP to suspended Promise objects, and resolve the Promise when the corresponding CDP response or event is received. Event-driven synchronization encapsulation is used to subscribe to asynchronous lifecycle events of the browser, encapsulating page load completion, network idle, and GC completion events into waitable synchronous signals; A streaming data aggregator is used to receive chunked heap snapshot data streams, cache them locally, and reassemble them into complete snapshot files.
2. The system according to claim 1, characterized in that, The heap snapshot comparison and incremental analysis module includes an object fingerprint generation unit, used to generate a unique object identifier that remains stable across page refreshes. The object fingerprint is composed of a weighted combination of the following features: Construct stack frame characteristics based on hash values generated from the complete function call chain and script location at the time of object creation; Attribute structure characteristics, a hash value generated based on the set of object's own attribute names and attribute type structure; Constructor signature, based on the normalized hash value of the object's constructor source code; Reference topology features are feature values generated based on the hierarchy and connectivity of objects in the heap memory reference graph; The heap snapshot comparison and incremental analysis module uses the object fingerprint to perform a one-to-one mapping of objects when comparing snapshots from different rounds.
3. The system according to claim 1, characterized in that, The heap snapshot comparison and incremental analysis module also includes a leakage confidence scoring unit, used to calculate the confidence score of suspected leakage objects based on multi-dimensional features, which at least include: Retained Size Growth Rate: The average percentage increase in the object's retained memory size over test rounds; The frequency with which the memory size of an object increases across consecutive test rounds; Leakage pattern matching degree, the degree of matching between object characteristics and a preset leakage pattern library, the pattern library including detached DOM nodes, uncleaned timers, and unbound event listeners; Reference chain characteristics: whether the reference path contains global variables, closures, or specific framework lifecycle objects.
4. The system according to claim 1, characterized in that, The reference chain analysis module is configured with a reference chain compression algorithm based on the dominator tree, specifically including: Construct the dominance tree of the heap memory graph and identify the key node paths that have a dominance relationship with the leaked object; Identify and collapse the internal nodes of the frame in the path, and match the internal nodes of the frame with a preset frame feature library; Importance sampling is performed on reference paths that exceed the preset length, retaining GC root nodes, leaked object nodes, and high-weight business logic nodes; The compressed reference paths are converted into structured feature vectors, which serve as the input context for the AI model.
5. The system according to claim 1, characterized in that, The SourceMap source code location module is configured with a multi-level mapping index cache, used to pre-build mapping relationships before snapshot collection. The index includes: The ScriptId mapping table stores the correspondence between runtime ScriptIds and the URLs of the packaged Bundle files, and dynamically tracks asynchronous chunks generated by code splitting; The Bundle mapping table stores the correspondence between Bundle file URLs and SourceMap files; The location mapping table stores the parsing results of the row and column numbers in the Bundle file to the original source code file path and row and column numbers; When locating the source map, the SourceMap source code location module first queries the cache index. If it does not find the target, it parses the SourceMap file in real time and updates the cache.
6. The system according to claim 1, characterized in that, The automated test execution module has an adaptive test strategy driven by the MCP protocol, specifically including: After the initial test rounds are completed, the incremental analysis module is invoked in real time to obtain intermediate results; Based on the memory growth trend and the number of Detached DOMs in the intermediate results, the subsequent testing strategy is dynamically adjusted through the MCP session context; The adjusted subsequent testing strategy includes: automatically increasing the number of test rounds when the growth is not significant; extending the GC wait time and increasing the GC intensity when a large number of Detached DOMs are detected but memory usage does not increase; and terminating the test early and entering the deep analysis phase when a high-confidence leak is detected.
7. The system according to claim 1, characterized in that, The IDE visualization module and the automated test execution module are also configured with an incremental verification mechanism to verify the repair effect: Listen for file save events in the IDE to identify code changes that involve leaked objects; Triggering browser module hot replacement or targeted refresh via the MCP protocol, performing a minimal sequence of operations only on the affected leaked objects; Collect targeted small heap snapshots or object query results, and compare the changes in Retained Size before and after the repair; Update the status of leak diagnostic markers in real time within the IDE editor.
8. A method for automatically locating browser memory leaks based on the system described in any one of claims 1-7, characterized in that, Includes the following steps: Step S1: Start the MCP server in the IDE and connect to the browser's debugging port via the WebSocket protocol; Step S2: Send instructions via the MCP protocol to control the browser to load the target page and establish a global index containing the mapping relationship between ScriptId and SourceMap; Step S3: Execute the automated test script to perform multiple rounds of page refresh operations, and force garbage collection and collect heap snapshots after each round of operations; Step S4: Perform incremental analysis on the collected multi-round snapshots, use the object fingerprint algorithm to match objects across rounds, and calculate the leakage confidence score; Step S5: For leaked objects with high confidence, construct a dominance tree and compress the reference chain, and use the SourceMap index to locate the source code location; Step S6: Send the compressed reference chain, source code context, and leakage characteristics to the AI model to generate repair suggestions and display them in the IDE.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements the method of claim 8.