Preprint
Article

This version is not peer-reviewed.

Securing Model Context Protocol Servers: Security Assessment and a Lightweight Wrapper-Based Hardening Approach

Submitted:

30 June 2026

Posted:

01 July 2026

You are already at the latest version

Abstract
The Model Context Protocol (MCP) enables LLM agents to interact with external tools, resources, file systems, and platform features. Although this improves interoperability in agent-based systems, improperly configured MCP servers may expose serious security risks, including unauthenticated tool invocation, excessive file access, arbitrary command execution, prompt injection, token replay, response leakage, and denial-of-service behavior. The current work presents a controlled security assessment of an insecure MCP server and evaluates a lightweight FastAPI-based security wrapper that hardens the server without modifying its original implementation. The wrapper mechanism enforces JWT authentication, role-based tool allow listing, input validation, prompt injection filtering, threat scoring, response inspection, rate limiting, and audit logging. The evaluation used 82 controlled scenarios across nine test suites mapped to STRIDE threat categories, including 69 attack cases, 10 rate-limit/DoS cases, 3 false-positive checks, and 3 legitimate-use validation cases. Compared with the insecure baseline, the wrapper reduced vulnerability exposure by 96%, blocked all tested attacks in several categories, and achieved 100% scenario-level mitigation for rate-limit exhaustion. The wrapper mechanism introduced low overhead, with an average latency increase of approximately 3 ms, corresponding to 1.1%, and a memory overhead of 4.3 MB, corresponding to 8.4%. These results show that external wrapper-based hardening can provide practical deployment-level protection for MCP servers, while remaining a complementary defense layer rather than a complete security solution.
Keywords: 
;  ;  ;  ;  ;  ;  ;  ;  

1. Introduction

Large language models (LLMs) are increasingly being integrated into software systems that interact with external tools, application programming interfaces (APIs), files, and system functions. This changes the security profile of LLM based applications. In traditional text generation systems, the model mainly produces textual output, whereas in tool integrated systems, the model may become part of an execution workflow that accesses resources or triggers external actions. The Model Context Protocol (MCP), introduced by Anthropic, provides a standardized way for LLM based hosts and clients to connect with external tools, resources, and prompts [1]. Although MCP improves interoperability and extensibility, it also introduces a security sensitive boundary where exposed tools must be carefully controlled.
Existing LLM security guidance shows that tool integrated systems are exposed to risks such as prompt injection, sensitive data disclosure, insecure tool use, and excessive agency [2]. In MCP based deployments, these risks are combined with conventional software security issues such as weak authentication, missing authorization, insufficient input validation, poor logging, and lack of rate control. When an MCP server exposes tools such as file access, command execution, or API operations without sufficient security controls, an attacker may invoke restricted tools, access sensitive files, manipulate requests, replay tokens, or exhaust server resources. Current MCP focused studies highlight risks such as unsafe tool exposure, weak access control, and excessive permissions. However, less attention has been given to practical deployment level hardening that can be added in front of an existing MCP server without modifying the server implementation or changing the protocol. This gap motivates the wrapper-based approach evaluated in this paper.
This work addresses that practical deployment problem by evaluating whether a lightweight FastAPI-based wrapper placed in front of an MCP server can reduce common security risks while preserving legitimate functionality and maintaining acceptable overhead. The wrapper enforces security checks before requests reach the MCP server, including authentication, authorization, request validation, path and command restrictions, logging, and rate limiting. This work has three main contributions. Firstly, it presents a structured security assessment of an insecure MCP server using controlled test cases mapped to Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, and Elevation of privilege (STRIDE) threat categories. Secondly, it designs and implements a modular security wrapper that can be positioned in front of an MCP server without modifying the original server. Thirdly, it evaluates the wrapper using controlled experimental scenarios, including attack cases, rate-limit and denial-of-service cases, false-positive checks, and legitimate-use validation cases. The results show a 96% reduction in successful security attacks while maintaining expected legitimate functionality and introducing limited overhead. Rather than proposing a new MCP protocol or a complete MCP security framework, this paper provides a practical, deployment-oriented hardening approach for MCP based AI systems. The findings are limited to the controlled experimental environment and should not be interpreted as proof of complete security against all MCP or LLM-agent attacks.
The remainder of this paper is organized as follows. Section 2 presents the related work and background on MCP, tool integrated LLM security, prompt injection, and existing MCP security approaches. Section 3 describes the methodology and system design, including the baseline MCP server, threat model, wrapper architecture, and security controls. Section 4 presents the experimental setup, test scenarios, metrics, and results. Section 5 discusses the interpretation of the results, practical implications, and limitations. Section 6 concludes the paper and outlines future work.

3. Methodology and System Design

This study follows a controlled experimental design to evaluate the effectiveness of a lightweight security wrapper for Model Context Protocol (MCP) servers. Two environments were deployed under identical conditions. Environment A consisted of an insecure MCP server. Environment B used the same MCP server but placed a FastAPI-based security wrapper in front of it. Both environments ran on the same machine and used the same operating system, Python version, dataset directory, and attack scripts. The presence of the wrapper was the only experimental variable. This design allowed the security impact of the wrapper to be evaluated while minimizing the influence of external factors [14]. The experiments used simulated MCP request execution rather than live LLM agent interactions. This approach provided repeatable testing conditions and ensured consistent execution across all scenarios. It also allowed the evaluation to focus on request-level security enforcement without introducing variability from model behaviour. The results therefore reflect the effectiveness of the security controls applied to MCP requests rather than the behaviour of a specific language model.

