Source-linked AI summary

MCP Guardian: A Security-First Layer for Safeguarding MCP-Based AI System

Sonu Kumar, Anubhav Girdhar, Ritesh Patil, Divyansh Tripathi

arXiv:2504.12757v2cs.CRcs.AI

TL;DR

MCP makes tool integration more uniform, but its openness leaves MCP systems exposed to malicious or compromised servers and other runtime threats. MCP Guardian adds middleware checks and monitoring; the authors report that it blocks common threats with modest performance overhead.

  • Problem

    MCP’s openness creates security risks from malicious or compromised servers, while the literature lacks an integrated defense-in-depth layer for security and monitoring.

    Source: §2.2 · p. 3, §2.5 · p. 6
  • Method

    MCP Guardian intercepts MCP calls as middleware to check authentication, rate limits, and suspicious patterns, then forwards accepted calls and logs server responses.

    Source: §3.1 · p. 6, §3.3 · p. 8
  • Results

    MCP Guardian blocked unauthorized tokens, malicious commands, and excessive request rates; its controlled local latency overhead was 10–15%.

    Source: §4.3 · p. 11, §4.2.2 · p. 11
  • Takeaways & Limitations

    The authors conclude that MCP Guardian can strengthen MCP workflows without disrupting their simple request flow, supporting safer and more accountable agentic AI.

    Source: §6 · p. 14

    The proof-of-concept WAF uses basic pattern matching, local-file logging may not scale well, and Guardian cannot fully protect against compromised servers or malicious tool code.

    Source: §5.4 · p. 13

Abstract

from arXiv · show

As Agentic AI gain mainstream adoption, the industry invests heavily in model capabilities, achieving rapid leaps in reasoning and quality. However, these systems remain largely confined to data silos, and each new integration requires custom logic that is difficult to scale. The Model Context Protocol (MCP) addresses this challenge by defining a universal, open standard for securely connecting AI-based applications (MCP clients) to data sources (MCP servers). However, the flexibility of the MCP introduces new risks, including malicious tool servers and compromised data integrity. We present MCP Guardian, a framework that strengthens MCP-based communication with authentication, rate-limiting, logging, tracing, and Web Application Firewall (WAF) scanning. Through real-world scenarios and empirical testing, we demonstrate how MCP Guardian effectively mitigates attacks and ensures robust oversight with minimal overheads. Our approach fosters secure, scalable data access for AI assistants, underscoring the importance of a defense-in-depth approach that enables safer and more transparent innovation in AI-driven environments.

1. INTRODUCTION

Agentic LLMs can chain tool calls, but bespoke integrations are difficult to scale and MCP’s openness creates security and observability risks. MCP Guardian is introduced as a middleware layer to secure and monitor MCP interactions.

1. INTRODUCTION

  • Agentic LLMs increasingly orchestrate actions across external systems, extending their role beyond text answers and summaries.Chaining multiple tool calls can address problems beyond the written word.Source: §1 · pp. 1–2
  • MCP Guardian intercepts tool calls to enforce authentication and authorization, apply rate limits, log and trace activity, and scan suspicious inputs with a lightweight WAF.The middleware draws on zero-trust security, web application firewalls, and distributed tracing practices.Source: §1 · p. 2

2.1. AI Agents and Tool Integration; 2.2. The Emergence of MCP

  • MCP offers a unified, extensible interface for discovering and invoking tools, replacing repeated bespoke integrations with a shared request/response channel.Earlier plugin and API approaches often required patchwork solutions with inconsistent access controls and limited audit trails.Source: §2.2 · p. 3, §2.1 · p. 3

2.2. The Emergence of MCP

  • MCP’s openness leaves malicious or compromised servers able to cloak harmful code and exfiltrate sensitive data, while comprehensive security strategies remain underdeveloped.The introduction also identifies risks from malicious prompts or compromised servers, including unauthorized exfiltration and destructive operations.Source: §1 · p. 2, §2.2 · p. 3

2.3. Security in LLM-Orchestrated Workflows; 2.3.1. Documented Attack Vectors in MCP

  • Agentic workflows can autonomously chain tool calls, raising security concerns that motivate continuous request validation, parameter sanitization, and logging.The paper frames documented attack vectors as arising from the flexibility of MCP-based communication.Source: §2.3 · p. 3, §2.3.1 · p. 3

