Skip to main content
Glama
TanvirIslam-BD

permission-aware-mcp

Permission-Aware MCP Security System

A production-grade Model Context Protocol server and client suite that demonstrates server-enforced permission management, risk assessment, and tamper-resistant audit logging.

It exposes four classic file-system tools — read_file, write_file, delete_file, execute_command — each classified by risk and gated by a permission policy. Privileged operations cannot run without explicit, single-use human approval.

Why this design

The defining principle: the server is the security boundary. A server can never trust a client to enforce restrictions on its behalf, so every check — policy, path confinement, approval, audit — happens server-side. Clients only surface the server's decisions and relay an explicit human approval back.

Control

How it works

Sandbox confinement

All file access passes through safe_resolve, which rejects absolute paths and .. traversal and verifies (after symlink resolution) that the target stays inside data/. Enforced at execution — even an approved escape attempt is blocked.

Permission policy

Each tool maps to allow / ask / deny. Stored in config/permissions.json, hot-reloaded on change, with risk-derived fail-safe defaults for unknown tools.

Risk assessment

Every tool has an inherent risk (lowcritical) from a single source of truth, shown at approval time and used to derive default policy.

Human-in-the-loop approval

An ask operation returns a single-use, args-bound, expiring token instead of executing. It runs only when a human relays the token back via approve_operation. The LLM never receives that tool, so it cannot approve its own calls.

Audit trail

Append-only JSONL with UTC timestamps, stored outside the sandbox so the file tools can't tamper with it. Every decision, approval, and outcome is recorded.

Related MCP server: quick-shell

Architecture

┌──────────────────┐        stdio (MCP)        ┌────────────────────────────┐
│  Client / Host   │ ────────────────────────► │  server.py (the boundary)  │
│                  │                            │                            │
│ gui_client.py    │   call_tool ──────────►    │  ┌──────────────────────┐  │
│ host_app.py      │                            │  │ policy → risk → gate │  │
│ cli_demo.py      │   ◄─ approval_required ──   │  │   allow / ask / deny │  │
│                  │                            │  └──────────┬───────────┘  │
│ (one background  │   approve_operation ──►    │   safe_resolve (sandbox)   │
│  event loop owns │                            │   AuditLog (outside data/) │
│  the session)    │   ◄─ ok / denied / error   │   ApprovalStore (tokens)   │
└──────────────────┘                            └────────────────────────────┘

Tool results use one uniform JSON envelope:

{"status": "ok",                "result": "..."}
{"status": "denied",            "reason": "...", "risk": "..."}
{"status": "approval_required", "token": "...", "summary": "...", "risk": "...", "expires_in": 180}
{"status": "error",             "message": "..."}

Layout

mcp_security/
  config.py       Settings & resolved paths (env-overridable)
  paths.py        Sandbox confinement (safe_resolve)
  risk.py         Risk classification (single source of truth)
  policy.py       allow/ask/deny engine, hot-reloadable
  audit.py        Append-only JSONL audit log
  approvals.py    Single-use, args-bound, expiring tokens
  server.py       FastMCP server — the enforcement boundary
  client.py       Background-loop MCP connection (Gradio-safe)
  gui_client.py   Gradio operator console
  host_app.py     Gradio AI host (OpenAI), human-in-the-loop
  cli_demo.py     Headless end-to-end demonstration
tests/            Unit tests for the deterministic core
config/  data/  logs/   Runtime state (generated)

Setup

python -m venv .venv
.venv\Scripts\activate          # Windows
# source .venv/bin/activate     # macOS / Linux
pip install -r requirements.txt

For the AI host, copy .env.example to .env and set OPENAI_API_KEY.

Running

All commands run from the project root.

Headless demo (no API key needed — the fastest way to see the whole gate):

python -m mcp_security.cli_demo

Operator console (browse tools/resources/prompts, manage policy, view audit log) at http://127.0.0.1:7863:

python -m mcp_security.gui_client

AI host (chat with an LLM that uses the gated tools) at http://127.0.0.1:7864:

python -m mcp_security.host_app

The clients launch the server (python -m mcp_security.server) themselves over stdio. To point a client at a different server, pass a module path or script file:

