Skip to Content
You are currently on the new version of our website. Access the old version .
Applied SciencesApplied Sciences
  • Article
  • Open Access

11 August 2026

25 Pages

SecureMCP: Policy-Enforced Defense Against Prompt Injection in LLM-Generated SQL for AIoT Databases

,
and
1
Data Science Lab Co., Ltd., Seoul 05855, Republic of Korea
2
Department of Computer Science and Engineering, Hoseo University, Asan 31499, Republic of Korea
*
Author to whom correspondence should be addressed.

Abstract

The deployment of Large Language Model (LLM)-generated SQL in Artificial Intelligence of Things (AIoT) systems introduces critical security risks, as prompt injection attacks can manipulate LLMs into producing unauthorized queries that expose sensitive data or execute destructive operations. Existing Natural Language to SQL (NL2SQL) research targets query accuracy, while current Model Context Protocol (MCP) servers offer only SQL-level protection without fine-grained, role-based access control. This paper proposes SecureMCP, a policy-enforced framework that integrates Role-Based Access Control (RBAC) with an MCP server to establish multi-layer defense for LLM-generated SQL execution. Grounded in an explicit threat model, the framework chains five defense modules in a sequential fail-closed pipeline addressing six prompt injection types spanning four adversary goals. We evaluate SecureMCP on the IoT-SQL dataset using Qwen3-8B, reporting filter performance—false positive rate (FPR) and false negative rate (FNR)—separately from LLM generation quality. On benign queries, the framework maintains a low false positive rate (0.3–2.2%) across four RBAC roles while keeping execution accuracy among allowed queries within 65.1–76.4%, matching the unprotected baseline of 63.8% and confirming that the defenses act as a transparent pre-execution filter. On 2400 adversarial queries, SecureMCP limits the effective false negative rate—computed over realized threats in which the injection payload was actually incorporated—to 3.98%, and an ablation confirms that RBAC and MCP-level defenses are complementary, as neither blocks the full range of injection vectors alone. The 72.5% injection incorporation rate confirms high LLM susceptibility, establishing the necessity of external policy enforcement.

1. Introduction

1.1. Background

The rapid expansion of Artificial Intelligence of Things (AIoT) ecosystems has produced an unprecedented volume of data generated by interconnected sensors, network devices, and building management systems [1]. Modern smart buildings, industrial facilities, and critical-infrastructure deployments routinely collect network traffic logs, sensor readings, device metadata, and environmental measurements, storing them in relational databases that serve as the operational backbone for monitoring, anomaly detection, and decision support. As these databases grow in scale and complexity, the demand for intuitive data access interfaces has intensified, particularly for non-expert stakeholders such as facility managers, auditors, and field engineers who lack proficiency in Structured Query Language (SQL) [2].
Large Language Models (LLMs) have emerged as a transformative technology for bridging natural language and structured database queries, a paradigm known as Natural Language to SQL (NL2SQL) [3,4]. Recent instruction-tuned LLMs, including GPT-4, Llama-3, and the Qwen series, achieve execution accuracy approaching human-level performance on established benchmarks such as Spider [5], WikiSQL [6], and BIRD [7]. The appeal of LLM-driven NL2SQL is especially strong in AIoT settings, where diverse user roles require access to heterogeneous data sources under varying operational constraints.

1.2. The Execution-Stage Security Problem

The deployment of LLM-generated SQL in production AIoT environments, however, introduces challenges fundamentally different from those addressed by benchmark-oriented accuracy research. When an LLM translates a natural language request into SQL and the resulting statement is executed against a live database of sensitive operational data, the consequences of an erroneous or malicious query extend far beyond an incorrect result set. A single unauthorized query can expose personally identifiable information such as source IP addresses and device MAC addresses, reveal the database schema to potential attackers, trigger resource-exhaustive full-table scans that degrade availability, or execute destructive Data Definition Language (DDL) operations that compromise data integrity [8,9]. These risks are amplified in AIoT environments, where databases hold network security logs, device configurations, and sensor data subject to regulatory compliance and organizational access policies [10].
This execution-stage exposure is compounded by prompt injection, in which adversarial instructions embedded in a natural language request manipulate the LLM into emitting harmful SQL. Recent studies have examined LLM security from complementary angles—federated learning with local differential privacy to protect LLM-based chatbots from data poisoning [11], and LLM-driven generation of security rating questionnaires for AIoT environments [12]—yet none address the execution-stage security of LLM-generated database queries, which is the focus of the present work.

1.3. Research Gaps

The gap between NL2SQL research and secure real-world deployment manifests in three dimensions.
First, NL2SQL research overwhelmingly optimizes generation accuracy while neglecting execution-stage security. The dominant evaluation paradigm measures whether a generated query reproduces a gold-standard result, not whether the query should be permitted to execute at all [3,4,5,6,7]. This leaves a critical blind spot: a query that is syntactically correct and semantically accurate may still violate organizational access policies, read sensitive columns beyond the user’s authorization, or impose unacceptable computational cost on the database server.
Second, the Model Context Protocol (MCP), introduced by Anthropic in November 2024 as an open standard for connecting LLMs to external tools and data sources [13], has been rapidly adopted across numerous database server implementations, prompting systematic analysis of its emerging security risks [14]. Early implementations proved vulnerable to security exploits, and even security-hardened community successors operate exclusively at the SQL-statement level, without role-based restrictions on which tables, columns, and operations a given user may access (Section 2.2). Consequently, any authenticated user can query any table and column within the permitted database, regardless of organizational role.
Third, AIoT databases impose security requirements that existing NL2SQL benchmarks do not capture. IoT schemas typically contain sensitive fields—source and destination IP addresses in traffic logs, MAC addresses and physical locations in device registries, and query domains in DNS logs—that must be protected according to the requesting user’s role [10]. A network administrator may legitimately require raw IP addresses for threat investigation, whereas a facility manager should see only aggregated sensor statistics. Standard benchmarks such as Spider [5] and WikiSQL [6] do not model these role-based scenarios, and the systems evaluated on them therefore provide no mechanism for enforcing differentiated access policies.

1.4. Proposed Approach and Contributions

To address these gaps, this paper proposes SecureMCP, a policy-enforced LLM data access framework that integrates Role-Based Access Control (RBAC) with MCP server built-in security to establish multi-layer defense for LLM-generated SQL execution in AIoT systems. The primary contribution lies not in the novelty of any individual defense algorithm, but in the systematic formulation of execution-stage security for NL2SQL pipelines as a distinct research problem, the design of a threat-informed defense architecture, and the empirical demonstration that integrating established techniques yields emergent security properties unattainable by any single component alone.
The contributions of this study are fourfold:
  • We formalize the NL2SQL execution-stage security problem and propose the SecureMCP framework, which combines an RBAC policy module with an MCP server through five defense modules covering six categories of prompt injection grounded in the OWASP Top 10 for LLM Applications [15], establishing a threat-model-driven mapping between injection types and primary defense modules that guides the fail-closed pipeline design.
  • We design a two-experiment evaluation methodology: Experiment A measures execution accuracy under clean SQL conditions across four RBAC roles, while Experiment B assesses injection robustness on 2400 adversarial queries spanning six injection types, quantifying each module’s contribution and distinguishing LLM-resistant cases from genuine defense failures.
  • We demonstrate through ablation analysis that RBAC alone and MCP built-in modules alone each leave substantial gaps (effective FNR of 27.53% and 17.93%, respectively), whereas the integrated framework attains an overall block rate of 82.3% and reduces the effective FNR to 3.98% while preserving baseline execution accuracy for authorized queries.
  • We conduct all experiments on the IoT-SQL dataset [16]—11 tables, 173 columns, and 239,398 records derived from IoT-23 network traffic [17] and smart building sensor data—providing the first empirical evidence of prompt injection risks specific to IoT database environments.
