Skip to content

feat(dotnet): add MCP security namespace — completes cross-language MCP parity#9

Merged
imran-siddique merged 3 commits intomainfrom
feat/dotnet-mcp-security
Apr 15, 2026
Merged

feat(dotnet): add MCP security namespace — completes cross-language MCP parity#9
imran-siddique merged 3 commits intomainfrom
feat/dotnet-mcp-security

Conversation

@imran-siddique
Copy link
Copy Markdown
Owner

Adds AgentGovernance.Mcp namespace with McpSecurityScanner, McpCredentialRedactor, McpResponseSanitizer, and McpGateway. 46 new tests, all 513 pass. Updates SDK-FEATURE-MATRIX.md to flip .NET MCP from — to ✅.

imran-siddique and others added 3 commits April 15, 2026 09:18
CI optimization:
- Add paths-ignore for docs to 5 code-only workflows
- Add paths filter to Link Check (only run on docs changes)
- Add concurrency groups to 7 heavy workflows
- Docs-only PRs drop from ~14 checks to ~4

README:
- Add v3.1.0 release announcement callout
- Add PyPI version badge
- Update tutorial count to 31

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Kill switch is no longer placeholder: now implements saga handoff
  with handoff_success_count tracking (kill_switch.py:69-178)
- DeltaEngine verify_chain() is no longer a stub: now performs SHA-256
  chain verification (delta.py:67-127)
- Move both from Critical/High gaps to new 'Resolved' section
- Update Processing Integrity coverage (2 of 4 defects, not 3 of 4)
- Update evidence table with current line ranges

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…tor, and sanitizer

Add AgentGovernance.Mcp namespace implementing full MCP security parity with
TypeScript and Rust SDKs:

- McpSecurityScanner: tool poisoning, typosquatting, hidden instructions,
  rug pull, schema abuse, cross-server attack, and description injection detection
- McpCredentialRedactor: regex-based redaction of API keys, bearer tokens,
  connection strings, and secret assignments
- McpResponseSanitizer: response scanning for prompt injection tags,
  imperative phrasing, credential leakage, and exfiltration URLs
- McpGateway: policy enforcement pipeline with deny/allow lists, payload
  sanitization, rate limiting, and human approval gates

Includes 46 xUnit tests covering all threat categories. Updates
SDK-FEATURE-MATRIX.md to flip .NET MCP Security from — to ✅.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@imran-siddique imran-siddique merged commit e571b64 into main Apr 15, 2026
22 of 26 checks passed
@imran-siddique imran-siddique deleted the feat/dotnet-mcp-security branch April 15, 2026 04:16
@github-actions
Copy link
Copy Markdown

Welcome to the Agent Governance Toolkit! Thanks for your first pull request.
Please ensure tests pass, code follows style (ruff check), and you have signed the CLA.
See our Contributing Guide.

@github-actions
Copy link
Copy Markdown

🤖 AI Agent: breaking-change-detector — Summary

🔍 API Compatibility Report

Summary

This pull request introduces the AgentGovernance.Mcp namespace in the .NET SDK, adding new classes and functionality for MCP security features. The changes are additive and do not introduce breaking changes to the existing API. All new additions are well-documented and follow established patterns.

Findings

Severity Package Change Impact
🔵 agent-governance-dotnet Added AgentGovernance.Mcp namespace with new classes (McpSecurityScanner, McpCredentialRedactor, McpResponseSanitizer, McpGateway) New functionality, no breaking changes
🔵 agent-governance-dotnet Added CredentialKind enum and RedactionResult class New public API for credential redaction
🔵 agent-governance-dotnet Added McpGatewayConfig, McpGatewayRequest, McpGatewayDecision, and McpGatewayStatus classes/enums New public API for MCP gateway configuration and decision-making

Migration Guide

No migration steps are necessary as this pull request does not introduce any breaking changes. Downstream users can adopt the new AgentGovernance.Mcp namespace and its classes without impacting existing functionality.

Additional Notes

  • The new classes and methods are well-documented, which will aid developers in understanding and using the new features.
  • The addition of MCP security features aligns with the project's roadmap and enhances cross-language parity.

No breaking changes detected.

@github-actions github-actions Bot added documentation Improvements or additions to documentation ci/cd tests labels Apr 15, 2026
@github-actions
Copy link
Copy Markdown

🤖 AI Agent: docs-sync-checker — Issues Found

📝 Documentation Sync Report

