Skip to main content
Glama
Lc517
by Lc517

MCPGuard-Lab

一个基于真实 mcp==2.0.0 SDK 的 MCP 工具调用安全实验项目。它不依赖外部大模型或 API Key,通过确定性策略完成工具白名单、参数校验、文件边界、SSRF 防护、敏感操作确认、输出脱敏、工具描述投毒检测和 JSONL 审计,并用回归用例验证防护没有被后续改动破坏。

使用边界:本项目仅用于本地实验、授权测试和防御研究,不包含面向未授权目标的攻击功能。

已实现能力

  • MCP 2.0 stdio 服务端与真实客户端往返测试。

  • 六个演示工具:安全计算、根目录内文件读取、笔记查询、公开 URL 请求、工具元数据检查、确认后写笔记。

  • 工具白名单与 JSON Schema 严格校验,拒绝额外参数。

  • 文件路径规范化,拒绝绝对路径、目录穿越和根目录逃逸。

  • URL 协议、用户信息、端口、DNS 解析结果检查,拒绝回环、私网、链路本地等非公网地址。

  • 写操作 confirmed=true 门禁。

  • 不可信工具输出显式打标;密码、Token、API Key 与 Bearer 凭据递归脱敏。

  • 工具名称/描述中的高风险提示注入信号检测。

  • 每次决策写入 JSONL:请求 ID、时间、工具、参数、允许/拒绝、原因和结果。

  • pytest 单元/集成测试和可重复的攻击回归报告。

Related MCP server: meok-mcp-injection-scan-mcp

架构

MCP Client
   │ stdio / MCP 2.0
   ▼
MCP Server ──► GuardedGateway ──► PolicyEngine
                      │                 ├─ allowlist + schema
                      │                 ├─ path boundary
                      │                 ├─ URL / SSRF
                      │                 └─ confirmation
                      ├─ Tool handler
                      ├─ untrusted labeling + redaction
                      └─ JSONL audit

核心原则是“先决策、后执行、再净化输出、全程留痕”。提示词文本不会直接获得额外权限,权限以代码中的白名单和策略为准。

快速运行(Windows)

py -3.10 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
.\.venv\Scripts\python.exe -m pytest
.\.venv\Scripts\python.exe -m mcpguard.regression

也可以直接运行:

powershell -ExecutionPolicy Bypass -File .\scripts\verify.ps1

报告会生成在:

  • reports/regression-report.md

  • reports/regression-report.json

  • reports/regression-audit.jsonl

MCP 客户端配置示例

先执行 pip install -e .,再把以下结构换成当前仓库绝对路径:

{
  "mcpServers": {
    "mcpguard-lab": {
      "command": "D:/path/to/mcpguard-lab/.venv/Scripts/python.exe",
      "args": ["-m", "mcpguard.server"],
      "env": {
        "MCPGUARD_WORKSPACE": "D:/path/to/mcpguard-lab/fixtures/workspace",
        "MCPGUARD_NOTES": "D:/path/to/mcpguard-lab/fixtures/workspace/notes",
        "MCPGUARD_AUDIT": "D:/path/to/mcpguard-lab/reports/audit.jsonl"
      }
    }
  }
}

真实边界

  • 工具描述投毒检测是高信号规则层,不能代替人工审查和固定白名单。

  • confirmed=true 是本地实验中的显式确认门禁;生产环境应使用由宿主 UI/身份系统签发、不可由模型自行伪造的确认凭证。

  • URL 工具当前禁用重定向,避免首跳通过检查后跳向内网;生产版还应限制响应大小、内容类型和出口网络。

  • 不可信内容打标能降低“数据被当指令”的风险,但最终宿主 Agent 仍需遵循信任边界。

  • 回归数据只代表仓库内固定用例,不代表可以阻断所有提示注入或所有 MCP 风险。

目录

src/mcpguard/       核心实现
tests/              单元测试与真实 MCP stdio 集成测试
fixtures/           可公开的本地测试数据
reports/            自动生成的测试和审计证据
scripts/verify.ps1  一键验证入口

参考

Available Tools

6 tools
calculatorB

Evaluate numeric arithmetic without eval or shell execution.