The remainder of this paper is organized as follows. Section 2 reviews related work and identifies research gaps. Section 3 presents the threat model. Section 4 describes the SecureMCP framework architecture, defense modules, and experimental setup. Section 5 reports experimental results. Section 6 discusses findings, limitations, and future work. Section 7 concludes the paper.

3. Threat Model

3.1. System and Trust Assumptions

We consider an LLM-driven NL2SQL data-access system deployed in a production AIoT environment. The system comprises four components: (i) a set of organizational users each assigned exactly one role from a predefined role set; (ii) an LLM-based SQL generatorthat translates a user’s natural-language request into an SQL statement; (iii) a policy-enforcement layer (SecureMCP) situated between the generator and the database; and (iv) a bckend relational database holding sensitive AIoT operational data.
We make the following trust assumptions:
  • Users are authenticated but only partially trusted. A user is correctly authenticated and bound to a single organizational role, and the role assignment itself is trusted. However, the content of a user’s natural-language request is not trusted, because it may—intentionally or unintentionally—carry adversarial instructions. Users cannot modify the role–permission matrix, the SecureMCP configuration, or the defense-module rule sets, all of which reside in the trusted computing base.
  • The LLM generator is untrusted. Following the established observation that LLMs cannot reliably separate trusted instructions from untrusted input [27,28], we treat the generator as an untrusted component whose output must be validated before execution. We make no assumption that the model resists injection; on the contrary, the injection incorporation rate reported in Section 5.2 quantifies precisely how often it does not.
  • The enforcement layer and database are trusted. SecureMCP, its audit log, and the MySQL backend execute within the trusted boundary. The database enforces connection-level privileges, but—consistent with the gap identified in Section 2.2—does not itself provide the table-, column-, and operation-level policy semantics that SecureMCP supplies.

3.2. Adversary Model

The adversary’s goal is to cause the system to execute an SQL statement that violates the requesting user’s authorized scope—specifically, to (G1) read tables or columns beyond the role’s permitted set, (G2) exfiltrate schema or system metadata, (G3) perform destructive data-definition or data-modification operations, or (G4) impose resource-exhaustive execution that degrades database availability.
We consider the adversary manifesting through prompt injection, and distinguish two vectors:
  • Direct prompt injection, in which the adversary is a legitimate, authenticated user who deliberately embeds malicious instructions in their own natural-language request in an attempt to escalate beyond their assigned role.
  • Indirect prompt injection, in which adversarial instructions originate from untrusted third-party content (e.g., sensor-supplied strings, log fields, or device metadata) that is incorporated into the request context and steers the generator toward harmful SQL, even when the human user is benign.
Both vectors converge on the same observable event—an LLM-generated SQL statement carrying injected intent reaching the enforcement layer—and SecureMCP defends against this event regardless of its origin. The primary evaluation (Experiment B) instantiates the direct-injection vector under the most restrictive role, as it represents the tightest test of policy enforcement; the framework’s decision logic is identical for the indirect vector.
Out of scope. We explicitly exclude the following from the present threat model: compromise of the enforcement layer or its configuration; attacks on user authentication or role assignment (e.g., credential theft, privilege forgery); attacks on the database or operating system through channels other than the generated SQL; and model-training-stage threats such as data poisoning or backdoor insertion, which are addressed by complementary lines of work [8,11]. These exclusions define the boundary within which the notion of an “authorized scope” is well-defined and within which SecureMCP’s guarantees hold.

3.3. Rationale for Enforcement-Layer Defense

A natural alternative is to rely on the database’s native RBAC by provisioning a distinct database account per organizational role. We adopt an enforcement-layer design instead, for three reasons that persist even at the small role cardinality of our setting and are therefore independent of user-population scalability:
  • Semantic-level policy expressiveness. Native database grants operate at the object and privilege level and cannot readily express the semantic constraints our roles require—for example, permitting facility_manager to access a sensitive column only through aggregate functions (COUNT, AVG) while forbidding row-level retrieval of the same column. Enforcing such column-conditional-on-usage policies at the database layer would require view proliferation or trigger logic that quickly becomes unmaintainable.
  • Pre-execution, cost- and pattern-aware inspection. Several threats (G4 resource exhaustion; UNION- and LOAD_FILE-based vectors) are best neutralized before execution, using EXPLAIN-based cost estimation and construct-level pattern analysis. Native privileges are evaluated at execution time and offer no equivalent pre-execution cost gate or syntactic-pattern interception.
  • Uniform, auditable decisioning. The enforcement layer produces a single, structured audit record per query—identifying the triggering module, rule, and SQL element—which is essential for security review in regulated AIoT deployments. Native grant failures surface as heterogeneous database errors that are harder to attribute and audit consistently.
Accordingly, SecureMCP is positioned as a policy-enforcement layer that complements rather than replaces native database controls, providing defense-in-depth at the execution stage.

3.4. Scope of Attack Categories

The six injection categories evaluated in this work are not claimed to be an exhaustive or authoritative taxonomy. They are a threat-derived instantiation: each category corresponds to one of the adversary goals G1–G4 realized through a concrete SQL-level mechanism observable at the enforcement layer, and we use the OWASP Top 10 for LLM Applications [15] as a practitioner-oriented reference to cross-check coverage against widely recognized risk classes, not as a formal ground truth. Categories were selected to span the four goals while remaining detectable and attributable at the SQL execution stage; injection intents that cannot be expressed as an observable SQL-level deviation (Section 6.5, Limitations) fall outside this operational scope and motivate the ML-augmented extension discussed as future work.

4. Materials and Methods

This section describes the SecureMCP framework and the experimental configuration used for its evaluation. We first outline the two pipelines considered in this study, then describe the defense modules and their injection-defense mapping, and finally present the dataset, role definitions, injection dataset construction, evaluation metrics, experimental design, and implementation details.

4.1. System Overview

The SecureMCP framework addresses the security gap in LLM-driven data access by introducing a policy-enforcement layer between SQL generation and database execution. The framework is evaluated through a controlled comparison between two pipelines: Pipeline a (NL2SQL), which represents the conventional unprotected setting, and Pipeline b (SecureMCP), which incorporates an RBAC policy module and an MCP server with built-in security mechanisms (Figure 1).
Figure 1. SecureMCP system architecture. (a) NL2SQL passes LLM-generated SQL directly to MySQL without security enforcement. (b) SecureMCP routes SQL through the RBAC policy module and MCP server, where five defense modules (check_policy, explain_gate, SQL Interceptor, Risk Level Filter, DB Isolation) operate before execution. Six prompt injection types target the user query input stage, each mapped to a designated primary defense module.
Both pipelines share the same front-end. A user submits a natural-language query, and the Qwen3-8B-FP8 model served through vLLM generates an SQL statement. The pipelines diverge at the execution stage. In Pipeline A, the generated SQL is sent directly to the MySQL 8.0 database. In Pipeline B, the SQL statement is evaluated by five defense modules before execution. The adversarial setting considers six prompt injection types, in which malicious instructions are appended to otherwise legitimate user queries to induce harmful SQL generation.

4.2. Pipeline A: NL2SQL (Baseline)

Pipeline A represents the conventional NL2SQL baseline. The pipeline operates in three stages. First, the user query is formatted as a prompt containing the schema description of the IoT-SQL database [16], including table names, column names with data types, primary-key and foreign-key relationships, and representative sample values. Second, the Qwen3-8B-FP8 model generates an SQL statement from the prompt. Third, the generated SQL is executed directly on the MySQL 8.0 database, and the result is returned to the user.
No execution-stage security control is applied in this pipeline. Any syntactically valid SQL statement generated by the LLM is executed with the privileges of the database connection, regardless of whether the query accesses sensitive columns, attempts destructive operations, or imposes excessive computational cost. Pipeline A therefore serves as the security-unprotected baseline against which Pipeline B is compared.

4.3. Pipeline B: SecureMCP