3.1. Threat Model and STRIDE Mapping

The threat model was organized using the STRIDE framework[15], which classifies threats into spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege Shown in Table 2. Spoofing threats were represented through forged or missing authentication. Tampering threats included malicious input manipulation, command abuse, and prompt injection. Information disclosure focused on unauthorized file access and secret leakage. Denial-of-service threats were represented through request flooding and rate-limit exhaustion. Elevation of privilege involved low-privilege users attempting to invoke high-privilege tools. Repudiation was addressed through audit logging rather than direct attack simulation.

3.2. Baseline MCP Server and Tool Risk Model

The baseline MCP server was implemented using the MCP Python SDK and ran locally on port 8000. The server was intentionally left insecure to provide a clear baseline for comparison. It exposed five tools: read_file, list_directory, write_file, shell_exec, and echo. These tools represent common MCP capabilities and expose realistic attack surfaces related to file access, command execution, file modification, and prompt manipulation. The baseline server did not enforce authentication, role-based access control, path validation, command filtering, rate limiting, response inspection, or audit logging.
Table 3. Baseline MCP tools and associated security risks.
Table 3. Baseline MCP tools and associated security risks.
Tool Function Security Risk
read_file Reads file contents Unauthorized file access and information disclosure
list_directory Returns directory listings Directory enumeration and exposure of file structure
write_file Writes data to files Unauthorized file modification and data tampering
shell_exec Executes system commands Arbitrary command execution and privilege abuse
echo Returns user input Prompt injection and malicious payload reflection

3.3. Proposed Wrapper-Based Security Architecture

The security wrapper was implemented using FastAPI and operated on port 8080. The wrapper acted as an external gateway between the caller and the MCP server. All requests were processed through a security pipeline before reaching the backend server. Requests that failed any security check were rejected immediately and were not forwarded to the MCP server. Requests that passed all checks were forwarded for processing, and the resulting responses were inspected before being returned to the caller.
Figure 1. High-level architecture of the proposed MCP security wrapper. Requests are routed through the FastAPI wrapper before reaching the MCP server.
Figure 1. High-level architecture of the proposed MCP security wrapper. Requests are routed through the FastAPI wrapper before reaching the MCP server.
Preprints 220899 g001

3.4. Security Pipeline and Wrapper Components

The wrapper applies authentication, authorization, validation, threat assessment, and response inspection controls before forwarding approved requests and returning validated responses to the client Shown in Figure 2. The request-processing pipeline begins with JWT based authentication. The wrapper validates tokens supplied through the HTTP Authorization header before any request is processed. Validation includes token structure, signature integrity, expiration time, issued-at time, required claims, and replay status. The required claims include sub, role, iat, exp, and jti. Replay protection is implemented using token identifiers, which prevents previously used tokens from being accepted again. The wrapper also restricts validation to the configured signing algorithm to prevent algorithm-substitution attacks. Requests that fail any authentication check are rejected before reaching the MCP server [18].
After authentication, the wrapper applies rate limiting to protect against excessive request volumes and resource exhaustion attempts. A sliding-window mechanism tracks request frequency using caller identity and source address. Requests that exceed configured thresholds receive an HTTP 429 response [19]. The wrapper then enforces role-based access control through a policy engine that restricts tool usage according to assigned permissions [20]. Three roles are supported: user, analyst, and admin. Each role is granted access only to the tools required for its intended function, reducing unnecessary privileges and limiting exposure to high-risk operations.
Additional protection was provided through input validation, prompt filtering, threat scoring, and response inspection. File-related requests were validated through path normalization and sandbox enforcement to prevent unauthorized access outside approved directories. Command arguments were inspected for dangerous operators, chaining patterns, and high-risk execution attempts. A lightweight prompt guard identified common prompt injection and jailbreak patterns before requests reached sensitive tools. The threat-scoring component evaluated multiple request characteristics and assigned a cumulative risk score. Requests exceeding predefined thresholds were blocked before being forwarded to the MCP server.
Table 4. Role-based tool permissions.
Table 4. Role-based tool permissions.
Role Tools Purpose
User read_file, list_directory, echo Read access
Analyst read_file, list_directory, echo, write_file Data analysis
Admin All tools Administration
The input validator protects file and command operations. For file-related tools, the supplied path is decoded, normalized, resolved, and compared against an allowed root directory. This is intended to prevent direct path traversal, encoded traversal, and access outside the configured sandbox. Path traversal is a known security weakness where attackers use path manipulation to access files outside the intended directory [21,22]. For shell execution, the validator checks command strings for dangerous operators, chaining patterns, and high-risk command keywords. This control addresses command injection risk, which occurs when attacker-controlled input is passed into a command interpreter [23,24]. The threat scorer assigns a cumulative risk score to each request based on suspicious features. High-risk tools, suspicious argument patterns, and combinations of warning signals increase the score. Requests above the blocking threshold are rejected, while requests above the alert threshold are logged for monitoring. The response inspector examines outgoing responses for secret-like patterns before they are returned to the caller. It searches for patterns such as AWS style key strings, private key headers, environment style key value assignments, database connection strings, and generic API key like values. If such content is detected, the wrapper blocks or redacts the response. The audit logger writes structured JSONL records for processed requests, including timestamp, caller identity, method or tool name, status code, triggered security rule, and threat score. This supports traceability and post-incident analysis, consistent with security log management guidance [25]. Table 5 summarizes the relationship between wrapper components, test cases, and STRIDE coverage. The components are designed as independent layers of defense. Authentication verifies identity, the policy engine restricts privileges, the input validator constrains file and command arguments, the prompt guard detects known prompt manipulation patterns, the threat scorer evaluates combined risk, the response inspector prevents leakage after tool execution, the rate limiter protects availability, and the audit logger records security-relevant events.