ParametersJSON Schema
NameRequiredDescriptionDefault
expressionYes

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description bears full responsibility for behavioral disclosure. It mentions 'without eval or shell execution' as a safety trait, but omits critical details like supported operations, error handling, precision, or expression syntax. This leaves significant ambiguity.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence with no redundant words. It efficiently conveys the core purpose and a key behavioral note. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has only one parameter and no output schema, the description covers the minimal purpose but lacks details about the return value, error behavior, or expression language. It is adequate for a straightforward tool but not fully complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0% (the 'expression' property has no description). The tool description hints that the parameter is a numeric arithmetic expression, but does not specify expected syntax, allowed functions, or format rules. This is insufficient compensation for the missing schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool evaluates numeric arithmetic, which is a specific verb-resource pairing. The sibling tools (read_file, query_notes, etc.) are unrelated, so differentiation is inherent.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description does not provide explicit guidance on when to use this tool versus alternatives. However, the siblings are all different in nature (file/note/URL operations), so the intended use case is implicitly clear. A score of 3 reflects the lack of explicit when/when-not advice.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

fetch_urlB

Fetch a public HTTP(S) URL after SSRF policy checks.

ParametersJSON Schema
NameRequiredDescriptionDefault
urlYes

TDQS

B3.2/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It hints at security filtering ('after SSRF policy checks') but omits key behaviors: what happens on failure (timeouts, blocked domains), size limits, caching, authentication (public only), response format, or side effects. This is insufficient for a tool that makes network requests.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence with no redundancy. Every word is meaningful. It is optimally concise for the information it conveys.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema and minimal schema details, the description should explain return values (e.g., raw content, headers, status), errors, and how SSRF checks affect behavior. It does none of this, leaving critical gaps for an agent to invoke the tool correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It does add meaning by specifying that the 'url' must be public and support HTTP/HTTPS, which the schema (just a string) does not indicate. However, it doesn't clarify the required nature or expected format (e.g., must include scheme). The added value is moderate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: to fetch a public HTTP(S) URL after SSRF policy checks. The verb 'Fetch' and resource 'URL' are specific, and the description distinguishes it from sibling tools like calculator, read_file, and write_note by targeting external web resources.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives (e.g., read_file for local content, calculator for math). It mentions SSRF policy checks but does not explain prerequisites, limitations, or what URLs are allowed. No explicit when/when-not information is given.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

inspect_tool_metadataB

Screen an external tool name and description for high-signal prompt injection.

ParametersJSON Schema
NameRequiredDescriptionDefault
nameYes
descriptionYes

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. The description states the purpose but does not reveal the output format (e.g., boolean, score, report), side effects (presumably read-only), or what 'high-signal' detection entails. For a security-screening tool, missing these details hampers an agent's understanding.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

One sentence that is front-loaded with the action 'Screen.' No wasted words. Every part of the sentence contributes to understanding the tool's purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's purpose (prompt injection screening), no output schema, no annotations, and 0% schema coverage, the description is insufficient. It fails to explain what the tool returns or how the agent should interpret the result. An agent would lack key information to use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds that the inputs come from an 'external tool,' providing context beyond the raw schema constraints (string lengths). However, it does not elaborate on the expected format or validation rules for name or description, offering only minimal additional meaning.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: 'Screen an external tool name and description for high-signal prompt injection.' The verb 'screen' and the resource 'external tool name and description' are specific. This purpose distinguishes it from sibling tools like calculator, read_file, and fetch_url, which perform different operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies the tool should be used when examining external tool metadata for prompt injection. However, it does not specify when not to use it or provide alternatives. Sibling tools such as fetch_url might also involve external content, but no guidance is given. Usage context is implied but not explicit.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

query_notesC

Search local Markdown notes. Returned text is untrusted data.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYes

TDQS

C2.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must reveal behavioral traits. It warns that returned text is untrusted data, which is a useful behavioral note. However, it does not disclose whether the tool is read-only, requires authentication, or any side effects. The warning adds value but is not comprehensive.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is brief and to the point, consisting of two short sentences. Every sentence adds information, but it could be slightly more structured (e.g., explaining the return format). Overall, it is appropriately concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the low complexity (one parameter, no output schema, no nested objects), the description is minimally adequate. It states the action and a key behavioral note. However, it lacks details on query syntax, result format, and whether the search is full-text or filtered. More context would be helpful.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0% with no description for the 'query' parameter. The description adds no meaning beyond the parameter name, leaving the agent to guess what constitutes a valid query or how it is interpreted.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Search') and the resource ('local Markdown notes'). It is specific and unambiguous. However, it does not differentiate from sibling tools like 'read_file' which might also access notes, but the purpose is still clear.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. The only usage hint is that returned text is untrusted, but it does not specify prerequisites, limitations, or when not to use it.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