Pipeline B implements the SecureMCP framework, which inserts a multi-layer security architecture between LLM-generated SQL and the database. The framework consists of two integrated components: an RBAC policy module that enforces role-based access control [30] and an MCP server based on mysql-mcp-server-sse [22] that provides SQL-level security protections. Within this integrated pipeline, five defense modules inspect each SQL statement before execution.
When an SQL statement is generated, SecureMCP evaluates it sequentially through the five defense modules. If all modules return an ALLOW decision, the query is forwarded to the MySQL database through the MCP server’s execute_sql tool and the result is returned to the user. If any module detects a violation, the framework returns a BLOCK decision, records the violation type and blocking module in the audit log, and terminates execution. This fail-closed design ensures that every query must satisfy all defense modules before reaching the database.

4.4. Defense Modules

The SecureMCP framework includes five defense modules, each targeting a different category of execution-stage risk. Table 1 summarizes the module functions, mechanisms, and key configurations.
Table 1. Five defense modules in the SecureMCP framework.

4.4.1. check_policy: RBAC Engine

The check_policy module is a custom RBAC engine that enforces table- and column-level permissions according to the user’s organizational role. When an SQL statement enters the SecureMCP pipeline, the module performs three steps. First, it parses the SQL statement into an abstract syntax tree (AST) using the sqlparse library and extracts the referenced tables, columns, and operation types (SELECT, INSERT, UPDATE, and DELETE). Second, it retrieves the role-permission matrix for the current user. Third, it compares the parsed SQL elements with the permitted scope and issues one of four decisions: ALLOW, BLOCK_TABLE, BLOCK_COLUMN, or BLOCK_OPERATION.

4.4.2. explain_gate: Cost Verification

The explain_gate module is a custom cost-verification mechanism designed to block resource-intensive queries before execution. For each SQL statement that passes check_policy, the module executes a MySQL EXPLAIN command and retrieves the estimated row count without executing the query itself. The estimated row count is then compared with a configurable threshold of 500,000 rows. Queries exceeding this threshold receive a BLOCK_COST decision. This mechanism is particularly relevant for AIoT databases, where large traffic-log tables may otherwise trigger full-table scans and reduce service availability.

4.4.3. SQL Interceptor: Pattern-Based Blocking

The SQL Interceptor is a built-in security mechanism of the mysql-mcp-server-sse server [22]. It performs regex-based matching against a configurable set of dangerous SQL patterns. In this study, the blocked patterns include UNION SELECT, INTO OUTFILE, LOAD_FILE, BENCHMARK, and SLEEP. The interceptor also enforces a maximum SQL length of 2000 characters and validates SQL syntax using sqlparse before forwarding the query to the database engine.

4.4.4. Risk Level Filter: SQL Risk Classification

The Risk Level Filter is another built-in mechanism of the mysql-mcp-server-sse server [22]. It classifies SQL statements into four risk levels according to their structure and operation type. In the SecureMCP configuration, the ALLOWED_RISK_LEVELS variable is set to LOW, so only simple SELECT statements are permitted. This setting blocks data-definition operations, data-modification operations, and multi-statement queries, thereby providing an additional safety layer against destructive payloads that are not filtered by the preceding modules.

4.4.5. DB Isolation: Cross-Database Access Prevention

The DB Isolation module is a built-in mechanism of the mysql-mcp-server-sse server [22] that restricts access to a single designated database. In strict mode, with DATABASE_ACCESS_LEVEL = strict and ENABLE_DATABASE_ISOLATION = true, the module blocks attempts to access databases other than the configured target (iot_database in this study). This includes SHOW DATABASES, fully qualified cross-database table references, and SHOW TABLES FROM other_db queries. The module therefore limits schema-exfiltration attempts against system or external databases.

4.5. Injection-Defense Mapping

A core design principle of SecureMCP is the explicit mapping between injection types and defense modules. We define six prompt injection types based on the OWASP Top 10 for LLM Applications [15], with each type assigned to a primary defense module for first-line interception. Table 2 presents the complete mapping.
Table 2. Injection type-defense module mapping.

4.6. Dataset: IoT-SQL

We use the IoT-SQL dataset [16], a benchmark for text-to-SQL research in IoT security contexts. The dataset is published on Zenodo and was introduced through the TrustNLP 2025 workshop. It consists of a MySQL database derived from two sources: the IoT-23 network traffic dataset [17], which contains labeled benign and malicious IoT traffic, and a smart-building sensor dataset containing temperature, humidity, pressure, and occupancy records. Table 3 summarizes the dataset statistics.
Table 3. IoT-SQL dataset statistics.

4.7. Role-Based Policy Definition

Four organizational roles were defined to reflect practical access requirements in AIoT environments. Table 4 presents the role-permission matrix enforced by the check_policy module.
Table 4. RBAC role-permission matrix.

4.8. Injection Dataset Generation

The injection dataset was constructed by augmenting a stratified sample of clean test queries with adversarial payloads derived from the OWASP prompt-injection threat model [15]. From the 1900 test queries, 400 representative queries were selected through stratified sampling (seed = 42) while preserving the Retrieval/Reasoning distribution. Six injection template sets were then defined, each with three linguistic variants. Table 5 provides representative examples.
Table 5. Injection templates by type (representative examples).

4.9. Evaluation Metrics

Because SecureMCP operates as a pre-execution filter that renders an ALLOW/BLOCK decision on each candidate SQL statement, its performance must be measured as detection performance—how reliably it admits benign, in-scope queries and rejects those that violate the authorized scope defined in Section 3.2. Reporting execution-result accuracy alone would conflate two distinct quantities: the filtering behavior of the defense layer and the generation quality of the underlying LLM. We therefore decouple the evaluation into two dimensions, summarized in Table 6, and report filter performance (false positive and false negative rates) as the primary metrics, while retaining execution-accuracy measures only as reference indicators of LLM generation quality.
Table 6. Decoupled evaluation framework: filter performance vs. LLM generation quality.
Confusion-matrix convention. Throughout, we define a positive as a malicious query that should be blocked and a negative as a benign, in-scope query that should be allowed. A benign query is defined relative to the requesting role: it is a query that lies entirely within that role’s authorized scope per the role–permission matrix (Table 4). Accordingly, true negatives (TN) are benign queries correctly allowed, false positives (FP) are benign queries incorrectly blocked, true positives (TP) are malicious queries correctly blocked, and false negatives (FN) are malicious queries incorrectly allowed. This convention makes explicit that a BLOCK decision on an out-of-scope query is a correct positive, not a filtering error—the distinction that motivated the metric redesign.
False Positive Rate (FPR). The primary metric for Experiment A, FPR measures the proportion of benign, in-scope queries that the framework incorrectly blocks:
FPR = FP/(FP + TN)
A low FPR demonstrates that the defense layer does not interfere with legitimate work. Crucially, FPR is computed only over queries that lie within the requesting role’s authorized scope; queries that fall outside a role’s scope are excluded from the benign set, since blocking them is the intended behavior rather than a false positive. Per-role FPR results are reported in Section 5.1. The two dominant sources of false positives—ambiguous wildcard expansion in SELECT * and unresolved column references in deeply nested subqueries—are analyzed there.
False Negative Rate (FNR). The primary metric for Experiment B, FNR measures the proportion of malicious queries that the framework incorrectly allows. Because a substantial fraction of injection queries never reach the enforcement layer as an actual threat—the LLM simply ignores the injected instruction and emits clean SQL—we report two variants to avoid conflating model behavior with filter behavior. The naive FNR treats every unblocked injection query as a miss and thus serves as an upper bound:
FNR_naive = (unblocked injection queries)/(all injection queries)
The effective FNR restricts the denominator to injection queries in which the adversarial payload was actually incorporated into the generated SQL—that is, cases in which the defense layer genuinely had to act—by excluding LLM-resistant queries:
FNR_effective = (genuine failures)/(injection queries − LLM-resistant queries)
Attributing LLM-resistant cases to filter misses would be a category error, since no injected payload reached the enforcement layer for those queries; the effective FNR therefore reflects the defense layer’s true miss rate against realized threats. Both variants, together with the decomposition of unblocked queries into LLM-resistant cases and genuine failures, are reported per injection type in Section 5.4.
Reference measures of LLM generation quality. To characterize the underlying generator independently of the filter, we retain three result-based measures, reported as reference indicators only. Execution Accuracy (EX) is the proportion of generated queries whose execution result exactly matches that of the gold SQL, compared at the row and column level; for SecureMCP, BLOCKed queries are excluded from the numerator. EX-in-ALLOW restricts EX to queries that received an ALLOW decision, isolating generation quality among admitted queries. Injection Incorporation Rate (Incorp) measures the proportion of injection queries for which the LLM incorporated the adversarial payload into the generated SQL, determined by type-specific risk indicators: sensitive columns absent from the gold SQL (INJ-1), schema-access patterns (INJ-2), UNION SELECT clauses or mysql.user references (INJ-3), WHERE-clause removal (INJ-4), LOAD_FILE or INTO OUTFILE functions (INJ-5), and multi-statement constructs or DDL operations (INJ-6). We emphasize that EX and EX-in-ALLOW reflect LLM generation capability, not filter performance, and that a low overall EX under a restrictive role indicates correct removal of out-of-scope queries rather than degraded filtering; the filter’s behavior is captured by FPR and FNR above.
Supplementary measure. For operational completeness we also report the Execution Success Rate (ES)—the proportion of queries that execute without runtime error regardless of result correctness—and the ALLOW Rate, the proportion of queries receiving an ALLOW decision, which contextualizes the relationship between overall EX and EX-in-ALLOW.