3.5. Dataset and Synthetic Sensitive Assets

The experimental dataset was designed to resemble realistic enterprise assets while avoiding the use of real sensitive information. The dataset included customer records, financial documents, configuration files, system logs, and simulated secrets. The simulated secrets included environment-style key-value pairs, credential-like values, and private-key-like content. These resources supported realistic file access, exfiltration, and response leakage scenarios during testing while ensuring that no real sensitive data were exposed.

3.6. Test Case Design

The evaluation used controlled scenarios grouped into nine test suites. The test suites covered authentication attacks, file access and exfiltration, command execution, evasion and obfuscation, prompt injection, response leakage, token replay and JWT abuse, denial-of-service behaviour, and legitimate use validation. Together, these test suites provided coverage across the STRIDE threat categories and represented realistic attack patterns that may be encountered in MCP deployments.The attack scripts used the httpx library to send MCP-style HTTP requests with JSON-RPC payloads. This approach provided direct control over request headers, authentication tokens, and payload contents. The same scripts were executed against both environments by changing only the target port. This ensured that both environments were evaluated using identical attack conditions.
Table 6. Test suite overview and evaluation purpose.
Table 6. Test suite overview and evaluation purpose.
ID Category Attacks Techniques Covered
TC1 Authentication Attacks 6 No token, garbage JWT, wrong secret, privilege escalation
TC2 File Access and Exfiltration 13 Path traversal, direct unauthorized reads, URL encoded traversal,
secret file access, and 3 policy compliant sandboxed file reads
used for allowed residual risk validation
TC3 Command Execution 10 Direct shell, chaining, RCE, log tampering, reconnaissance
TC4 Evasion and Obfuscation 10 URL encoding, Base64, Unicode, null byte, homoglyphs
TC5 Prompt Injection 13 Instruction override, DAN, SYSTEM tag, INST token, chained,
Legitimate inputs flagged as malicious (keywords, patterns,
prompt guard triggers)
TC6 Response Manipulation 10 Secret pattern detection, PEM keys, AWS keys, .env content
TC7 Token Replay and JWT Abuse 10 Expired, none-alg, jti replay, clock skew, aud mismatch
TC8 Denial of Service attack 10 Burst, rotation, concurrent, slow drain, large payload flood
TC9 Legitimate Use Validation 3 Normal user requests (echo, safe file read) to ensure functionality
is not blocked

3.7. Evaluation Metrics

Several evaluation metrics were collected during testing. These included attack success rate, vulnerability reduction, response-time overhead, evasion resistance, false-positive rate, rate-limit mitigation, legitimate-use pass rate, and residual risk. Attack success rate measured whether an attack achieved its intended objective. Vulnerability reduction measured the decrease in successful attacks after deploying the wrapper. Performance metrics focused on response-time and memory overhead, while false-positive analysis evaluated the impact of security controls on legitimate requests.
Table 7. Evaluation metrics used in the study.
Table 7. Evaluation metrics used in the study.
Metric Definition Scope
Attack Success Rate (Successful attacks / Total attacks) × 100 Per environment and per TC
Vulnerability Reduction ( V before V after ) / V before × 100 Overall and per STRIDE class
Response Time Overhead ( AvgTime hardened AvgTime insecure ) / AvgTime insecure × 100 Per TC and overall
Evasion Resistance Score (Blocked evasion attempts / Total evasion attempts) × 100 TC4
False Positive Rate (Incorrectly blocked legitimate requests / Total legitimate) × 100 Legitimate request suite

4. Experiments and Evaluation

4.1. Experimental Setup and Execution Procedure

The experiments were conducted on a Windows 11 machine with an Intel Core i7 processor, 16 GB RAM, and Python 3.12. Both environments were executed over the loopback interface to avoid external network variability. The insecure MCP server ran on port 8000, and the FastAPI wrapper ran on port 8080.
Figure 3. Experimental deployment setup
Figure 3. Experimental deployment setup
Preprints 220899 g003
The same dataset and attack scripts were used for both environments. For each individual scenario, the experiment runner recorded the attack identifier, target environment, HTTP response status, result classification, and execution time. In the hardened environment, additional wrapper-specific information was recorded, including the security stage that rejected the request, authentication outcome, tool allow-list decision, path validation result, command filter result, and computed threat score.