python -m mcp_security.gui_client path/to/other_server.py

Tests

python -m pytest -q

The suite covers the deterministic security core — path confinement (traversal/absolute/symlink-escape), policy defaults & hot-reload, token binding/single-use/expiry, audit structure, and risk classification. The MCP/Gradio/OpenAI layers are exercised by cli_demo.py and the included smoke checks.

Configuration

Every setting is overridable via environment variable (see .env.example): sandbox/log/config directories, max file size, and approval-token TTL.

Security notes & limits

  • execute_command is simulated — it never runs a real subprocess, matching the original's stance. It is denied by default regardless.

  • Approval tokens live in the server's memory; restarting the server clears pending approvals (by design — stale approvals should not survive a restart).

  • The bundled clients run on 127.0.0.1 with no authentication; they are operator tools, not multi-tenant services. For shared deployment, add authentication and per-session state.

  • The server's policy file (config/permissions.json) is the control plane; protect it with filesystem permissions in production.

Available Tools

5 tools
approve_operationA

Approve and execute a pending ask operation.

This is the ONLY way an ask operation runs. The token must have been issued by the server for the exact operation being approved; it is single-use and expires. Intended to be called on behalf of an explicit human approval action, not autonomously by an LLM.

ParametersJSON Schema
NameRequiredDescriptionDefault
tokenYesThe approval token returned in an ``approval_required`` result.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.7/5.0
Behavior5/5

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

No annotations are provided, so the description carries full burden. It discloses key behaviors: token is single-use, expires, must match exact operation. No contradictions.

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 concise (three sentences) and front-loaded with the core purpose. Every sentence provides essential information without redundancy.

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

Completeness5/5

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

Given the simple parameter structure (one required token) and existence of an output schema, the description fully covers preconditions (token must be server-issued, single-use, expires) and usage intent (human approval). No gaps.

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 coverage is 100%, so baseline is 3. The schema already describes the 'token' parameter well. The description does not add additional semantic detail beyond what is in the schema.

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 ('Approve and execute a pending ask operation') and specifies that this is the only way such an operation runs. It distinguishes itself from sibling tools by its unique approval function.

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

Usage Guidelines5/5

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

Explicitly states when to use (only for pending ask operations) and when not to (not for autonomous LLM use, intended for human approval). Also mentions token constraints (must be server-issued, single-use, expires).

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

delete_fileA

Delete a file from the data directory. (Risk: HIGH)

Destructive; requires explicit human approval.

ParametersJSON Schema
NameRequiredDescriptionDefault
filepathYesPath relative to the sandboxed data directory.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.2/5.0
Behavior4/5

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

Given no annotations, the description sufficiently discloses the destructive nature and approval requirement, though it could mention side effects like irreversibility.

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?

Extremely concise: two sentences, front-loaded with the core action, and no redundant or ambiguous words.

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

Completeness4/5

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

For a simple tool with one parameter and an output schema, the description covers the essential behavioral traits and safety concerns, though it could mention error handling or response details.

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?

With 100% schema coverage, the description reinforces the parameter meaning (path relative to sandboxed directory) but adds limited new semantic information beyond the schema.

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 ('Delete a file') and the target ('data directory'), distinguishing it from sibling tools like read_file, write_file, and execute_command.

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

Usage Guidelines4/5

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

The description explicitly flags the tool as destructive and requiring human approval, but does not detail specific conditions or prerequisites beyond that warning.

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

execute_commandA

Execute a system command (SIMULATED). (Risk: CRITICAL)

Denied by default. Never runs a real subprocess.

ParametersJSON Schema
NameRequiredDescriptionDefault
commandYesThe command to (simulate) executing.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior5/5

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

No annotations are provided, so the description carries full burden. It fully discloses that the tool is simulated, poses critical risk, and never executes a real subprocess, providing all necessary behavioral context.

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 extremely concise with three sentences, no wasted words, and all critical information front-loaded: simulation, risk, and behavior.

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

Completeness4/5

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

Given that output schema exists, the description need not detail return values. It covers purpose, risk, and behavior adequately for a simulated command tool. Could mention output format, but not required.

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