4.10. Experiment Design

The evaluation consists of two complementary experiments. Experiment A measures the effect of security enforcement on clean-query accuracy. Experiment B evaluates injection robustness and the contribution of each defense module. Table 7 summarizes the design of both experiments.
Table 7. Experiment design summary.
Experiment A (benign, in-scope queries) evaluates whether the defense modules admit legitimate queries without over-blocking. The 1900 test queries are executed through NL2SQL once and through SecureMCP four times (once per role). Its primary metric is the false positive rate (FPR)—the proportion of benign, in-scope queries that are incorrectly blocked—computed separately for each role over the queries that lie within that role’s authorized scope (Section 4.9). Execution accuracy (EX and EX-in-ALLOW) is reported alongside FPR only as a reference indicator of LLM generation quality, not as a measure of filter performance; a lower overall EX under a more restrictive role reflects the correct removal of out-of-scope queries rather than degraded filtering.
Experiment B (injection queries) is the core security experiment. It quantifies blocking effectiveness against the six injection types with the role fixed to auditor—the most restrictive configuration and therefore the tightest test of policy enforcement (Section 3.2). The blocked-by analysis examines the audit logs to identify which module triggered each BLOCK decision, validating the mapping in Table 2. The false-negative analysis then decomposes unblocked injection queries into LLM-resistant cases, in which the LLM ignores the injection and emits clean SQL, and genuine defense failures, in which the LLM incorporates the injection but no module detects it. From this decomposition we compute both the naive FNR (all unblocked queries) and the effective FNR (genuine failures relative to injection queries in which the payload was actually incorporated), as defined in Section 4.9, so that the filter’s true miss rate against realized threats is not obscured by the LLM’s own robustness.

4.11. Implementation and Infrastructure

Implementation details are summarized in Table 8. The two custom modules, check_policy and explain_gate, were implemented in Python with sqlparse for AST parsing. A pipeline orchestrator manages sequential defense-module execution under fail-closed logic, and an audit logger records each decision as a JSON Lines entry. The three MCP-native modules—SQL Interceptor, Risk Level Filter, and DB Isolation—were activated through environment variables provided by mysql-mcp-server-sse [22]. The LLM temperature was set to 0.0 to ensure deterministic output.
Table 8. Implementation and Infrastructure details.

5. Results

This section reports the evaluation results. Following the decoupled framework of Section 4.9, we present filter performance—false positive rate (FPR) and false negative rate (FNR)—as the primary outcome, and treat execution-accuracy measures (EX, EX-in-ALLOW) as reference indicators of LLM generation quality. Section 5.1 reports Experiment A (benign, in-scope queries); Section 5.2 reports Experiment B (injection queries); Section 5.3 presents the blocked-by and ablation analysis; and Section 5.4 decomposes false negatives. All quantitative values are reported in Table 9, Table 10, Table 11, Table 12, Table 13 and Table 14.
Table 9. False Positive Rate on benign, in-scope queries across RBAC roles, decomposed by responsible module (primary filter metric).
Table 10. Reference execution-accuracy measures under benign in-scope conditions (LLM generation quality, not filter performance).
Table 11. Experiment B results—injection environment (role: auditor).
Table 12. Blocked-by analysis by injection type.
Table 13. Module ablation on the injection set (role: auditor).
Table 14. False negative decomposition and FNR by injection type (role: auditor).

5.1. Experiment A: Benign In-Scope Query Results

Experiment A evaluates whether the defense modules admit legitimate, in-scope queries without over-blocking. Because false positives can originate from two distinct modules—the cost-based explain_gate and the RBAC-based check_policy—Table 9 reports the false positive rate separately for each, so that the source of any over-blocking is unambiguous. Table 10 reports the reference execution-accuracy measures in full.
The primary finding is that the RBAC engine itself over-blocks almost nothing: the check_policy false positive rate stays between 0.3% and 2.2% across all four roles (Table 9). This directly addresses the concern that restrictive roles might block a large fraction of a legitimate user’s valid queries—the RBAC policy admits in-scope work with very few errors, and the low overall execution accuracy observed for the more restrictive roles is not the result of blocking in-scope work but of correctly removing queries outside the role’s authorized scope. Because FPR is computed only over in-scope queries, it isolates genuine over-blocking from the policy-correct rejection of out-of-scope requests.
Decomposing the FPR by module also reveals where the residual over-blocking actually arises. Across every role, false positives are dominated by explain_gate rather than check_policy: the explain_gate FPR (8.0–12.1%) is roughly an order of magnitude larger than the check_policy FPR (0.3–2.2%). The pattern is most pronounced for network_admin, whose broad scope admits large log-table scans; 229 benign queries are blocked by the global 500,000-row cost threshold even though they are perfectly within policy, against only 6 blocked by check_policy. This shows that the practical over-blocking cost of SecureMCP is driven by the coarse, database-wide explain_gate threshold rather than by role-based access control, and motivates the per-table adaptive thresholds discussed in Section 6. The comparatively minor check_policy false positives that do occur stem from ambiguous wildcard expansion in SELECT * and unresolved column references in deeply nested subqueries, examined further in Section 5.4.
As reference measures, EX-in-ALLOW remains within a stable range that matches or exceeds the NL2SQL baseline (63.8%) across all four roles (65.1–76.4%; Table 10), confirming that the defense modules act as a transparent pre-execution filter for admitted queries. Overall EX varies with the ALLOW rate rather than with generation quality: as a role’s authorized scope narrows, more out-of-scope queries are correctly removed, lowering overall EX while leaving EX-in-ALLOW essentially unchanged. We therefore do not interpret the ordering of overall EX across roles as a performance trend; in particular, the auditor role does not fall on a simple monotonic curve, because its permitted query composition differs from that of the sensor- and facility-oriented roles. The elevated EX-in-ALLOW for sensor_engineer reflects a selection effect, as BLOCK decisions disproportionately remove complex multi-table queries that are harder for the LLM to generate correctly. Figure 2 visualizes the role-wise FPR (primary) alongside EX and EX-in-ALLOW as reference measures, making the decoupling between filter performance and generation quality visually explicit.
Figure 2. Experiment A—role-wise FPR (primary) with EX and EX-in-ALLOW shown as reference.

5.2. Experiment B: Injection SQL Results