4.2. Attack Success Rate and Vulnerability Reduction

The evaluation shows that the wrapper substantially reduced vulnerability exposure compared with the insecure baseline. Across the 69 attack cases, the verified vulnerability reduction is 96% Shown in Table 8. The 96% reduction was calculated by comparing successful attack outcomes in the insecure baseline with successful attack outcomes after wrapper enforcement; legitimate-use validation cases were excluded from this calculation. In the insecure environment, tested attacks succeeded across the evaluated attack categories because the baseline server did not enforce authentication, role based access control, path validation, command filtering, response inspection, rate limiting, or audit logging. In the hardened environment, the wrapper blocked all tested attacks in several categories, including authentication abuse, command execution, evasion and obfuscation, token replay and JWT abuse, response leakage, and rate-limit exhaustion.
File access risk was reduced through sandboxing and path validation, although some policy compliant operations were intentionally allowed. Prompt injection attacks were blocked against the tested patterns, but the strict rule-based prompt guard also produced false positives for benign inputs that resembled attack patterns.

4.3. STRIDE-Based Results

The STRIDE analysis showed that the wrapper provided coverage across all six threat categories evaluated in this study.Table 9 shows the STRIDE based results. Spoofing threats were addressed through JWT validation, token expiry checks, issued-at validation, algorithm restrictions, and replay protection. Tampering threats were mitigated using input validation, command filtering, prompt guard checks, and threat scoring. Information disclosure risks were reduced through file sandboxing and response inspection. However, policy-compliant file operations were intentionally allowed. Denial-of-service threats were mitigated through rate limiting, while elevation of privilege was addressed through role-based tool restrictions. Repudiation was not evaluated through a dedicated attack scenario. Instead, the wrapper supported traceability through comprehensive audit logging of requests and outcomes.

4.4. Denial of Service and Rate Limiting Evaluation

The rate limiting evaluation demonstrated a clear difference between the two environments. The insecure server accepted all request flooding attempts without restriction. In contrast, the hardened environment returned HTTP 429 responses once the configured threshold was exceeded. All TC8 scenarios were successfully mitigated. This corresponds to 100% mitigation for the tested denial-of-service cases. However, this should not be interpreted as complete protection against all forms of DoS attacks. A small number of requests may still be processed before the threshold is reached, which is expected behaviour in threshold-based rate-limiting systems.

4.5. Evasion Resistance

The evasion and obfuscation results showed that the input validator successfully blocked all TC4 attack variants. These included encoded path traversal attempts, Unicode-based variations, null-byte payloads, and other bypass techniques used in the test suite. This suggests that the wrapper relies on input normalization and validation rather than simple string matching. However, the result should be interpreted only within the scope of the evaluated attacks. It does not guarantee protection against future or previously unseen obfuscation techniques.

4.6. False Positive Analysis

The false positive analysis revealed a limitation of the rule-based filtering approach. Three legitimate requests were incorrectly blocked. These included an academic discussion of prompt injection, an OWASP reference URL used for learning purposes, and a sample credential string used for demonstration. The purpose of these tests was to determine whether strict filtering rules could affect normal usage. The results indicate that pattern-based detection is effective against known attack indicators, but it may also flag benign security-related content that resembles malicious input.
Table 10. False-positive scenarios and wrapper outcome.
Table 10. False-positive scenarios and wrapper outcome.
Scenario Input Description Insecure Result Hardened Result
TC5.11 Academic prompt-injection discussion Benign educational sentence: “ignore previous instructions” used only as a classroom/example phrase. Tests whether the prompt guard over-blocks academic security discussion Passed (no guard) Blocked
TC5.12 Legitimate security-learning URL Benign URL: https://owasp.org used for security learning. Tests whether URL filtering is too broad. Passed (no guard) Blocked
TC5.13 Dummy credential example Benign placeholder text: password=sample123. Tests whether the response inspector over-redacts non-real secrets Passed (no guard) Blocked

4.7. Performance Overhead

The performance results indicate that the wrapper introduced only a small operational overhead. The average response time increased from approximately 272 ms in the baseline environment to 275 ms in the hardened environment. This represents an increase of about 3 ms, corresponding to 1.1%. Memory consumption increased from 51.0 MB to 55.3 MB, resulting in an overhead of 4.3 MB or 8.4%. Despite these additional security controls, normal system functionality was preserved. TC8 was excluded from the latency comparison because rate limiting intentionally alters request timing by rejecting requests that exceed the configured threshold.
Table 11 summarizes performance overhead.

4.8. Residual Risk Analysis