1. Tool Poisoning Attacks

Tool poisoning hides malicious instructions inside apparently benign tool documentation, while tool-name conflicts can steer an LLM toward a counterfeit server.

1. Tool Poisoning Attacks

  • Hidden instructions in a seemingly ordinary addition tool can prompt unauthorized reading and exfiltration of SSH keys and local MCP configuration files.The described example embeds these directives in the tool documentation while presenting the tool as an arithmetic function.Source: §1 · p. 4

2. Tool Name Conflicts

  • Attackers can register MCP servers under names resembling trusted tools, potentially causing sensitive data leaks or unintended command execution if users or models confuse them.The passage gives “tavily-mcp” and “mcp-tavily” as an example pair.Source: §2 · p. 4

3. Shadowing Attacks (Overwriting Tool Descriptions)

MCP-related threats include hijacked tool descriptions, spoofed installers, command injection, and malicious updates to tools that initially appear safe.

3. Shadowing Attacks (Overwriting Tool Descriptions)

  • A trusted tool’s description can be overwritten to silently reroute its behavior, such as sending email messages to an attacker’s address.The cited example describes a routine “send_email” tool being redirected.Source: §3 · p. 4

4. Installer Spoofing

  • Tampered community MCP installers can compromise system configurations or introduce backdoors, especially when users skip verification.The passage names mcp-get and smithery-cli as examples of community-driven installers that may lack robust integrity checks.Source: §4 · p. 5

5. Command Injection Vulnerabilities

  • Dynamically placing user-supplied parameters into shell commands creates command-injection risk; one cited study found 43% of tested MCP server implementations susceptible.An attacker can use shell metacharacters in this setting to execute arbitrary code.Source: §5 · p. 5

6. MCP Rug Pulls

  • A tool that initially appears safe can later add malicious logic; without version pinning or code signing, silent updates can enable data theft or privilege escalation.The passage calls this threat a “rug pull.”Source: §6 · p. 5

7. Token Theft and Account Takeover

The paper describes risks from exposed credentials and sandbox escapes alongside gaps in observability and protocol-level security. MCP Guardian is positioned as a unified layer for intercepting and monitoring requests.

7. Token Theft and Account Takeover

  • Stolen OAuth tokens or API credentials can let attackers impersonate legitimate clients to access emails, databases, or other resources.The passage identifies insecure storage and exposure through logs as routes to token theft.Source: §7 · p. 5

8. Sandbox Escape

  • Sandboxing does not guarantee host isolation: library vulnerabilities or misconfigurations can give malicious scripts unwarranted host access.The passage lists system calls, buffer overflows, and third-party dependency logic errors as escalation paths.Source: §8 · p. 5

2.4. Observability and Distributed Systems

  • Granular request and response instrumentation is needed because LLM agents can chain tool calls without explicit user direction, complicating debugging and forensics.The passage notes that tools such as OpenTelemetry can correlate logs and traces across services.Source: §2.4 · pp. 5–6

2.5. Gap in the Literature

  • Prior efforts address parts of access control, but the literature identifies a gap in an integrated defense-in-depth framework combining security and observability for MCP workflows.The listed capabilities include authentication and authorization, rate limiting, WAF scanning, intrusion detection, logging, and tracing.Source: §2.5 · p. 6

2.6. Positioning of Our Work

  • MCP Guardian is positioned as a unified layer that intercepts each request to enforce authentication, rate limits, suspicious-pattern detection, and logging.The paper describes the approach as lightweight and intended to integrate without major restructuring of MCP servers.Source: §2.6 · p. 6

3. RESEARCH METHODOLOGY

MCP Guardian is middleware that intercepts MCP tool calls and centralizes security checks. It validates tokens, limits request rates, and scans inputs before forwarding calls to servers.

3.1. Overview of the MCP Guardian Approach

  • MCP Guardian intercepts tool calls through an override of MCP’s invoke_tool method, centralizing authentication, authorization, rate limiting, monitoring, and WAF scanning.The middleware approach avoids requiring security checks to be embedded in each tool server.Source: §3.1 · p. 6

1. Authentication and Authorization

  • Each request must have a valid API token, which can be restricted to particular tools or read-only versus administrative privileges.Source: §1 · p. 7

2. Rate Limiting

  • A per-token request counter denies further calls after a configured threshold, helping prevent resource exhaustion and LLM-triggered infinite loops.The passage gives five requests per minute as an example threshold.Source: §2 · p. 7
  • The WAF scans request arguments for malicious patterns and blocks or flags suspicious inputs before they reach the MCP server.Examples include SQL injection signatures and destructive file commands.Source: §2 · p. 7

4. Logging and Observability

MCP Guardian records requests and responses and can connect their flow across distributed systems. Its architecture checks requests before server invocation and logs responses on return.

4. Logging and Observability

  • Each request and response is logged with context such as the caller, parameters, timestamps, and warnings; optional OpenTelemetry integration supports end-to-end request correlation.Source: §4 · p. 7

3.3. System Architecture

  • The tool-call sequence runs from client request through Guardian checks to server invocation, then logs the server response before returning it to the client.Source: §3.3 · pp. 7–8, Figure 1 · p. 7

3.4. Implementation Details

  • The Python reference implementation uses middleware to intercept calls between the AI client and underlying tool servers through a single class.Source: §3.4 · p. 8

3.4.1. Core Classes and Methods

  • MCPGuardian overrides the default invocation method, while guarded_invoke_tool validates request parameters, applies security rules, logs data, and forwards only calls that pass all checks.Source: §3.4.1 · p. 8

1. Secure Token Storage (Optional)

The implementation describes optional token protection alongside request logging, WAF pattern checks, rate limits, and token configuration choices.

1. Secure Token Storage (Optional)

  • Tokens can be encrypted in storage, and higher-assurance workflows can use short-lived, scope-limited tokens to limit harm from accidental exposure.The passage gives five minutes as an example token lifetime.Source: §1 · p. 8

2. Logging and Observability

  • Request and response logs capture timestamps, tool names, and user identifiers; suspicious references to SSH files or tokens can trigger warnings or critical entries.Custom notification functions can support real-time alerts.Source: §2 · p. 8

3. Suspicious Pattern Detection (WAF Layer)

  • A regex-based WAF flags SQL injection, destructive shell commands, and references to sensitive files or environment variables, with rules extendable for domain-specific checks.Source: §3 · p. 8

4. Rate Limiting

  • A per-token counter returns a “429 Too Many Requests” error when calls exceed a configured interval threshold, helping prevent runaway processes or denial-of-service scenarios.Five requests per minute is an example threshold.Source: §4 · p. 9

1. Tokens

  • Tokens may come from a file or environment variable by default, or from a dynamic backend that generates encrypted or short-lived credentials.Source: §1 · p. 9

2. Rate Limits

The implementation offers configurable rate limits, WAF rules, and logging options, plus a short setup path and extensible features for enterprise use.

2. Rate Limits

  • Rate limits use a numerical threshold, such as five requests per minute per token, and can be changed at runtime for different workloads or policies.Source: §2 · p. 9

3. WAF Patterns

  • The default WAF rules target common attacks, including SQL injection, script tags, and destructive commands; users can add domain-specific rules or intrusion detection systems.Source: §3 · p. 9

4. Logging & Tracing

  • Logs can be written locally or sent to remote services, with distributed tracing and optional real-time alerts for critical or suspicious events.Source: §4 · p. 9

3.4.3. Code Example

  • The code example installs Guardian by replacing the MCP invocation method with guarded_invoke_tool; optional modules can add secret detection or encrypted short-lived credentials.The paper says this setup applies the security and monitoring stack to the server’s exposed MCP tools.Source: §3.4.3 · pp. 9–10

3.5. Advanced Features

  • Enterprise extensions include remote logging, role-based access control, dynamic policy updates, and anomaly detection.Source: §3.5 · p. 10

4. RESULTS

MCP Guardian blocked the tested malicious commands, unauthorized tokens, and excessive request rates. In controlled local tests, its added processing increased median latency by about 3–4 ms and produced 10–15% overhead.

4.1.1. Prompt Injection and Destructive Commands

  • The WAF blocked a tested rm -rf / request, and a 100-call burst was rejected after the configured limit of five requests per token.The WAF recognized the substring rm\s+-rf; excess requests received a “429 Too Many Requests” status.Source: §4.1.1 · p. 10

4.1.2. Preventing Unauthorized Access

  • Requests without a token or with an invalid token were denied with an “Unauthorized” error, and the authors report that these checks thwarted typical attack vectors.The tests are presented as reducing risks of unintentional and malicious misuse.Source: §4.1.2 · pp. 10–11

4.2.1. Experimental Setup

  • Load tests compared get_forecast calls to a baseline without Guardian against calls with authentication, rate limiting, and WAF scanning on an 8-core VM running Python 3.12.The server was a simple weather MCP server.Source: §4 · p. 10, §4.2.1 · p. 11

4.2.2. Latency Measurements

  • Guardian added about 3–4 ms in median latency, with 10–15% overhead in the controlled local environment; Table 1 concerns median and 95th-percentile latency across scenarios.The reported overhead primarily comes from token lookups, rate-limit counters, regex WAF checks, and logging requests and responses.Source: §4.2.2 · p. 11, Table 1 · p. 11

4.3. Summary of Results

  • Guardian blocked unauthorized tokens, malicious commands, and excessive request rates, while adding 10–15% overhead in a controlled local environment.The results describe the overhead as modest for typical AI-driven applications.Source: §4.3 · p. 11, §4.2.2 · p. 11

5. DISCUSSION AND FUTURE WORK

The discussion places MCP Guardian within a broader defense-in-depth approach, while identifying limits in its current implementation. It proposes expanded observability, MCP security standards, and interoperability with mcpo as future directions.

5.1. Defense-in-Depth for Agentic AI

  • Guardian’s checks should be complemented by sandboxing, signed tools, and least-privilege credentials to address risks that request-level controls do not cover.The discussion gives a read-only weather-data role as an example of restricting permissions.Source: §5.1 · p. 12

5.2. Enhanced Observability and Governance

  • The current implementation focuses on core logging, rate limiting, and WAF checks; distributed tracing, audit and compliance features, and anomaly detection are proposed to strengthen oversight.Distributed traces could link steps across MCP servers and help diagnose errors in multi-tool sequences.Source: §5.2 · p. 12

5.3. Toward a Standardized Security Layer in MCP

  • The authors call for MCP security standards, including secure-transport extensions, shared policy-language integration, and trusted registries for vetted, cryptographically signed servers.OAuth 2, mTLS, and Open Policy Agent’s Rego are given as examples.Source: §5.3 · pp. 12–13

5.4. Limitations

  • The proof-of-concept WAF uses basic pattern matching, local-file logging may not scale, and Guardian cannot fully protect against compromised servers or malicious tool code.The authors also identify per-agent identity and quota tracking as non-trivial when multiple LLMs share an instance.Source: §5.4 · p. 13

5.5. Interoperability with mcpo

  • mcpo exposes MCP servers as RESTful OpenAPI services, and the authors propose pairing it with Guardian’s security checks for a layered, interoperable approach.The proposed pairing assigns Guardian authentication, rate limiting, and WAF checks while mcpo provides a web-standards-aligned interface.Source: §5.5 · p. 13

6. CONCLUSION

The conclusion presents MCP Guardian as a middleware layer that applies authentication, rate limiting, WAF scanning, and logging to MCP workflows. The recommendations extend that approach with developer training, testing, signed registries, and least-privilege safeguards.

6. CONCLUSION

  • MCP Guardian applies authentication, rate limiting, WAF scanning, and logging to MCP workflows without disrupting the simple MCP workflow; the authors report that it blocks common threats and maintains performance at scale.The conclusion names policy engines, vetted tool registries, real-time anomaly detection, and open telemetry standards as future directions.Source: §6 · p. 14

7. RECOMMENDATIONS

  • The recommendations include security training, zero-trust practices, sandboxing, signed tool registries, least-privilege tokens, regular code reviews, penetration tests, and WAF-rule updates.The authors also recommend collaboration on best practices, threat intelligence, and protocol extensions.Source: §7 · p. 14
Loading 2504.12757v2…