Parameters4/5

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

Schema description coverage is 100%, but the tool description adds value by reinforcing that the command is simulated and never actually executed, which goes beyond the schema's description of 'The command to (simulate) executing.'

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 'Execute a system command (SIMULATED)', which specifies the verb and resource, and distinguishes it from sibling tools like read_file and write_file by explicitly noting it's a simulation.

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

Usage Guidelines4/5

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

The description provides clear context by stating 'Denied by default. Never runs a real subprocess,' which tells the agent this tool is for simulation only. However, it does not explicitly state when to use it or provide alternatives, but the context is sufficient for basic guidance.

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

read_fileA

Read a UTF-8 text file from the data directory. (Risk: LOW)

ParametersJSON Schema
NameRequiredDescriptionDefault
filepathYesPath relative to the sandboxed data directory.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior2/5

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

No annotations provided; description only mentions 'Risk: LOW' but lacks details on error handling, permissions, or what happens if file doesn't exist. Carries full burden but insufficient.

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?

Two concise sentences with no wasted words. Front-loaded with essential information.

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

Completeness4/5

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

Tool is simple with one parameter and an output schema. Description covers file type, location, and risk level. Could mention error behavior but not essential given output schema.

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 coverage is 100% with description for filepath. Description adds no additional meaning beyond schema, resulting in baseline score.

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?

Clearly states verb 'read', resource 'UTF-8 text file', and scope 'from the data directory'. Distinguishes from sibling tools like write_file and delete_file.

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?

Implies usage for reading files but provides no explicit guidance on when to use this tool vs alternatives, no when-not or exclusions.

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

write_fileA

Write content to a file in the data directory. (Risk: MEDIUM)

Modifies data; requires human approval unless policy allows it.

ParametersJSON Schema
NameRequiredDescriptionDefault
contentYesUTF-8 text to write.
filepathYesPath relative to the sandboxed data directory.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.2/5.0
Behavior4/5

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

The description discloses that the tool modifies data and requires human approval, which is critical behavioral info. With no annotations, it carries the full burden and does so adequately.

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?

Two concise sentences: first defines purpose, second adds risk and policy context. No wasted words.

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

Completeness4/5

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

Given the low complexity (2 params) and presence of output schema, the description covers purpose, risk, and behavioral constraints adequately. Minor omission: does not mention if file overwrite is default or behavior on existing file.

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 coverage is 100%, so the description adds no additional meaning beyond what the schema already provides. Baseline score of 3 is appropriate.

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 ('Write content to a file') and the target ('data directory'), which is specific and distinguishes it from siblings like read_file or delete_file.

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

Usage Guidelines4/5

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

It mentions the risk level and approval requirement, guiding when to use cautiously. However, it does not explicitly state when not to use or provide alternatives.

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. 5 tool updatesv1.0.0
    • First observedapprove_operation
    • First observeddelete_file
    • First observedexecute_command
    • First observedread_file
    • First observedwrite_file

TDQS

A4.2/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: read, write, delete files; execute commands; and approve operations. No overlap or ambiguity between them.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern, e.g., read_file, delete_file, approve_operation. This makes the tool surface predictable and easy to navigate.

Tool Count5/5

With 5 tools, the server is well-scoped for its purpose of providing permission-aware file and command operations. Each tool earns its place without unnecessary complexity.

Completeness4/5

Core file operations (read, write, delete) and command execution are covered. Minor gaps include the lack of a list/directory tool and no way to view pending approvals, but the essential workflow is complete.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    Enables human-approved SSH terminal sessions and confined SFTP file operations for SSH-configured devices, with user-controlled terminal and file explorer.
    AGPL 3.0
  • F
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to safely read and write files in a sandboxed workspace via natural language, with on-demand connection, CVE-hardened path confinement, injection resistance, and full audit logging.
    -
  • F
    license
    A
    quality
    A
    maintenance
    Enables coding agents to perform workspace-confined file operations, read-only Git inspection, and structured shell commands, while requiring out-of-band human approval for mutations and external executions and maintaining an audit trail.
    14
    3
    -