The residual risk assessment showed that the wrapper did not indiscriminately block all requests. Several policy compliant operations were successfully allowed. These included authenticated access within assigned roles, file reads within the approved sandbox directory, and standard echo requests. Such actions represent acceptable residual risk under the defined security policy rather than a failure of the wrapper. TC9 also confirmed that legitimate user activities remained functional in the hardened environment. This shows that the wrapper reduced the threat exposure while preserving normal MCP functionality. Audit logs also provided traceability for permitted operations, supporting monitoring and investigation in practical deployments.
Table 12. Residual risk scenarios allowed by policy and Legitimate Usecase
Table 12. Residual risk scenarios allowed by policy and Legitimate Usecase
Scenario Insecure (Allowed) Hardened (Allowed) Policy Reason/ Validation Outcome
Low-risk authenticated access 1 / 1 1 / 1 Permitted by RBAC: complies with user role
Benign file read within sandbox 1 / 1 1 / 1 Path inside ALLOWED_ROOT: no violation
Safe command under policy 1 / 1 1 / 1 Command passes all validator checks
Valid auth and echo call 1 / 1 1 / 1 Request processed normally end to end
Safe file read within sandbox 1 / 1 1 / 1 Path accepted : within ALLOWED_ROOT
Normal user request 1 / 1 1 / 1 No pipeline stage triggered a block

5. Discussion

5.1. Interpretation of Security Findings

The results highlight that an insecure MCP server can have serious security risks when high impact tools are connected without authentication, authorization, validation, rate limiting, or logging. The insecure baseline allowed attacks to succeed across the tested categories, confirming that deployment level misconfiguration can turn MCP tool exposure into a significant attack surface. The FastAPI based wrapper reduced vulnerability exposure by 96% in the controlled evaluation and blocked all tested attacks in several categories. These findings support the argument that an external wrapper can provide meaningful runtime hardening without modifying the underlying MCP server.

5.2. Security–Usability Trade-Off

The results highlight the tradeoff of the security mechanism with usability. The prompt guard blocked the tested prompt injection patterns, but it also blocked benign inputs that resembled malicious payloads. This demonstrates the limitation of static pattern matching. A more semantically aware detector could reduce false positives by considering context, but it would likely introduce additional latency, complexity, and dependency on an external model or classifier. The current wrapper deliberately favors lightweight and interpretable controls, which makes it easier to deploy but less capable of understanding subtle semantic attacks.

5.3. Comparison with Existing MCP Security Approaches

Compared with existing MCP security work, the proposed wrapper occupies a practical deployment level position. Benchmarking studies and systematic analyses are valuable because they identify vulnerabilities and provide evaluation frameworks, but they do not necessarily enforce runtime protection [12,13]. Protocol level or cryptographic approaches can provide stronger trust guarantees, but they may require changes to the protocol or wider ecosystem support. Detection focused frameworks such as MCP Guard provide stronger multi stage analysis for runtime threat detection, but deployment complexity and enforcement focus differ from the lightweight wrapper design [9]. ETDI strengthens tool identity and authorization, while SAMOS addresses data-flow restrictions in MCP-based workflows [10,11]. The wrapper in this paper is not a replacement for these approaches. Instead, it complements them by providing a deployable external security layer that combines authentication, authorization, input validation, prompt filtering, response inspection, rate limiting, and logging. The practical value of the wrapper comes from its ability to protect an existing MCP server without requiring changes to the server implementation. This is useful when the MCP server is legacy, externally managed, rapidly developed, or difficult to modify.

5.4. Scalability and Deployment Considerations

The modular design allows individual controls to be tuned according to deployment needs. For low risk tools, authentication and logging may be sufficient. For high risk tools stronger controls such as role based access control, path validation, command filtering, response inspection, and rate limiting can be additionally enabled. This makes the wrapper suitable as a first line defense in a defense in depth architecture.

5.5. Limitations

The study has several limitations. The evaluation is conducted in a controlled laboratory environment rather than a production deployment. The dataset is synthetic, the tool set is intentionally small, and the experiment uses simulated MCP requests instead of live LLM agent reasoning. This means the results measure request level enforcement and do not fully capture the behavior of real LLM agents interacting with external context. The prompt injection evaluation measures pattern filtering effectiveness rather than semantic prompt injection resilience. The attack scenarios are based on documented vulnerability classes, but they do not cover every possible adaptive attack technique.
The current implementation also has engineering limitations. Token replay protection and rate limiting use local state, which means that state would not automatically be shared across multiple wrapper instances. Production deployment would require distributed state management, such as a shared cache or database, to support horizontal scaling. The JWT implementation uses a shared secret, which is suitable for a controlled prototype but should be replaced or strengthened in production through centralized identity management, secure key rotation, and mechanisms such as OAuth2 or OpenID Connect. The response inspector and prompt guard rely on patterns and heuristics, which means they may miss novel variants or block benign inputs that resemble attacks.
The internal validity of the experiment is strengthened by the controlled design. Both environments use the same machine, dataset, scripts, and underlying MCP server, and the main variable is the presence of the wrapper. Automated execution reduces human error and ensures that attack scenarios are applied consistently. External validity is more limited because real deployments may involve different MCP servers, larger tool ecosystems, multiple users, variable network latency, live LLM reasoning, and attackers who adapt their strategies over time. Construct validity is also limited because attack success rate and blocking rate do not capture every dimension of security. For example, blocking prompt injection like text is not the same as proving robust semantic prompt injection defense.

5.6. Practical Value of Wrapper Based Hardening