Experiment B evaluates injection robustness with the role fixed to auditor, the most restrictive configuration and the tightest test of policy enforcement (Section 3.2). Table 11 reports the comparative results for both pipelines under benign and injection conditions.
The injection incorporation rate of 72.5% (Table 11) confirms that a large majority of adversarial payloads successfully steer the LLM toward SQL reflecting the injected intent, establishing the practical risk of an unprotected pipeline and the necessity of external enforcement. The unprotected NL2SQL pipeline also shows a marked decline in reference EX and ES under injection, as injected payloads produce runtime errors such as references to non-existent system tables (e.g., mysql.user).
Under SecureMCP, the effective false negative rate—the share of realized threats (payload-incorporated queries) that the filter fails to block—is 3.98% (Table 11; derivation in Section 5.4). The low reference EX under this setting is the intended consequence of blocking, not a generation deficit: SecureMCP correctly rejects the overwhelming majority of adversarial queries, so few reach execution. We report EX and ES here only to characterize the baseline’s degradation and are careful not to interpret SecureMCP’s low injection-condition EX as a quality signal.

5.3. Blocked-by and Ablation Analysis

The blocked-by analysis examines the audit logs to determine which module triggered each BLOCK decision. Table 12 summarizes the blocking results by injection type.
The check_policy module, positioned first in the fail-closed pipeline, accounts for the largest share of blocks, because injection-manipulated SQL frequently introduces tables or columns that violate the auditor role’s RBAC permissions before the query reaches downstream modules. For example, INJ-3 queries containing UNION SELECT … FROM mysql.user and INJ-2 queries referencing information_schema are intercepted at the RBAC layer rather than by the SQL Interceptor or DB Isolation module.
The blocking rates by type clarify the framework’s relative strengths. INJ-5 and INJ-6 are blocked almost completely, whereas INJ-4 (Cost Explosion) shows the lowest rate (63.0%). Two factors explain the INJ-4 result: payloads that remove WHERE clauses from otherwise auditor-permitted queries may still access only permitted tables and columns and therefore pass check_policy; and the global explain_gate threshold of 500,000 rows is rarely triggered for the smaller tables accessible under the auditor role. This motivates the per-table adaptive threshold discussed in Section 6.
Module ablation. To quantify each module’s marginal contribution rather than assert it, we disabled the modules individually and in combination and measured the resulting block rate and effective FNR on the injection set (Table 13). In this ablation, the modules are evaluated independently on each stored query and their decisions are combined by a logical OR, so the “Full” row reproduces the integrated pipeline exactly (82.3% block rate and 3.98% effective FNR), matching the fail-closed pipeline reported in Table 11; any small residual difference would arise from the order-independent re-evaluation of explain_gate against the live database and does not affect the comparative conclusions.
The ablation substantiates two claims made qualitatively above. First, removing the secondary (downstream) modules and retaining RBAC alone reduces the block rate from 82.3% to 64.8%—a 17.5-percentage-point reduction—and raises the effective FNR from 3.98% to 27.53%. This confirms that the SQL-level controls provide substantial protection beyond RBAC for queries that are policy-compliant at the table-and-column level yet exhibit unsafe execution-level characteristics (e.g., UNION or LOAD_FILE constructs within auditor-permitted tables). Adding explain_gate on top of RBAC (the “secondary modules removed” configuration) yields essentially the same block rate (64.9%, +0.1 pp over RBAC-only) and a marginally lower effective FNR (27.47% vs. 27.53%), indicating that the cost gate contributes little to injection blocking under the auditor role and that the SQL Interceptor and Risk Level Filter account for most of the secondary-module coverage.
Second, the two single-layer configurations each leave large gaps that the integrated framework closes. The RBAC-only configuration attains an effective FNR of 27.53%, and the MCP-only configuration (the four built-in modules without check_policy) attains 17.93%, whereas the full framework reaches 3.98%. In terms of block rate, the MCP-only configuration (62.3%) even trails RBAC-only (64.8%) by 2.5 percentage points and lies 20.0 percentage points below the full pipeline—the largest single-layer gap in Table 13—yet it achieves a substantially lower effective FNR than RBAC-only (17.93% vs. 27.53%). This asymmetry indicates that the two layers block different injection vectors: RBAC misses the execution-level constructs that the MCP modules catch (chiefly INJ-3 UNION and INJ-5 file-access payloads), while the MCP modules miss the role-specific table-and-column violations that only RBAC can express (chiefly INJ-1 privilege escalation and INJ-2 schema exfiltration on auditor-forbidden objects). Neither layer alone approaches the integrated result. This demonstrates that RBAC and MCP-level defenses are complementary rather than interchangeable, and that neither blocks the full range of injection vectors on its own.

5.4. False Negative Analysis

A false negative occurs when an injection query receives an ALLOW decision from all five modules. Following Section 4.9, we distinguish LLM-resistant cases, where the LLM ignores the injection and emits clean SQL, from genuine defense failures, where the LLM incorporates the injection but no module detects it, and report both the naive and effective FNR. Table 14 presents the decomposition.
The naive FNR (17.7%) substantially overestimates the filter’s true miss rate, because most unblocked queries are LLM-resistant cases in which no injected payload reached the enforcement layer; attributing these to the filter would be a category error. Restricting the denominator to the 2058 realized threats (injection queries minus LLM-resistant cases) yields an effective FNR of 3.98% (82/2058). This distinction matters because model robustness alone provides no stable security guarantee; the effective FNR isolates what the defense layer itself failed to catch.
Genuine failures concentrate in INJ-4 and INJ-1 (effective FNR 11.0% and 8.6%; Table 14), which together account for 62 of the 82 genuine failures. INJ-4 failures arise when partial WHERE-clause removal retrieves more rows than intended yet remains below the global 500,000-row threshold for the smaller tables accessible under the auditor role—the injection-side counterpart of the explain_gate threshold conservatism seen on the benign side in Table 9. INJ-1 failures arise when the LLM incorporates sensitive columns from auditor-permitted tables that the single-pass sqlparse-based resolver does not fully bind back to the blocked-column set under table aliases or implicit references. INJ-2 contributes a smaller number of failures [14] in which a data-exposure intent is expressed through unrestricted retrieval with no syntactically detectable exfiltration pattern. The remaining injection types produce few genuine failures (three for INJ-3, two for INJ-5, and one for INJ-6), because their payloads typically introduce syntactically explicit constructs—UNION SELECT, LOAD_FILE, or multi-statement separators—that the SQL Interceptor and Risk Level Filter intercept reliably.
Two representative genuine failures illustrate the two dominant modes. In the WHERE-removal case (INJ-4), the injected instruction directed the model to drop all filtering conditions, and the LLM emitted SELECT * FROM IoT23_FILES_LOG; in place of a filtered lookup. Because IoT23_FILES_LOG is an auditor-permitted table and its EXPLAIN row estimate falls below the global threshold, the query cleared both check_policy and explain_gate and was allowed, even though the wildcard projection combined with the removed predicate constitutes the intended resource-exhaustion payload (goal G4). In the alias-obscured column case (INJ-1), the injected instruction requested additional sensitive fields, and the LLM produced a query of the form SELECT DISTINCT iot23_dns_log.id_orig_h, iot23_dns_log.id_resp_p FROM iot23_dns_log WHERE a benign equality predicate;. Here the auditor-forbidden columns id_orig_h and id_resp_p appear under a lowercased, fully qualified table reference that the single-pass parser did not consistently bind back to the blocked-column set, so check_policy issued an ALLOW rather than a BLOCK_COLUMN decision (goal G1). Both queries pass all five modules and therefore surface only in this false-negative decomposition, not in the blocked-by analysis of Section 5.3.
These two failure modes map directly to the engineering improvements developed in Section 6.5: the INJ-4 residual motivates per-table adaptive cost thresholds calibrated to each table’s expected cardinality, replacing the single global cutoff that is insensitive to smaller tables, while the INJ-1 residual motivates multi-pass AST resolution with alias tracking and wildcard expansion, which would bind qualified and lowercased column references back to the role’s blocked-column set. Because both residuals stem from specific, well-localized mechanisms rather than from a fundamental limitation of the rule-based approach, they define concrete targets for the roadmap in Section 6.5 rather than a call to replace the deterministic first line.