Issues Found

  • McpCredentialRedactor.Redact() in packages/agent-governance-dotnet/src/AgentGovernance/Mcp/McpCredentialRedactor.cs — missing detailed docstring for parameters and return value.
  • McpCredentialRedactor.PlaceholderFor() in packages/agent-governance-dotnet/src/AgentGovernance/Mcp/McpCredentialRedactor.cs — missing detailed docstring for parameters and return value.
  • McpCredentialRedactor.InferKindFromKey() in packages/agent-governance-dotnet/src/AgentGovernance/Mcp/McpCredentialRedactor.cs — missing detailed docstring for parameters and return value.
  • McpGateway class and its methods in packages/agent-governance-dotnet/src/AgentGovernance/Mcp/McpGateway.cs — missing docstrings for methods like EvaluateRequest (incomplete diff, but assuming based on pattern).

Suggestions

  • 💡 Add detailed docstrings for the following methods in McpCredentialRedactor:
    • Redact(input: string) -> RedactionResult: Explain the purpose of the method, the input parameter, and the structure of the RedactionResult.
    • PlaceholderFor(kind: CredentialKind) -> str: Explain the kind parameter and what the method returns.
    • InferKindFromKey(key: str) -> Optional[CredentialKind]: Explain the key parameter and the conditions under which the method returns None.
  • 💡 Add docstrings for all public methods in McpGateway to describe their purpose, parameters, return values, and exceptions.
  • ⚠️ packages/agent-governance-dotnet/README.md — no mention of the new Mcp namespace or its components (e.g., McpCredentialRedactor, McpGateway, etc.). Consider adding a section to describe the new namespace and its functionality.
  • ⚠️ CHANGELOG.md — no entry for the addition of the Mcp namespace and its components. Add a detailed entry summarizing the new features and their purpose.
  • ⚠️ docs/SDK-FEATURE-MATRIX.md — while updated to reflect .NET MCP security support, it does not provide detailed descriptions of the new classes and their functionality. Consider adding more details about the specific capabilities of McpCredentialRedactor, McpGateway, and other new components.
  • ⚠️ docs/compliance/soc2-mapping.md — while updated to reflect MCP security scanning, it does not explicitly mention the new McpCredentialRedactor or McpGateway. Consider adding these components to the relevant sections for clarity.
  • ⚠️ examples/ — no updates were made to the example code to demonstrate the usage of the new Mcp namespace. Consider adding examples for McpCredentialRedactor and McpGateway.

Summary

The PR introduces significant new functionality in the form of the Mcp namespace for .NET, including classes like McpCredentialRedactor and McpGateway. However, there are several documentation gaps, including missing docstrings, outdated README and CHANGELOG, and missing example code. Addressing these issues will ensure the documentation remains in sync with the new features.

Let me know if you need further assistance with any of these updates!

Copy link
Copy Markdown

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI Agent: code-reviewer

Review Summary

This PR introduces the AgentGovernance.Mcp namespace for the .NET SDK, adding critical features such as McpSecurityScanner, McpCredentialRedactor, McpResponseSanitizer, and McpGateway. It also updates the CI/CD workflows and documentation to reflect these changes. The PR includes 46 new tests, and all 513 tests pass.

The changes are generally well-structured and align with the project's goals of enhancing multi-cloud poisoning (MCP) security capabilities. However, there are some areas that require attention to ensure security, correctness, and maintainability.