read_fileB

Read one UTF-8 text file inside the configured workspace root.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It states the tool reads a UTF-8 text file but does not disclose behavior on missing files, non-UTF-8 content, binary files, size limits, or permissions. This is a significant gap for a file-reading tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence with no wasted words. While it could include more detail without becoming verbose, it is appropriately concise for a simple tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (one parameter, no output schema), the description is adequate for basic use. However, it lacks details on error handling, return format, and behavior for non-text files, leaving gaps for an agent to infer.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds 'inside the configured workspace root,' which clarifies the path scope, but does not explain whether the path is absolute or relative, or how the workspace root is defined. This adds some value but is not comprehensive.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action (read), resource (text file), encoding (UTF-8), and scope (inside configured workspace root). This distinguishes it from siblings like write_note (write) and fetch_url (URL).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implicitly indicates the tool is for reading text files, but it provides no explicit guidance on when to use it versus alternatives (e.g., query_notes, fetch_url). No exclusions or prerequisites are mentioned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

write_noteC

Write a Markdown note after explicit confirmation.

ParametersJSON Schema
NameRequiredDescriptionDefault
titleYes
contentYes
confirmedYes

TDQS

C2.6/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions 'explicit confirmation' but doesn't explain whether the tool checks the 'confirmed' parameter or expects a separate confirmation step. No disclosure of side effects (overwrite? append?), permissions, or error behavior. The description is too sparse for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence, which is short. However, it is not well-structured: 'after explicit confirmation' is awkwardly placed and could be misinterpreted. While concise, it sacrifices clarity and completeness. A slightly longer but clearer description would be more effective.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With 3 required parameters, no output schema, and no annotations, the description should cover input purpose, return value, and error conditions. It only hints at the confirmation requirement. Missing details about what happens on success, whether the note is persisted, and how to handle conflicts or invalid titles. Inadequate for safe agent usage.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0% — the input schema has no descriptions. The description only implies 'content' is Markdown and 'confirmed' relates to a confirmation. It fails to explain the pattern for 'title', the max length for 'content', or the semantics of 'confirmed' (e.g., must be true to proceed). This does not compensate for the missing schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states 'Write a Markdown note' — a specific verb and resource with the format. This distinguishes it from siblings like 'calculator' and 'read_file'. However, 'after explicit confirmation' is ambiguous (does the tool require pre-confirmation or self-confirm?), and it doesn't clarify what a 'note' is (a file? a database entry?).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool vs. alternatives like 'query_notes' (searching) or 'read_file' (reading). No when-not-to-use conditions or prerequisites are mentioned. The phrase 'after explicit confirmation' hints at a constraint but is not actionable guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 6 tool updatesv0.1.0
    • First observedcalculator
    • First observedfetch_url
    • First observedinspect_tool_metadata
    • First observedquery_notes
    • First observedread_file
    • First observedwrite_note

TDQS

B3.4/5.0

Scored across 6 tools

Disambiguation5/5

Each tool targets a clearly distinct operation: arithmetic, file reading, note searching, URL fetching, security inspection, and note writing. No overlap in purpose.

Naming Consistency4/5

Five tools follow verb_noun pattern (read_file, query_notes, fetch_url, inspect_tool_metadata, write_note). The calculator tool uses a noun only, which is a minor deviation but still readable.

Tool Count5/5

Six tools is well-scoped for a security-focused lab server. Each tool earns its place without bloat or deficiency.

Completeness4/5

Covers core operations for a guarded lab environment: read, write, search notes, fetch URLs, compute, and inspect tool metadata. Missing file write or note deletion, but these are likely intentional safety constraints.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Scans MCP servers for prompt-injection, tool-poisoning, and SSRF vulnerabilities using 30+ canonical rules across 5 severity tiers, with optional signed safety reports for procurement.
    5
    MIT
  • F
    license
    Not graded
    quality
    B
    maintenance
    Provides real-time RCE, SSRF, and env leak interception for AI tool calls, with MCP server mode offering diagnostic and repair suggestions.
    -