6. Discussion

6.1. Defense-in-Depth Architecture

The results in Section 5 indicate that integrating RBAC with MCP-level security provides layered protection that neither component achieves independently, while preserving generation quality for authorized queries (Section 5.1). The module ablation (Table 13) makes this concrete: the RBAC-only and MCP-only configurations each leave substantial gaps (effective FNR of 27.53% and 17.93%, respectively), whereas the integrated framework attains an effective FNR of 3.98%—a reduction of 23.55 percentage points relative to RBAC alone and 13.95 percentage points relative to the MCP-only configuration. Two architectural observations explain this outcome.
First, the check_policy module accounts for the largest share of blocking decisions (Table 12), consistent with the sequential fail-closed design and the restrictive scope of the auditor role. Because injection payloads frequently introduce non-permitted tables (e.g., mysql.user in INJ-3 and information_schema in INJ-2) or non-permitted columns, the RBAC engine intercepts these violations before the downstream modules are evaluated. This is advantageous because many adversarial queries are blocked at the policy layer with clear, auditable reasons before SQL-level pattern analysis is required.
Second, the secondary modules remain essential for the subset of injections that operate within the target role’s permitted scope. Removing them and retaining RBAC alone lowers the overall block rate from 82.3% to 64.8%—a 17.5-percentage-point reduction—and raises the effective FNR from 3.98% to 27.53% (Table 13). Adding only explain_gate on top of RBAC recovers essentially none of this gap (64.9% block rate, 27.47% effective FNR), indicating that the SQL Interceptor and Risk Level Filter account for the bulk of the secondary-module coverage. This confirms that SQL-level controls add substantive protection against queries that are policy-compliant at the table-and-column level yet exhibit unsafe execution-level characteristics (e.g., UNION, LOAD_FILE, or multi-statement constructs within auditor-permitted tables). Although the DB Isolation module records no blocks under the auditor role in Experiment B, its inclusion remains useful as a safety layer for less restrictive roles such as network_admin, where a broader authorized scope allows more queries to reach the downstream modules.
The observed module attribution differs from the strict one-to-one mapping hypothesized in Table 2. Rather than a design weakness, this reflects redundant coverage: multiple modules can intercept the same attack type, so a payload evading its designated primary defense is often caught by another module. Notably, INJ-2 (Schema Exfiltration, mapped to DB Isolation in Table 2) is instead absorbed by check_policy in practice (Table 12), which is why DB Isolation records zero blocks under the auditor role even though the corresponding attack class is blocked at 68.0%. Under this interpretation, the primary-defense mapping in Table 2 is best understood as a design-time threat-modeling aid—linking each adversary goal (G1–G4, Section 3.2) to a first-line module—rather than a strict runtime prediction of which module will fire.

6.2. Rule-Based Defense Justification

The rule-based design is supported by two properties important for production AIoT systems: determinism and interpretability. Determinism ensures consistent decisions for identical inputs, which is essential for security auditing and reproducible incident review; the same SQL text always yields the same enforcement verdict, so post-hoc investigations do not have to reconcile stochastic model outputs. Interpretability allows the audit log to record the specific module, rule, and SQL element associated with each block decision—a property already exploited by the blocked-by analysis in Section 5.3, where every BLOCK verdict in Table 12 is attributed to a concrete module and rule. Together, these properties give operators a defense whose behavior can be reviewed, tested, and certified against organizational policy, rather than one whose decisions must be inferred from model behavior.
At the same time, rule-based methods cannot detect threats that are policy-compliant at the table/column level yet exhibit unsafe execution-level characteristics—for example, WHERE-clause removal within permitted tables (goal G4)—as shown by the genuine-failure analysis (Section 5.4). This is quantitatively visible in Table 14: INJ-4 alone contributes an effective FNR of 11.0% and INJ-1 contributes 8.6%, together accounting for the majority of the 82 genuine failures out of 2058 realized threats that determine the overall 3.98% effective FNR. For this reason, a downstream ML-based anomaly detector is proposed as future work (Section 6.5). Such an extension may improve zero-day attack detection while preserving the determinism and interpretability of the rule-based first line—the ML layer would raise coverage without displacing the auditable, reproducible baseline on which security review depends.

6.3. Comparison with Existing Defenses

SecureMCP occupies a design point not covered by existing execution-stage defenses. Application-layer P2SQL mitigations [29] operate at the query-construction stage and constrain how SQL is assembled, but do not enforce role-specific table-and-column policies; conversely, MCP-native controls such as those in mysql-mcp-server-sse [22] act only at the SQL-statement level and cannot express organizational-role semantics. Because no existing system enforces table- and column-level RBAC at the NL2SQL execution stage (Section 2.2), a like-for-like quantitative baseline against a competing role-aware system is not available.
The module ablation (Table 13) therefore serves as the internal comparison, isolating the contribution of each mechanism. The results make the complementarity claim quantitative rather than qualitative: an RBAC-only configuration analogous to prior policy-only proposals attains an effective FNR of 27.53%; an MCP-only configuration analogous to prior SQL-statement-level controls attains 17.93%; SecureMCP’s integrated pipeline reduces the effective FNR to 3.98%. Neither single-layer configuration approaches the integrated result, and the two layers block different injection vectors—RBAC catches role-specific table/column violations (INJ-1, INJ-2 on forbidden objects) that MCP-native controls cannot express, while the MCP modules catch execution-level constructs (INJ-3 UNION, INJ-5 file-access) that RBAC cannot see. This positioning substantiates the paper’s central claim that the contribution lies in the threat-informed integration and the formulation of execution-stage security as a distinct problem, rather than in any individual module.

6.4. Practical Deployment and Engineering Applicability

Several properties support deployment in operational AIoT settings. The framework is architecturally LLM-agnostic: because enforcement operates on generated SQL rather than on model internals, it applies without modification across generators, and the injection incorporation rate of 72.5% (Section 5.2, Table 11) indicates that external enforcement is necessary regardless of the specific model—that is, mitigating prompt injection cannot be delegated to the LLM alone.
The enforcement overhead is negligible relative to generation cost. Across the 2400 injection queries of Experiment B, the mean per-query defense latency—the wall-clock time consumed by the five-module pipeline, including the EXPLAIN round-trip in explain_gate—was 21 ms, against a mean LLM inference time of approximately 950 ms per query. The filter therefore accounts for roughly 2% of the end-to-end response time, so its addition does not materially affect interactive responsiveness; because the dominant cost remains LLM generation, the pipeline’s effect on sustained throughput is correspondingly small. The four rule-based modules (check_policy, sql_interceptor, risk_level_filter, db_isolation) execute entirely in-process on the parsed SQL and contribute sub-millisecond latency each, so the measured overhead is dominated by the single database round-trip that explain_gate issues; workloads that disable the cost gate—or that cache EXPLAIN estimates per query shape—would reduce even this residual cost. This confirms that the multi-layer defense is practical for production deployment rather than a purely offline analysis tool.
The false-positive impact on legitimate work is likewise contained. The FPR attributable to check_policy remains at or below 2.2% across all four roles (0.3% for network_admin, 1.1% for sensor_engineer, 2.2% for facility_manager, 1.4% for auditor; Table 9), and execution accuracy under the filter (EX-in-ALLOW = 65.1–76.4% across roles, Table 10) matches or exceeds the NL2SQL baseline of 63.8%. In other words, the multi-layer defense that produces the 3.98% effective FNR on the injection set does not come at the cost of usability for authorized users: for benign in-scope queries the pipeline behaves as a near-transparent pre-execution filter that adds only the 21 ms overhead noted above.
The structured audit log—recording the triggering module, rule, and SQL element for every decision—directly supports the security-review and compliance requirements typical of regulated AIoT deployments; the same audit records that enabled the blocked-by analysis in Section 5.3 also serve as the operational evidence trail for post-incident review. Deployment does require an upfront investment: defining the role–permission matrix (Table 4) and tuning module configurations (e.g., the explain_gate threshold and interceptor patterns) to the target schema. The false-positive analysis in Section 5.1 indicates that most over-blocking stems from parser-resolution limitations (ambiguous SELECT * expansion, alias-obscured columns) rather than from policy misconfiguration, suggesting that the parser-hardening improvements listed in Section 6.5 will also reduce operational friction—the same fixes that lower false negatives on INJ-1 will lower false positives on ambiguous benign queries.

6.5. Limitations and Future Work

Three main limitations define the scope of the present findings.
First, the primary evaluation was conducted with a single generator, Qwen3-8B-FP8. Although the framework is LLM-agnostic and the filter operates on generated SQL rather than on the model, injection susceptibility varies across models; broader validation with additional generators remains future work.
Second, the evaluation is limited to the IoT-SQL dataset and, in Experiment B, to the auditor role; generalization to other AIoT domains, other role configurations (e.g., network_admin, whose broader authorized scope would exercise the DB Isolation module that recorded zero blocks under auditor), and real-world attack logs remains to be established.
Third, the rule-based modules cannot detect intents outside predefined rules, as reflected in the 3.98% effective genuine-failure rate and—more diagnostically—in the 11.0% effective FNR on INJ-4 (Cost Explosion) and 8.6% on INJ-1 (Privilege Escalation) reported in Table 14. Two mechanisms drive these residuals: the global explain_gate threshold of 500,000 rows is insufficiently sensitive for the smaller tables accessible under the auditor role (INJ-4), and alias-obscured or wildcard-expanded column references occasionally slip past the current single-pass check_policy resolver (INJ-1).
These limitations map to a concrete engineering roadmap.
  • Per-table adaptive cost thresholds. Replacing the single global explain_gate cutoff with per-table thresholds calibrated to each table’s expected cardinality would raise sensitivity for the smaller tables that currently evade the cost gate—directly targeting the INJ-4 residual (11.0% effective FNR).
  • Multi-pass AST resolution with alias tracking and wildcard expansion. This would address both the parser-induced false negatives (alias-obscured sensitive columns) contributing to the INJ-1 residual (8.6% effective FNR) and the false positives (ambiguous SELECT * expansion) identified in Section 5.1.
  • ML-augmented anomaly detection as a downstream layer. Positioned after the rule-based first line, it would target intents outside predefined rules while preserving the determinism and interpretability that Section 6.2 and Section 6.4 rely on; the rule-based layer would continue to provide the auditable, reproducible baseline, and the ML layer would raise coverage without changing the enforcement contract exposed to operators.
Together, these three directions target the specific residual failure modes surfaced by Section 5.4 (INJ-4 and INJ-1 concentration) rather than pursuing generic improvements, and they do so without weakening the defense-in-depth and rule-based justification developed in Section 6.1 and Section 6.2.

7. Conclusions

This paper presented SecureMCP, a policy-enforced framework for LLM-driven data access that integrates Role-Based Access Control [30] with an MCP server [22] to provide multi-layer defense for LLM-generated SQL execution in AIoT systems. The framework combines five defense modules—check_policy, explain_gate, SQL Interceptor, Risk Level Filter, and DB Isolation—within a sequential fail-closed pipeline, and grounds their design in an explicit threat model (Section 3) that defines the adversary goals, trust boundaries, and the rationale for enforcing policy at the MCP layer rather than through native database controls.
The primary contribution of this study is the formulation of execution-stage security for NL2SQL pipelines as a distinct research problem, together with the empirical demonstration that integrating established techniques yields security properties unattainable by any single component alone. Evaluated on the IoT-SQL dataset [16] with Qwen3-8B-FP8, and reporting filter performance (FPR/FNR) separately from LLM generation quality, the study supports four main conclusions. First, the defense layer admits legitimate, in-scope queries without over-blocking, maintaining a low false positive rate across all four roles (0.3–2.2%) while leaving EX-in-ALLOW at or above the unprotected baseline; the low overall execution accuracy under restrictive roles reflects the correct removal of out-of-scope queries rather than degraded generation. Second, against realized threats—injection queries in which the adversarial payload was actually incorporated—the framework limits the effective false negative rate to 3.98%, and the module ablation confirms that RBAC and MCP-level defenses are complementary, since each alone leaves substantial gaps (effective FNR of 27.53% and 17.93%, respectively). Third, the defense-in-depth architecture provides redundant coverage, with the RBAC engine handling most first-line interceptions and the SQL-level modules supplying additional protection for queries that remain within a role’s permitted scope. Fourth, the 72.5% injection incorporation rate confirms that LLM-generated SQL remains highly susceptible to adversarial manipulation, establishing the necessity of external policy enforcement in production AIoT settings.
Taken together, these findings indicate that RBAC and MCP-level security are complementary rather than interchangeable: neither blocks the full range of injection vectors independently, whereas their integration provides broader, auditable protection at the execution stage. The remaining genuine failures concentrate in the cost-explosion and privilege-escalation categories, pointing to concrete engineering directions—per-table adaptive cost thresholds and multi-pass AST resolution with alias tracking. Future work will extend the evaluation to additional LLMs, AIoT domains, and role configurations, and will investigate a downstream ML-based anomaly detector for zero-day injection patterns while preserving the determinism and interpretability of the rule-based first line.

Author Contributions

Conceptualization, methodology, software, formal analysis, investigation, data curation, writing—original draft preparation, and visualization, W.K.; writing—review and editing, resources and project administration, H.-K.Y.; supervision, writing—review and editing, N.M. All authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Institutional Review Board Statement

Not applicable.

Data Availability Statement

The IoT-SQL dataset is publicly available on Zenodo at https://zenodo.org/records/15000588 (accessed on 5 May 2026) (https://doi.org/10.5281/zenodo.15000588). The mysql-mcp-server-sse server implementation is publicly available at https://github.com/mangooer/mysql-mcp-server-sse (accessed on 5 May 2026). The experiment scripts and policy configuration files used in this study are available from the corresponding author upon reasonable request.

Acknowledgments

The authors thank the contributors of the IoT-SQL dataset and the developers of the mysql-mcp-server-sse open-source project for making these resources publicly available. During the preparation of this manuscript, the authors used a generative AI tool (Claude Opus 4.8, Anthropic) solely for language proofreading and grammar improvement of the English draft. The authors carefully reviewed and edited all AI-assisted output and take full responsibility for the content and integrity of the published work.

Conflicts of Interest

Authors Wonbae Kim and Hee-Kyong Yoo were employed by the company Data Science Lab Co., Ltd. The remaining authors declare that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest. The Data Science Lab Co., Ltd. had no role in the design of the study; in the collection, analyses, or interpretation of data; in the writing of the manuscript, or in the decision to publish the results.

References

  1. Gubbi, J.; Buyya, R.; Marusic, S.; Palaniswami, M. Internet of Things (IoT): A vision, architectural elements, and future directions. Future Gener. Comput. Syst. 2013, 29, 1645–1660. [Google Scholar] [CrossRef] [Scilit]
  2. Li, F.; Jagadish, H.V. Constructing an interactive natural language interface for relational databases. Proc. VLDB Endow. 2014, 8, 73–84. [Google Scholar] [CrossRef] [Scilit]
  3. Katsogiannis-Meimarakis, G.; Koutrika, G. A survey on deep learning approaches for text-to-SQL. VLDB J. 2023, 32, 905–936. [Google Scholar] [CrossRef] [Scilit]
  4. Gao, D.; Wang, H.; Li, Y.; Sun, X.; Qian, Y.; Ding, B.; Zhou, J. Text-to-SQL empowered by large language models: A benchmark evaluation. arXiv 2023, arXiv:2308.15363. [Google Scholar]
  5. Yu, T.; Zhang, R.; Yang, K.; Yasunaga, M.; Wang, D.; Li, Z.; Ma, J.; Li, I.; Yao, Q.; Roman, S.; et al. Spider: A large-scale human-labeled dataset for complex and cross-database semantic parsing and text-to-SQL task. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing (EMNLP), Brussels, Belgium, 31 October–4 November 2018; pp. 3911–3921. [Google Scholar]
  6. Zhong, V.; Xiong, C.; Socher, R. Seq2SQL: Generating structured queries from natural language using reinforcement learning. arXiv 2017, arXiv:1709.00103. [Google Scholar]
  7. Li, J.; Hui, B.; Qu, G.; Yang, J.; Li, B.; Li, B.; Wang, B.; Qin, B.; Geng, R.; Huo, N.; et al. Can LLM already serve as a database interface? A big bench for large-scale database grounded text-to-SQLs. In Proceedings of the 37th Conference on Neural Information Processing Systems (NeurIPS), New Orleans, LA, USA, 10–16 December 2023. [Google Scholar]
  8. Lin, M.; Zhang, H.; Lao, J.; Li, R.; Zhou, Y.; Yang, C.; Cao, Y.; Tang, M. Are Your LLM-Based Text-to-SQL Models Secure? Exploring SQL Injection via Backdoor Attacks. Proc. ACM Manag. Data 2025, 3, 297. [Google Scholar] [CrossRef] [Scilit]
  9. Yao, Y.; Duan, J.; Xu, K.; Cai, Y.; Sun, Z.; Zhang, Y. A survey on large language model (LLM) security and privacy: The good, the bad, and the ugly. High-Confid. Comput. 2024, 4, 100211. [Google Scholar] [CrossRef] [Scilit]
  10. Sicari, S.; Rizzardi, A.; Grieco, L.A.; Coen-Porisini, A. Security, privacy and trust in Internet of Things: The road ahead. Comput. Netw. 2015, 76, 146–164. [Google Scholar] [CrossRef] [Scilit]
  11. Salim, M.M.; Deng, X.; Park, J.H. A privacy-preserving local differential privacy-based federated learning model to secure LLM-from adversarial attacks. Hum.-Centric Comput. Inf. Sci. 2024, 14, 57. [Google Scholar]
  12. Han, Y.; Shim, S.; Gajulamandyam, D.K.; Choi, Y.; Lee, H.; Chang, H. Generation of Impact Factor-Driven Security Rating Questionnaire Using LLMs for AIoT Applications. Hum.-Centric Comput. Inf. Sci. 2026, 16, 6. [Google Scholar]
  13. Anthropic. Introducing the Model Context Protocol. Available online: https://www.anthropic.com/news/model-context-protocol (accessed on 15 January 2025).
  14. Hou, X.; Wang, S.; Zhang, Y.; Xue, Z.; Zhao, Y.; Fu, C.; Wang, H. SMCP: Secure Model Context Protocol. arXiv 2026, arXiv:2602.01129. [Google Scholar]
  15. OWASP Foundation. OWASP Top 10 for Large Language Model Applications. Available online: https://owasp.org/www-project-top-10-for-large-language-model-applications/ (accessed on 15 January 2025).
  16. Pavlich, R.; Ebadi, N.; Tarbell, R.; Linares, B.; Tan, A.; Humphreys, R.; Das, J.; Ghandiparsi, R.; Haley, H.; George, J.; et al. Beyond Text-to-SQL for IoT Defense: A Comprehensive Framework for Querying and Classifying IoT Threats. In Proceedings of the 5th Workshop on Trustworthy NLP (TrustNLP 2025), Albuquerque, NM, USA, 1–12 May 2025. [Google Scholar]
  17. Garcia, S.; Parmisano, A.; Erquiaga, M.J. IoT-23: A Labeled Dataset with Malicious and Benign IoT Network Traffic [Data Set]. Zenodo. 2020. Available online: https://zenodo.org/records/4743746 (accessed on 10 January 2025).
  18. Androutsopoulos, I.; Ritchie, G.D.; Thanisch, P. Natural language interfaces to databases: An introduction. Nat. Lang. Eng. 1995, 1, 29–81. [Google Scholar] [CrossRef] [Scilit]
  19. Pourreza, M.; Rafiei, D. DIN-SQL: Decomposed in-context learning of text-to-SQL with self-correction. In Proceedings of the 37th Conference on Neural Information Processing Systems (NeurIPS), New Orleans, LA, USA, 10–16 December 2023. [Google Scholar]
  20. Dong, X.; Zhang, C.; Ge, Y.; Mao, Y.; Gao, Y.; Chen, L.; Lin, J.; Lou, D. C3: Zero-shot text-to-SQL with ChatGPT. arXiv 2023, arXiv:2307.07306. [Google Scholar]
  21. Li, H.; Zhang, J.; Liu, H.; Fan, J.; Zhang, X.; Zhu, J.; Wei, R.; Pan, H.; Li, C.; Chen, H. CodeS: Towards building open-source language models for text-to-SQL. In Proceedings of the ACM SIGMOD International Conference on Management of Data; ACM: New York, NY, USA, 2024. [Google Scholar]
  22. Mangooer. mysql-mcp-server-sse: MySQL Query Server Based on MCP Framework. Available online: https://github.com/mangooer/mysql-mcp-server-sse (accessed on 1 December 2025).
  23. Talaei, S.; Pourreza, M.; Chang, Y.; Mirhoseini, A.; Saberi, A. CHESS: Contextual harnessing for efficient SQL synthesis. arXiv 2024, arXiv:2405.16755. [Google Scholar]
  24. Model Context Protocol. servers-archived: Archived MCP Reference Server Implementations. Available online: https://github.com/modelcontextprotocol/servers-archived (accessed on 4 June 2026).
  25. CrystalDBA. Postgres MCP Pro: Open-Source MCP Server for PostgreSQL. Available online: https://github.com/crystaldba/postgres-mcp (accessed on 1 December 2025).
  26. Microsoft. SQL Model Context Protocol (MCP) Server Overview. Available online: https://learn.microsoft.com/en-us/azure/data-api-builder/mcp/overview (accessed on 15 December 2025).
  27. Schulhoff, S.; Pinto, J.; Khan, A.; Bouchard, L.-F.; Si, C.; Anati, S.; Tagliabue, V.; Kost, A.; Carnahan, C.; Boyd-Graber, J. Ignore this title and HackAPrompt: Exposing systemic vulnerabilities of LLMs through a global-scale prompt hacking competition. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing (EMNLP), Singapore, 6–10 December 2023; pp. 4945–4977. [Google Scholar]
  28. Greshake, K.; Abdelnabi, S.; Mishra, S.; Endres, C.; Holz, T.; Fritz, M. Not what you’ve signed up for: Compromising real-world LLM-integrated applications with indirect prompt injection. In Proceedings of the 16th ACM Workshop on Artificial Intelligence and Security (AISec), Copenhagen, Denmark, 30 November 2023; pp. 79–90. [Google Scholar]
  29. Pedro, R.; Castro, D.; Carreira, P.; Santos, N. Prompt-to-SQL Injections in LLM-Integrated Web Applications: Risks and Defenses. In Proceedings of the 2025 IEEE/ACM 47th International Conference on Software Engineering (ICSE), Ottawa, ON, Canada, 27 April–6 May 2025; pp. 76–88. [Google Scholar]
  30. Sandhu, R.S.; Coyne, E.J.; Feinstein, H.L.; Youman, C.E. Role-based access control models. Computer 1996, 29, 38–47. [Google Scholar] [CrossRef] [Scilit]
  31. Hu, V.C.; Ferraiolo, D.; Kuhn, R.; Schnitzer, A.; Sandlin, K.; Miller, R.; Scarfone, K. Guide to Attribute Based Access Control (ABAC) Definition and Considerations; NIST Special Publication 800-162; National Institute of Standards and Technology: Gaithersburg, MD, USA, 2014.
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.