The strongest results were observed in authentication enforcement, JWT abuse prevention, command execution blocking, evasion resistance, response leakage prevention, and rate limit exhaustion mitigation. Authentication and policy enforcement are especially important because they determine whether a caller can reach high risk tools. Input validation is also central because file access and command execution tools can become dangerous if user-provided arguments are not constrained. Response inspection adds a protection layer by preventing sensitive content from being returned. Rate limiting reduces denial of service attack by controlling excessive request patterns before they exhaust server resources. From a practitioner perspective, the results suggest that MCP servers should not expose high risk tools directly without security controls. Authentication should be enforced before tool invocation, and role-based access control should restrict tools according to least privilege. File access should be constrained using sandboxing and canonical path validation. Shell execution should be avoided where possible or strictly controlled when required. Responses should be inspected for secret leakage, rate limiting should be applied to reduce request flooding risks, and audit logging should be enabled for traceability and incident response. A wrapper-based architecture provides a practical way to apply these controls externally, but it should be deployed as part of a broader defense-in-depth strategy.

6. Conclusions

This paper presented a security assessment and lightweight hardening approach for MCP servers. An intentionally insecure MCP server was evaluated using 85 controlled scenarios across nine test suites, and a FastAPI-based wrapper was implemented to enforce authentication, role-based access control, input validation, prompt injection filtering, threat scoring, response inspection, rate limiting, and audit logging. The wrapper reduced attack exposure by 96% across the attack cases used for vulnerability reduction calculation, achieved 100% scenario level mitigation for the tested rate limit exhaustion cases, preserved the legitimate-use validation cases, and introduced low overhead, with an average latency increase of approximately 3 ms and memory overhead of 4.3 MB. The evaluation also revealed three false positives in strict rule-based filtering, showing the need to balance security and usability.
The main conclusion is that a lightweight external wrapper can provide measurable deployment-level hardening for MCP servers without modifying the underlying MCP implementation. This is valuable in practical settings where MCP servers may be externally managed, legacy, or difficult to change. However, the wrapper should be viewed as a complementary defense layer rather than a complete solution for all MCP security risks. Future work should evaluate the wrapper in real LLM-agent workflows, larger MCP ecosystems, and production-like network environments. Further improvements should include distributed state management for rate limiting and replay protection, OAuth2 or OpenID Connect integration, secure key rotation, fuzzing and red-team testing, semantic prompt-injection detection, and broader false-positive evaluation.

Author Contributions

Conceptualization, A.K.M. and F.D.; methodology, A.D. and V.K.D.; software, A.D. and V.K.D.; validation, A.D., V.K.D., A.K.M. and F.D.; formal analysis, A.D. and V.K.D.; investigation, A.D. and V.K.D.; resources, A.K.M. and F.D.; data curation, A.D. and V.K.D.; writing—original draft preparation, A.D. and V.K.D.; writing—review and editing, A.D., V.K.D., A.K.M. and F.D.; visualization, A.D. and V.K.D.; supervision, A.K.M. and F.D.; project administration, A.K.M. and F.D.; funding acquisition, not applicable. 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 original data supporting the conclusions of this article will be made available by the authors on request.

Acknowledgments

During the preparation of this manuscript, the authors used OpenAI ChatGPT only for language editing, including grammar checking, translation support, and improving sentence clarity. The AI tool was not used for the design of the study, security analysis, interpretation of results, or generation of any scientific findings or conclusions reported in this work. The authors have reviewed and edited the output and take full responsibility for the content of this publication.

Conflicts of Interest

The authors declare no conflicts of interest.

Abbreviations

The following abbreviations are used in this manuscript:
LLM Large Language Model
MCP Model Context Protocol
JWT JSON Web Token
OWASP Open Worldwide Application Security Project
API Application Programming Interface
STRIDE Spoofing, Tampering, Repudiation, Information Disclosure,
Denial of Service, and Elevation of Privilege
DoS Denial of Service
RBAC Role-Based Access Control
EoP Elevation of Privilege
JSON-RPC JavaScript Object Notation Remote Procedure Call
WAF Web Application Firewall
OAuth2 Open Authorization 2.0
ETDI Enhanced Tool Definition Interface
SAMOS Secure Agent-MCP Orchestration System

References

  1. Anthropic. Model Context Protocol Specification. Available online: https://modelcontextprotocol.io/specification (accessed on 28 February 2026).
  2. OWASP Foundation. OWASP Top 10 for Large Language Model Applications. Available online: https://genai.owasp.org/llm-top-10/ (accessed on 28 February 2026).
  3. Perez, F.; Ribeiro, I. Ignore Previous Prompt: Attack Techniques for Language Models. arXiv 2022, arXiv:2211.09527. [Google Scholar]
  4. 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, Copenhagen, Denmark, November 2023; pp. 79–90. [Google Scholar]
  5. Liu, Y.; Deng, G.; Li, Y.; Wang, K.; Wang, Z.; Wang, X.; Zhang, T.; Liu, Y.; Wang, H.; Zheng, Y.; et al. Prompt Injection Attack against LLM-Integrated Applications. arXiv 2023, arXiv:2306.05499. [Google Scholar]
  6. Kumar, S.; Girdhar, A.; Patil, R.; Tripathi, D. MCP Guardian: A Security-First Layer for Safeguarding MCP-Based AI System. arXiv 2025, arXiv:2504.12757. [Google Scholar]
  7. Hasan, M.; Li, H.; Fallahzadeh, E.; Adams, B.; Hassan, A.E. Model Context Protocol (MCP) at First Glance: Studying the Security and Maintainability of MCP Servers. arXiv 2025, arXiv:2506.13538. [Google Scholar]
  8. Radosevich, B.; Halloran, J.T. MCP Safety Audit: LLMs with the Model Context Protocol Allow Major Security Exploits. arXiv 2025, arXiv:2504.03767. [Google Scholar]
  9. Xing, W.; Qi, Z.; Qin, Y.; Li, Y.; Chang, C.; Yu, J.; Lin, C.; Xie, Z.; Han, M. MCP-Guard: A Multi-Stage Defense-in-Depth Framework for Securing Model Context Protocol in Agentic AI. arXiv 2026, arXiv:2508.10991. [Google Scholar]
  10. Bhatt, M.; Narajala, V.S.; Habler, I. ETDI: Mitigating Tool Squatting and Rug Pull Attacks in Model Context Protocol (MCP) by Using OAuth-Enhanced Tool Definitions and Policy-Based Access Control. arXiv 2025, arXiv:2506.01333. [Google Scholar]
  11. Ntousakis, G.; Stephen, J.; Le, M.; Chukkapalli, S.; Taylor, T.; Molloy, I.; Araujo, F. Securing MCP-Based Agent Workflows. In Proceedings of the 4th Workshop on Practical Adoption Challenges of ML for Systems, Seoul, Republic of Korea, October 2025; pp. 1–6. [Google Scholar]
  12. Yang, Y.; Gao, C.; Wu, D.; Chen, Y.; Li, Y.; Wang, S. MCPSecBench: A Systematic Security Benchmark and Playground for Testing Model Context Protocols. arXiv 2026, arXiv:2508.13220. [Google Scholar]
  13. Guo, Y.; Liu, P.; Ma, W.; Deng, Z.; Zhu, X.; Di, P.; Xiao, X.; Wen, S. MCPXKIT: The Unified Toolkit for Analyzing Model Context Protocol Security. arXiv 2025, arXiv:2508.12538. [Google Scholar]
  14. Wohlin, C.; Runeson, P.; Höst, M.; Ohlsson, M.C.; Regnell, B.; Wesslén, A. Experimentation in Software Engineering; Springer: Berlin/Heidelberg, Germany, 2012. [Google Scholar]
  15. Shostack, A. Threat Modeling: Designing for Security; John Wiley & Sons: Hoboken, NJ, USA, 2014. [Google Scholar]
  16. Rose, S.; Borchert, O.; Mitchell, S.; Connelly, S. NIST Special Publication 800-207; Zero Trust Architecture. National Institute of Standards and Technology: Gaithersburg, MD, USA, 2020.
  17. Siriwardena, P. Edge Security with an API Gateway. In Advanced API Security; Apress: Berkeley, CA, USA, 2020; pp. 103–127. [Google Scholar]
  18. Jones, M.; Bradley, J.; Sakimura, N. JSON Web Token (JWT); RFC 7519; RFC Editor, 2015. Available online: https://datatracker.ietf.org/doc/html/rfc7519 (accessed on 16 May 2026).
  19. Nottingham, M.; Fielding, R. Additional HTTP Status Codes; RFC 6585; RFC Editor, 2012. Available online: https://www.rfc-editor.org/rfc/rfc6585.html (accessed on 16 May 2026).
  20. 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]
  21. OWASP Foundation. Path Traversal. Available online: https://owasp.org/www−community/attacks/PathTraversal (accessed on 16 May 2026).
  22. MITRE Corporation. CWE-22: Improper Limitation of a Pathname to a Restricted Directory. Available online: https://cwe.mitre.org/data/definitions/22.html (accessed on 16 May 2026).
  23. OWASP Foundation. Command Injection. Available online: https://owasp.org/www−community/attacks/CommandInjection (accessed on 16 May 2026).
  24. Common Weakness Enumeration. CWE-77: Improper Neutralization of Special Elements Used in a Command. Available online: https://cwe.mitre.org/data/definitions/77.html (accessed on 16 May 2026).
  25. Kent, K.; Souppaya, M. NIST Special Publication 800-92; Guide to Computer Security Log Management. National Institute of Standards and Technology: Gaithersburg, MD, USA, 2006.
  26. Hou, X.; Zhao, Y.; Wang, S.; Wang, H. Model Context Protocol (MCP): Landscape, Security Threats, and Future Research Directions. arXiv 2025, arXiv:2503.23278. [Google Scholar]
  27. Zhang, D.; Li, Z.; Luo, X.; Liu, X.; Li, P.; Xu, W. MCP Security Bench (MSB): Benchmarking Attacks Against Model Context Protocol in LLM Agents. arXiv 2025, arXiv:2510.15994. [Google Scholar]
  28. Huang, C.; Huang, X.; Tran, N.P.; Fard, A.M. Model Context Protocol Threat Modeling and Analyzing Vulnerabilities to Prompt Injection with Tool Poisoning. arXiv 2026, arXiv:2603.22489. [Google Scholar]
  29. Bühler, C.; Biagiola, M.; Di Grazia, L.; Salvaneschi, G. AgentBound: Securing Execution Boundaries of AI Agents. arXiv 2025, arXiv:2510.21236. [Google Scholar]
  30. Singh, G.; Madisetti, V.K. MCP-Secure: A Runtime Access Control Layer for Privilege-Aware LLM Agent Tooling. IEEE Open J. Comput. Soc. 2026, 1–10. [Google Scholar] [CrossRef]
  31. Maloyan, N.; Namiot, D. Breaking the Protocol: Security Analysis of the Model Context Protocol Specification and Prompt Injection Vulnerabilities in Tool-Integrated LLM Agents. arXiv 2026, arXiv:2601.17549. [Google Scholar]
  32. 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]
Figure 2. Multi-stage request-processing pipeline of the security wrapper.
Figure 2. Multi-stage request-processing pipeline of the security wrapper.
Preprints 220899 g002
Table 1. Comparison of MCP security approaches.
Table 1. Comparison of MCP security approaches.
Approach Auth. Tool Prompt Runtime Prot. Chg.
MCP Guardian Yes Yes Yes Yes No
ETDI Yes Yes No Partial Yes
SAMOS Yes Partial No Yes Yes
Wrapper Yes Yes Yes Yes No
Table 2. STRIDE threat categories, MCP risks, and wrapper controls.
Table 2. STRIDE threat categories, MCP risks, and wrapper controls.
STRIDE Category MCP Security Risk Related Test Cases Wrapper Control
Spoofing Forged or missing credentials TC1, TC7 JWT authentication
Tampering Malicious commands, encoded payloads, prompt manipulation TC3, TC4, TC5 Input validation, prompt guard
Information Disclosure Unauthorized file access, secret leakage TC2, TC6 Path sandboxing, response inspection
Denial of Service Request flooding TC8 Rate limiting
Elevation of Privilege Low-role user invoking high-risk tools TC1, TC3 RBAC and tool allow-list
Repudiation Lack of traceability All TCs Audit logging
Table 5. Security controls and STRIDE coverage.
Table 5. Security controls and STRIDE coverage.
Control Purpose Test Cases STRIDE
Authentication Identity verification TC1, TC7 Spoofing
RBAC Tool restriction TC1, TC3 Elevation of Privilege
Input Validation Attack prevention TC2–TC4 Tampering, Disclosure
Prompt Guard Prompt filtering TC5 Tampering
Response Inspection Secret protection TC6 Disclosure
Rate Limiting DoS protection TC8 Denial of Service
Audit Logging Accountability TC1–TC9 Repudiation
Table 8. Attack success rate and vulnerability reduction by test suite.
Table 8. Attack success rate and vulnerability reduction by test suite.
ID Category STRIDE Tests Insecure Hardened Reduction
TC1 Authenti-cation Attacks Spoofing / EoP 6 6 0 100%
TC2 File Access and Exfil. Attacks Info Disclosure 13 13 3 77%
TC3 Command Execution Attacks Tampering / EoP 10 10 0 100%
TC4 Evasion and Obfuscation Attacks Tampering 10 10 0 100%
TC5 Prompt Injection / False-positive Checks Tampering / EoP 13 10 attack successes + 3 benign cases 0 attack successes + 3 false positives 100% attack blocking; 23% false-positive rate
TC6 Response Manipulation Attacks Info Disclosure 10 10 0 100%
TC7 Token Replay / JWT Abuse Spoofing 10 10 0 100%
TC8 Rate Limit Exhaustion Denial of Service 10 10 0 100%
TC9 Legitimate use and Validation NA 3 3 3 0%
Table 9. STRIDE based security effectiveness.
Table 9. STRIDE based security effectiveness.
STRIDE Category Test Cases Insecure Success Hardened Success Block Rate
Spoofing TC1, TC7 16/16 (100%) 0/16 (0%) 100%
Tampering TC3, TC4, TC5 30/30 attacks succeeded; 3 benign TC5 cases passed 0/30 attacks succeeded; 3/3 benign TC5 cases blocked 100% attack blocking; false positives observed
Information Disclosure TC2, TC6 23/23 (100%) 3/23 (13%) 87%
Denial of Service TC8 10/10 (100%) 0/10 (0%) 100%
Elevation of Privilege TC1, TC3 20/20 (100%) 0/20 (0%) 100%
Repudiation All TCs Covered by audit logger
Table 11. Performance overhead of the hardened wrapper environment.
Table 11. Performance overhead of the hardened wrapper environment.
Metric Baseline MCP Hardened MCP Overhead
Response Time 272 ms 275 ms 1.1%
Memory Usage 51.0 MB 55.3 MB 8.4%
Latency Increase 3 ms +3 ms
Functionality Maintained Maintained None
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.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.
Prerpints.org logo

Preprints.org is a free preprint server supported by MDPI in Basel, Switzerland.

Subscribe

© 2026 MDPI (Basel, Switzerland) unless otherwise stated

Accessibility

Disclaimer

Terms of Use

Privacy Policy

Privacy Settings