🔴 CRITICAL

  1. Regex Timeout in McpCredentialRedactor:

    • The RegexTimeout is set to 200ms, which might be insufficient for complex or maliciously crafted inputs. A short timeout could lead to incomplete processing or denial of service (DoS) vulnerabilities if the regex engine times out prematurely.
    • Recommendation: Increase the timeout to at least 1 second or implement a mechanism to handle regex timeouts gracefully.
  2. Regex Patterns in McpCredentialRedactor:

    • The regex patterns used for credential detection are prone to bypasses. For example:
      • The BearerToken regex assumes tokens are alphanumeric with specific characters and a minimum length of 8. However, tokens can vary in format and length.
      • The ApiKey regex assumes specific keywords like api_key or x-api-key, which can be bypassed by using alternative naming conventions.
    • Recommendation: Use a more robust approach for credential detection, such as machine learning models or libraries specifically designed for sensitive data detection (e.g., Microsoft's Presidio or similar tools).
  3. McpGateway Deny/Allow List Matching:

    • The DenyList and AllowList in McpGatewayConfig support prefix patterns ending with *. However, the implementation of pattern matching is not shown in the diff. If this is implemented using regular expressions or string matching, it could be prone to errors or inefficiencies.
    • Recommendation: Ensure that the pattern matching logic is robust and well-tested. Consider using a library or well-tested algorithm for pattern matching.
  4. Concurrency in McpGateway:

    • The McpGateway class is marked as thread-safe, but the implementation of thread safety is not visible in the provided diff. Given the use of shared resources like _rateLimiter and _config, there is a risk of race conditions.
    • Recommendation: Ensure that all shared resources are properly synchronized or use thread-safe data structures.
  5. Rate Limiting in McpGateway:

    • The rate-limiting logic is not visible in the diff. If the rate limiter is not implemented securely, it could be bypassed or lead to inconsistent behavior.
    • Recommendation: Review the rate-limiting implementation to ensure it is robust against common attacks, such as burst traffic or distributed denial-of-service (DDoS) attacks.

🟡 WARNING

  1. Backward Compatibility:

    • The addition of the AgentGovernance.Mcp namespace introduces new public APIs. While this is an additive change, it is essential to ensure that these APIs do not conflict with existing ones.
    • Recommendation: Verify that the new APIs are backward-compatible and do not introduce breaking changes for existing users.
  2. Documentation Updates:

    • The documentation updates are comprehensive, but the addition of new features like McpGateway and McpCredentialRedactor may require more detailed examples and usage guidelines.
    • Recommendation: Add detailed usage examples and best practices for the new features in the documentation.

💡 SUGGESTIONS

  1. Test Coverage:

    • While 46 new tests have been added, it is unclear if they cover all edge cases, especially for the regex patterns and McpGateway logic.
    • Recommendation: Ensure that the test suite includes edge cases for regex patterns, such as unusual or maliciously crafted inputs. Also, test the McpGateway pipeline with various configurations and scenarios.
  2. Error Handling in McpGateway:

    • The McpGateway class processes requests through multiple stages (deny-list, allow-list, payload sanitization, etc.). If an error occurs in one stage, it is unclear how the gateway handles it.
    • Recommendation: Implement and document a clear error-handling strategy for the gateway pipeline. Consider adding tests for error scenarios.
  3. Credential Redaction Logging:

    • The McpCredentialRedactor does not appear to log redaction events. Logging redaction events can be useful for auditing and debugging.
    • Recommendation: Add optional logging for redaction events, including the types of credentials detected and redacted.
  4. Performance Benchmarks:

    • The new features, especially McpCredentialRedactor and McpGateway, may introduce performance overhead. It is essential to ensure that these components perform well under load.
    • Recommendation: Conduct performance benchmarks for the new features and optimize them if necessary.
  5. Cross-Language Consistency:

    • The PR aims to achieve cross-language parity for MCP security features. However, it is unclear if the .NET implementation is consistent with other languages (e.g., Python, TypeScript).
    • Recommendation: Review the implementations in other languages to ensure consistency in functionality and behavior.

Final Assessment

The PR introduces valuable features that enhance the security and governance capabilities of the toolkit. However, there are critical issues related to regex patterns, timeout handling, and concurrency that need to be addressed to ensure robustness and security. Additionally, some areas require further testing, documentation, and performance evaluation.

  • Approval Status: Changes Requested
  • Priority: High

@github-actions
Copy link
Copy Markdown

🤖 AI Agent: security-scanner — Security Analysis of Pull Request

Security Analysis of Pull Request

This pull request introduces the .NET MCP Security Namespace, including McpSecurityScanner, McpCredentialRedactor, McpResponseSanitizer, and McpGateway. These components are critical for runtime governance and security enforcement in AI agents. Below is a detailed security analysis based on the provided diff.


Findings

1. Prompt Injection Defense Bypass

Severity: 🔴 CRITICAL
Attack Vector:
The McpGateway pipeline enforces deny-list, allow-list, payload sanitization, rate limiting, and human approval. However, the McpGatewayConfig allows AutoApprove for tools requiring human approval. If AutoApprove is enabled, malicious payloads could bypass manual review, especially if the BlockOnSuspiciousPayload flag is disabled. This creates a potential bypass for prompt injection attacks embedded in payloads.

Fix:

  • Ensure AutoApprove defaults to false and cannot be overridden for tools flagged as high-risk.
  • Add a mandatory semantic analysis layer for payloads, even when AutoApprove is enabled.
  • Log all auto-approved requests for audit and anomaly detection.

2. Policy Engine Circumvention

Severity: 🟠 HIGH
Attack Vector:
The McpGatewayConfig uses DenyList and AllowList for tool filtering. However, the implementation does not validate wildcard patterns (*) rigorously. A malicious actor could craft tool names that bypass filtering by exploiting ambiguous or overly permissive wildcard matching.

Fix:

  • Implement strict validation for wildcard patterns in DenyList and AllowList.
  • Add unit tests to ensure edge cases (e.g., tool*, *tool, tool*tool) are handled correctly.
  • Log any requests that match ambiguous patterns for further investigation.

3. Trust Chain Weaknesses

Severity: 🔴 CRITICAL
Attack Vector:
The McpGatewayRequest relies on an AgentId field for identification but does not specify how the identity is verified. If the AgentId is not cryptographically validated (e.g., using SPIFFE/SVID or similar mechanisms), attackers could spoof identities and bypass governance policies.

Fix:

  • Require cryptographic validation of AgentId using SPIFFE/SVID or similar zero-trust identity mechanisms.
  • Reject requests with invalid or unverifiable AgentId.
  • Add logging for failed identity validations.

4. Credential Exposure

Severity: 🟡 MEDIUM
Attack Vector:
The McpCredentialRedactor uses regex-based patterns to redact sensitive information. While effective for common patterns, it may fail to detect non-standard credential formats or obfuscated secrets. Additionally, the SanitizedPayload field in McpGatewayDecision could still contain sensitive information if the redactor misses certain patterns.

Fix:

  • Enhance McpCredentialRedactor to support custom regex patterns provided by users.
  • Implement a fallback mechanism to flag payloads with potential sensitive information for manual review.
  • Add logging for all redacted payloads to ensure visibility into redaction effectiveness.

5. Sandbox Escape

Severity: 🔵 LOW
Attack Vector:
No evidence of sandboxing mechanisms in the McpGateway or related classes. While this may be handled elsewhere in the toolkit, the absence of explicit sandboxing in the gateway increases the risk of malicious payloads executing arbitrary code.

Fix:

  • Integrate sandboxing mechanisms (e.g., containerization or process isolation) into the McpGateway pipeline.
  • Ensure payloads are executed in isolated environments with restricted permissions.

6. Deserialization Attacks

Severity: 🟠 HIGH
Attack Vector:
The McpGatewayRequest.Payload field accepts serialized data (e.g., JSON). If the deserialization process is not properly secured, attackers could craft malicious payloads to execute arbitrary code or manipulate the deserialization process.

Fix:

  • Use a secure deserialization library that validates input against a schema.
  • Reject payloads that contain unexpected or dangerous data types.
  • Add tests for common deserialization attack vectors.

7. Race Conditions

Severity: 🔵 LOW
Attack Vector:
The McpGateway pipeline uses a rate limiter (RateLimiter) to enforce call limits. However, there is no evidence of locking mechanisms to prevent race conditions during concurrent requests. This could allow attackers to bypass rate limits by exploiting timing gaps.

Fix:

  • Implement thread-safe locking mechanisms in the rate limiter.
  • Add tests to simulate concurrent requests and ensure rate limits are enforced correctly.

8. Supply Chain Risks

Severity: 🟠 HIGH
Attack Vector:
The pull request does not include a dependency review for the new .NET MCP Security Namespace. This increases the risk of dependency confusion or typosquatting attacks if new dependencies are introduced without proper validation.

Fix:

  • Ensure all new dependencies are reviewed for security vulnerabilities and supply chain risks.
  • Use dependency locking mechanisms to prevent unintentional upgrades to malicious versions.
  • Add a dependency review step to the CI/CD pipeline.

Summary of Findings

Category Severity Description Fix Summary
Prompt Injection Defense Bypass 🔴 CRITICAL AutoApprove and BlockOnSuspiciousPayload flags can allow malicious payloads. Disable AutoApprove for high-risk tools; enforce semantic analysis.
Policy Engine Circumvention 🟠 HIGH Wildcard patterns in DenyList/AllowList can be exploited. Validate wildcard patterns; add edge case tests.
Trust Chain Weaknesses 🔴 CRITICAL AgentId lacks cryptographic validation. Use SPIFFE/SVID for identity validation; log failed validations.
Credential Exposure 🟡 MEDIUM Regex-based redaction may miss non-standard patterns. Support custom regex patterns; flag suspicious payloads for manual review.
Sandbox Escape 🔵 LOW No explicit sandboxing in the gateway pipeline. Integrate containerization or process isolation mechanisms.
Deserialization Attacks 🟠 HIGH Payload deserialization is not secured against malicious input. Use schema validation; reject unexpected data types.
Race Conditions 🔵 LOW Potential timing gaps in rate limiter enforcement. Add thread-safe locking mechanisms; test for concurrent requests.
Supply Chain Risks 🟠 HIGH No dependency review for new .NET MCP Security Namespace. Review new dependencies; implement dependency locking in CI/CD pipeline.

Recommendations

  1. Immediate Actions:

    • Address critical findings related to prompt injection defense and trust chain weaknesses.
    • Ensure cryptographic validation of AgentId and disable AutoApprove for high-risk tools.
  2. Code Improvements:

    • Enhance regex patterns in McpCredentialRedactor and add support for custom patterns.
    • Validate wildcard patterns in DenyList/AllowList to prevent circumvention.
  3. Pipeline Enhancements:

    • Add dependency review for the .NET MCP Security Namespace.
    • Implement sandboxing and secure deserialization mechanisms.
  4. Testing:

    • Add tests for race conditions, deserialization attacks, and wildcard pattern edge cases.
    • Validate redaction effectiveness with diverse credential formats.

Final Rating:

This pull request introduces critical security risks that must be addressed before merging. Immediate fixes are required for prompt injection defense bypass and trust chain weaknesses. Other findings should be prioritized based on their severity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci/cd documentation Improvements or additions to documentation size/XL tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant