Beyond Input Guardrails: Reconstructing Cross-Agent Semantic Flows for Execution-Aware Attack Detection Yangyang Wei, Yijie Xu, Zhenyuan Li, Xiangmin Shen, Shouling Ji Abstract Multi-Agent System is emerging as the de facto standard for complex task orchestration. However, its reliance on autonomous execution and unstructured inter-agent communication introduces severe risks, such as indirect prompt injection, that easily circumvent conventional input guardrails. To address this, we propose MAScope, a framework that shifts the defensive paradigm from static input filtering to execution-aware analysis. By extracting and reconstructing Cross-Agent Semantic Flows, MAScope synthesizes fragmented operational primitives into contiguous behavioral trajectories, enabling a holistic view of system activity. We leverage a Supervisor LLM to scrutinize these trajectories, identifying anomalies across data flow violations, control flow deviations, and intent inconsistencies. Empirical evaluations demonstrate that MAScope effectively detects over ten distinct compound attack vectors, achieving F1-scores of 85.3% and 66.7% for node-level and path-level end-to-end attack detection, respectively. The source code is available at https://anonymous.4open.science/r/MAScope-71DC . 1 Introduction Large Language Models (LLMs) have demonstrated remarkable efficacy across expanding domains ( 15 ; 8 ) . However, when applied to complex, open-ended tasks, solitary models often face limited reasoning horizons and intrinsic hallucinations ( 27 ; 16 ) . To overcome these bottlenecks, Multi-Agent System (MAS) is emerging as the de facto standard for orchestrating intricate workflows, with platforms like AutoGen and LangGraph now managing millions of autonomous interactions daily across sectors ranging from automated software engineering to financial analysis. By integrating role specialization and collaborative planning, MAS can effectively address long-horizon reasoning challenges and decompose tasks that are otherwise intractable for single models ( 19 ) . Figure 1 : OWASP Top 10 Attack Surfaces in MAS However, this architectural paradigm shift inherently expands the attack surface. By relying on autonomous execution and open-ended inter-agent communication, MAS introduces critical vulnerabilities, including indirect prompt injection and privilege escalation. Crucially, these systems do not merely expand the threat landscape quantitatively but complicate it qualitatively: vulnerabilities emerge not only from individual agent defects but also from the interaction dynamics, coordination logic, and transitive trust dependencies that permeate the system lifecycle ( 24 ) . These threats manifest across the entire execution spectrum, ranging from input-level prompt manipulation and interaction-stage memory poisoning or channel interception, to output-stage tool misuse, where dynamic delegation amplifies the cascading impact of unauthorized system modifications ( 21 ; 3 ) , as Figure 1 shown. A central challenge lies in the semantic ambiguity and execution fragmentation inherent to these threats. Unlike monolithic applications, MAS dissolves architectural boundaries, relying on agents driven by unstructured inputs and probabilistic logic. Consequently, attackers can orchestrate multi-step exploits by chaining seemingly innocuous micro-operations, fragmented across different agents and time steps, that only manifest as malicious when viewed as a complete sequence. Conventional input guardrails and sandboxing are rendered insufficient against such threats. They struggle to perform fine-grained extraction of critical fields from unstructured natural language interactions and lack the semantic situational awareness required to distinguish complex legitimate behaviors from malicious intent ( 9 ) . Thus, shifting from static input filtering to dynamic, execution-aware monitoring remains a formidable challenge. To address this gap, this paper proposes MAScope, a unified framework that shifts the defensive paradigm to execution-aware analysis by observing and abstracting Cross-Agent Semantic Flows. Our methodology centers on three key innovations to tackle the aforementioned challenges. First, we address unstructured ambiguity by abstracting sensitive entities and operational primitives from raw interaction logs. Second, we tackle attack fragmentation by reconstructing contiguous behavioral execution trajectories from dispersed inter-agent communications and artifact manipulations. Finally, to resolve the benign-versus-malicious distinction, we leverage a dedicated Supervisor LLM to scrutinize these reconstructed flows, detecting anomalies across data flow violations, control flow deviations, and intent inconsistencies. To evaluate the effectiveness of MAScope, we empirically reproduce the OWASP Top 10 attack techniques targeting various stages of the MAS lifecycle. By integrating these techniques into diverse operational scenarios, we synthesize and execute a series of compound attacks. Experimental results demonstrate that MAScope effectively abstracts sensitive fields, reconstructs suspicious behavioral trajectories, and successfully detects over ten distinct combinations of attack vectors. Quantitatively, the framework exhibits robust performance, attaining an F1-score of 76.8% for sensitive information extraction, along with F1-scores of 85.3% and 66.7% for node-level and path-level end-to-end attack detection, respectively. All in all, our contributions can be concluded as follows: • Methodology Proposal. We propose an innovative methodology that accurately identifies violations in data and control flows by abstracting sensitive entities from unstructured logs and reconstructing discrete communications into continuous behavioral trajectories. • Semantic Flows Framework. We introduce the MAScope framework to transition the defense paradigm toward execution-aware analysis by analyzing cross-agent semantic flows. • Empirical Evaluation. We reproduced the OWASP Top 10 vulnerabilities and complex attack scenarios for testing. The results demonstrate that MAScope accurately extracts sensitive fields, reconstructs suspicious trajectories, and successfully detects over ten types of combined attacks. 2 Background and Related Work 2.1 Emerging Multi-Agent System While LLMs demonstrate remarkable versatility, their direct application to complex problem-solving is often constrained by intrinsic hallucinations and limited reasoning horizons. To address these limitations, MAS such as LangGraph 1 1 1 LangGraph, https://www.langchain.com/langgraph , AutoGen 2 2 2 AutoGen, https://microsoft.github.io/autogen , and MetaGPT 3 3 3 MetaGPT, https://github.com/FoundationAgents/MetaGPT have emerged, utilizing role-based orchestration and Standardized Operating Procedures (SOPs) to decompose intricate tasks into manageable sub-routines. Currently, these frameworks predominantly rely on sandboxed environments (e.g., Docker) and human-in-the-loop oversight to mitigate execution risks. However, these measures often overlook the deeper architectural implications. Analogous to how microservices dismantled the boundaries of monolithic applications, thereby expanding the attack surface, MAS similarly dissolves the rigid constraints of deterministic software. That is, unlike traditional services bound by structured APIs, agents possess the autonomous capability to process unstructured data and maintain persistent context. Furthermore, MAS exhibits emergent collaborative intelligence through dynamic orchestration, intent alignment, and information sharing. This transition from rigid, formatted interactions to adaptive, general-purpose services, while enabling solutions for complex open environments, inherently introduces non-deterministic behavioral spaces and novel semantic security risks. To systematize these threats, the OWASP Foundation ( 24 ) has categorized the Top 10 attack surfaces spanning the input, interaction, and output stages, as illustrated in Figure 1 . Further details are provided in the Appendix A . 2.2 Defence for LLMs and LLM-based Agents Guardrail-based defenses serve as the first line of defense, primarily mitigating threats such as prompt injection by intercepting, inspecting, and sanitizing model inputs and outputs ( 4 ; 14 ) . While effective in neutralizing single-turn adversarial exchanges, these approaches typically rely on static heuristics or context-agnostic filters. Consequently, they remain vulnerable to attacks that exploit multi-step reasoning, contextual dependencies, or semantic deception embedded across prolonged interaction histories. To transcend the limitations of local I/O filtering, structural and graph-based approaches have emerged. These methods model agent interactions as graphs, identifying potential threats by analyzing propagation paths and applying structural interventions, such as edge pruning, to disrupt attack flows ( 26 ) . However, their effectiveness is often predicated on the assumption that underlying models possess a baseline level of safety. Furthermore, they struggle to detect malicious intent when semantic manipulation is camouflaged within structurally valid interaction trajectories, effectively bypassing topology-based detection. A parallel line of research focuses on pre-execution constraints and formal verification, aiming to synthesize deterministic safety policies that block unsafe actions prior to execution ( 23 ) . While providing theoretical safety guarantees for isolated decision steps, these methods face significant scalability challenges in open-ended agentic environments. Crucially, they lack a holistic view of system-level state evolution, making it difficult to trace the causal origins of attacks or assess their impact on global system artifacts (e.g., file systems and network endpoints) across complex, multi-agent workflows. 3 Preliminaries This section introduces the notation and formalizes the key concepts used throughout the paper. We define the structure of the Cross-Agent Semantic Graph and formulate two main problems in the threat detection task. 3.1 Cross-Agent Semantic Graph Inspired by provenance-based threat detection ( 20 ; 13 ) , we construct a semantic graph framework to characterize the cross-agent behavior of multi-agent systems. In a MAS, each interaction e can be defined as a quintuple (l,s,r,o,t) , where l , s , r , o , and t denote the layer, subject, relationship, object, and timestamp, respectively. Table 1 provides detailed mappings of the dependency relationships for different types of events. These events collectively form a MAS semantic graph G , which is defined as: \displaystyle G=\{e_{1},e_{2},\ldots,e_{n}\} (1) where each event e_{i}=(l_{i},s_{i},r_{i},o_{i},t_{i})\in G denotes a temporal update to the graph structure. 3.2 Problem Definition We formulate the detection of multi-stage attacks as a two-step optimization problem: mapping unstructured logs to structured semantic primitives, and then reconstructing causal flows to identify anomalies. Semantic Primitives Extraction. Given a raw log entry u\in\mathcal{L} associated with a potential event, and a foundation model P_{\theta} , the goal is to extract a set of structured semantic primitives Y . These primitives include both Sensitive Entities (e.g., credentials, PII) and Operational Primitives (e.g., specific tool parameters). We formulate this as a constraint-based conditional generation task. Let \mathcal{C} be the hierarchy of predefined sensitive categories. The extraction function f(u,\mathcal{C}) outputs a set of labeled pairs: y_{i}=\{(s,\ell)\mid(s,\ell)\sim P_{\theta}(Y\mid u,\tau_{\mathcal{C}})\} (2) where s is the extracted entity text, \ell\in\mathcal{C} is the semantic category, and \tau_{\mathcal{C}} represents the hierarchical constraint instructions (HSEC). The objective is to maximize the likelihood of correctly identifying all relevant entities y_{i} for every event e_{i} , thereby populating the attributes of the semantic graph nodes. Flow Reconstruction and Threat Detection. Locally, a single event e_{i} may appear benign. To detect complex threats, we must analyze Behavioral Flows. Let \mathcal{H} be the space of all possible execution paths within graph G . We define a candidate behavioral trajectory T_{k}\in\mathcal{H} as a time-ordered sequence of causally dependent events ending at a terminal node n : T_{k}=\langle e_{k_{1}},e_{k_{2}},\ldots,e_{k_{m}}\rangle, (3) where e_{k_{j+1}} depends on e_{k_{j}} . The detection problem is to define a Flow Reconstruction Function \Phi(G) that synthesizes fragmented events into candidate trajectories, and a Scrutiny Function \mathcal{S}(T_{k}) (parameterized by the Supervisor LLM) that estimates the maliciousness of a trajectory. The goal is to identify the subset of optimal attack paths \mathcal{T}^{*} that maximize the risk score: \mathcal{T}^{*}=\{T_{k}\in\Phi(G)\mid\mathcal{S}(T_{k})>\delta\} (4) where \mathcal{S}(\cdot) evaluates the trajectory against data flow, control flow, and intent consistency policies, and \delta is the decision threshold. Table 1 : Dependency Event Relationships in MAS Layer Subject Object Relationship Agent Agent Agent Agent_Invoke; Agent_Resp Process Process_Start; Process_End Kernel Process Process Process_Start; Process_End File File_Read; File_Write Network IP_Send; IP_Receive Figure 2 : MAScope Overview 4 Method As illustrated in Figure 2 , MAScope comprises three interconnected modules: (1) a Data Collection Module that captures fine-grained interaction data between agents and system entities; (2) a Semantic Extracting & Flow Reconstruction Module that analyzes unstructured interaction logs to extract semantic primitives and synthesize execution flows; and (3) a Trajectory Scrutiny Module that audits these reconstructed paths to identify and detect latent attack vectors. 4.1 Data Collection in MAS Building upon the formal definitions in § 3 , we operationalize the construction of the MAS semantic graph. It is crucial to recognize that while tool calls initiated by agents ultimately manifest as specific system events handled by kernel-level processes, relying exclusively on traditional kernel monitoring is insufficient to encompass the full observational scope of a MAS. Agents introduce high-level semantics, specifically intent, context, and reasoning chains, at the application layer, which typically elude capture by low-level kernel instrumentation. To bridge this semantic gap and address the challenge of scattered, temporally inconsistent cross-layer data, we implement a dual-layer observation strategy. This involves integrating observations from both application and kernel layers, performing temporal alignment, and normalizing entity identifiers to uniformly incorporate heterogeneous data into the semantic graph. As illustrated in Figure 2 , kernel collectors (e.g., ETW ( 6 ) , eBPF ( 5 ) ) are primarily responsible for monitoring the behavior of system process entities, while application-layer collectors (e.g., structured logging mechanisms ( 22 ) ) capture the high-level interactive behaviors of agents. We denote each raw log record as a structured tuple containing rich contextual information: L_{i}=\{\text{Log}_{i},\text{Sub}_{i},\text{Obj}_{i}\} (5) where \text{Log}_{i} encompasses basic log attributes (e.g., timestamp, log type), \text{Sub}_{i} denotes the subject context, and \text{Obj}_{i} denotes the object context. Following acquisition, we deserialize and parse these records to instantiate the semantic event e=(l,s,r,o,t) for subsequent graph construction and analysis. 4.2 Semantic Extracting & Flow Reconstruction Following data collection, we parse unstructured interaction logs to identify sensitive information and reconstruct the multi-agent semantic graph. This phase entails two critical objectives: (i) the precise extraction of security-relevant entities from free-form context, and (ii) the quantitative assignment of sensitivity scores to prioritize suspicious paths for downstream scrutiny. Directly applying general-purpose foundation models for open-domain sensitive information extraction often results in the retrieval of irrelevant entities and coarse-grained labels. This introduces significant noise, as the model may fail to distinguish benign references (e.g., city names in public news) from privacy-sensitive data (e.g., residential addresses), leading to both false positives and false negatives. To mitigate these issues, we propose the Hierarchical Sensitive Entity Constraint (HSEC) mechanism. As illustrated in Figure 3 , HSEC transforms abstract security knowledge into structured, hierarchical constraints. For instance, rather than a generic ”Location” label, HSEC maps entities to the subcategory Contact Information under the parent category Identity & Privacy . This hierarchical structure compels the model to evaluate entity attributes within an explicit risk context, significantly enhancing robustness against semantic ambiguity. Figure 3 : Hierarchical Sensitive Entity Constraint We formulate the extraction task as a constraint-based conditional sequence generation problem. Let x denote the interaction content, encompassing agent messages, tool inputs/outputs, file paths, URLs, and associated kernel artifacts. Our goal is to predict a specific set of sensitive entities Y=\{y_{1},\dots,y_{n}\} and their corresponding sensitivity attributes via a mapping f(x)\rightarrow(Y,\mathcal{L}) . Specifically, HSEC constrains the model to generate triples (y_{i},c_{i},sc_{i}) , where c_{i} and sc_{i} denote the top-level category and subcategory, respectively. Post-generation, we apply lightweight canonicalization \phi(\cdot) to normalize case, strip punctuation, and resolve relative file paths, ensuring graph consistency by storing \phi(y_{i}) . Besides, we assign each extracted entity a continuous sensitivity score s(y)\in[0,1] . We decompose the score into a sensitive category prior and context adjustments: s(y)=b(c,sc)+\Delta_{\text{ctx}}(y,x) (6) Here, b(c,sc) is a fixed base sensitivity weight per category and subcategory. For example, Credential & Secrets receives the highest base weight, Identity & Privacy is medium, and System & Infrastructure and Code & Payloads are medium-to-high depending on the subcategory. The context term \Delta_{\text{ctx}} captures security cues that cannot be represented by sensitive categories alone, computed deterministically from y and its local context x . Let \pi_{k}(y,x)\in\{0,1\} indicate whether cue k is present, where k\in\{\text{pat},\text{ent},\text{path},\text{net}\} correspond to (i) matching a secret-like pattern, (ii) high-entropy strings, (iii) sensitive file or directory paths, and (iv) appearing as an egress destination. The adjustment is computed as: \Delta_{\text{ctx}}(y)=\sum_{k}\delta_{k}\cdot\mathbb{I}\!\left[\pi_{k}(y)\right], (7) where \delta_{k} denotes the marginal risk contribution of cue k . To identify the most critical latent malicious behavioral trajectories for scrutiny, we prioritize candidate provenance paths based on aggregated risk. We define a weighted event risk score w(e_{i}) that integrates entity sensitivity, operation type, and target trustworthiness: w(e_{i})=\left(\sum_{y\in\mathcal{E}(e_{i})}s(y)\right)\cdot\alpha_{r_{i}}\cdot\left(1+\beta\cdot\mathbb{I}[d(o_{i})\notin\mathcal{T}]\right) (8) where \mathcal{E}(e_{i}) is the set of entities involved in event e_{i} , and \alpha_{r_{i}} is a relation-dependent weight (assigning higher values to critical operations like IP_Send or File_Read ). The term \mathbb{I}[d(o_{i})\notin\mathcal{T}] serves as a penalty factor, increasing the score by \beta if the object’s domain d(o_{i}) does not belong to the trusted set \mathcal{T} (e.g., known internal services). Finally, we score a candidate provenance path H(n)=\langle e_{1},\dots,e_{m}\rangle ending at node n by aggregating its constituent event scores with a temporal decay factor: \text{Score}(H(n))=\sum_{i=1}^{m}\gamma^{(t_{m}-t_{i})}\cdot w(e_{i}) (9) where \gamma\in(0,1] applies a mild recency discount to emphasize immediate threats while retaining historical context. The top-ranked paths are then forwarded to the Supervisor module for deep semantic verification. 4.3 Trajectory Scrutiny To identify potential attacks in multi-agent systems, we design a supervisor module based on a foundation model that audits the reconstructed paths in the semantic graph against a set of rigorous security policies. As illustrated in Figure 1 , attacks on MAS typically manifest across the input, interaction, and output stages. A high-level analysis of complete attack causal chains reveals that successful exploits invariably distort one of three core dimensions: (1) the Data Flow (how information propagates between nodes); (2) the Control Flow (how authority and context are transferred); and (3) the Intent Alignment (whether the system’s actual behavior adheres to the user’s initial objective). Attacks achieve penetration by compromising these factors individually or in combination. Based on this observation, we build three corresponding policies around these three types of factors to identify and intercept attack behaviors: intent consistency, data flow confidentiality, and control flow integrity, as shown in Table 2 . In this table, H(n) is a provenance path of time-ordered events associated with node n , s_{\text{sens}} is the set of sensitive entities, and o_{\text{ext}} is the set of untrusted external destinations on the path. s_{\text{perm}} and o_{\text{perm}} denote the privilege levels of the source and target nodes, respectively. To evaluate intent consistency, we need an explicit representation of the user-approved intent for the current task. We obtain P_{\text{intent}} from the initial user request and the agent’s declared plan. Concretely, we prompt a foundation model to produce a short structured intent specification that includes (i) the allowed goal(s), (ii) required resources (e.g., files, repositories, or tools) and their scopes, and (iii) explicit constraints (e.g., “do not exfiltrate data” or “do not contact external endpoints unless necessary”). We treat this structured intent specification as P_{\text{intent}} and use it as the reference when checking whether a provenance path contains actions that deviate from the stated goal or violate stated constraints. In our implementation, P_{\text{intent}} is generated once per session and can be optionally overridden by a user-defined policy template. We define sensitive entities using a threshold on numeric sensitivity scores from § 4.2 : s_{\text{sens}}=\{y\mid s(y)\geq\tau_{\text{sens}}\}, (10) where \tau_{\text{sens}} is a policy parameter. For confidentiality checks, we also identify untrusted external destinations on a path. For each event e_{i} whose object o_{i} is a network endpoint, we normalize the destination as: d(o_{i})=\begin{cases}\text{base\_domain}(o_{i})&\text{if }o_{i}\text{ is a URL/domain},\\ o_{i}&\text{if }o_{i}\text{ is an IP address}.\end{cases} (11) We mark o_{i} as untrusted if d(o_{i})\notin\mathcal{T} , where \mathcal{T} is a configurable trusted set (e.g., allowlist domains, localhost, and private IP ranges), and define o_{\text{ext}}=\{d(o_{i})\mid d(o_{i})\notin\mathcal{T}\} for events on the path. The confidentiality policy then checks whether any sensitive entity flows to untrusted external destinations via s_{\text{sens}}\cap o_{\text{ext}}\neq\emptyset . We estimate the privilege level of each node using a foundation model conditioned on node attributes and local execution context. The input features include (i) process and user identity (e.g., user SID/UID, integrity level, token/role), (ii) execution context (e.g., parent process, service vs. interactive session), and (iii) operation type and object metadata (e.g., access to protected paths, registry hives, or privileged system calls). The model maps these signals to an ordinal privilege level (e.g., low , user , admin / root ). We assign s_{\text{perm}} and o_{\text{perm}} to the source and target nodes by applying this estimator to their associated context on the provenance path. Given P_{\text{intent}} and the selected provenance path H(n) , the supervisor evaluates whether any policy is violated (intent consistency, confidentiality, or integrity). The supervisor outputs (i) a binary decision y\in\{0,1\} indicating whether a violation is detected, and (ii) a short evidence string that cites concrete event attributes (e.g., destination d(o) , tool names, file paths, or commands) to make alerts explainable. Table 2 : Policy Violation Definitions Policy Violation Condition Intent Consistency \neg P_{\text{intent}}(\text{H}(n),\tau) Data Flow Confidentiality \exists s,o\in\text{H}:s_{\text{sens}}\cap o_{\text{ext}}\neq\varnothing Control Flow Integrity \exists s,o\in\text{H}:s_{\text{perm}}