r/MCPservers • • 6h ago

How to guard MCP tool calls with deterministic PreToolUse hooks (Python pattern + pitfalls)

1 Upvotes

When connecting coding agents to external MCP servers, most setups rely on prompt instructions or coarse-grained server-level allowlists. The gap is that an agent can still invoke an approved MCP tool with dangerous arguments (e.g., querying prod tables with unparameterized SQL, reading `.env` / SSH keys via a filesystem MCP server, or exfiltrating secrets through a fetch/HTTP MCP tool).

A clean defense-in-depth pattern is adding a deterministic `PreToolUse` hook on the agent client side that inspects every `mcp__<server>__<tool>` invocation *before* the JSON-RPC `tools/call` request ever leaves the host.

1. Why `PreToolUse` instead of prompt rules alone?

  • **Deterministic:** Runs as an out-of-band subprocess before execution; prompt injection inside a repo or issue body cannot override it.
  • **Argument-level inspection:** Unlike static allow/deny lists per tool name, you can inspect `tool_input` fields (SQL strings, file paths, target hosts, flags).
  • **Fast fail with feedback:** Returning exit code `2` (or a structured JSON `permissionDecision: "deny"` with a reason) blocks the call and feeds the exact policy reason back to the model so it can self-correct.

2. Minimal Python `PreToolUse` guard for MCP tools

```python import json import re import sys

SENSITIVE_PATH_RE = re.compile( r"(^|/)(?:\.env(?:\..*)?|id_rsa|id_ed25519|\.aws/credentials|\.npmrc)$", re.IGNORECASE, ) DANGEROUS_SQL_RE = re.compile( r"\b(DROP|TRUNCATE|ALTER|DELETE\s+FROM|GRANT)\b", re.IGNORECASE, )

def main() -> int: payload = json.load(sys.stdin) tool_name = payload.get("tool_name", "") tool_input = payload.get("tool_input") or {}

# Only inspect MCP tool calls (e.g. mcp__postgres__query, mcp__fs__read_file)
if not tool_name.startswith("mcp__"):
    return 0

parts = tool_name.split("__", 2)
server = parts\[1\] if len(parts) > 1 else ""
action = parts\[2\] if len(parts) > 2 else ""

# 1. Block filesystem MCP reads/writes on credential files
for key in ("path", "file_path", "target", "uri"):
    val = str(tool_input.get(key, ""))
    if val and SENSITIVE_PATH_RE.search(val.replace("\\\\", "/")):
        print(f"Blocked MCP call {tool_name}: access to sensitive path '{val}' is denied.", file=sys.stderr)
        return 2

# 2. Enforce read-only guardrails on database MCP servers
if server in {"postgres", "sqlite", "mysql"} or "query" in action:
    sql = str(tool_input.get("sql") or tool_input.get("query") or "")
    if DANGEROUS_SQL_RE.search(sql):
        print(f"Blocked MCP call {tool_name}: mutating SQL statement requires manual approval.", file=sys.stderr)
        return 2

return 0

if __name__ == "__main__": raise SystemExit(main()) ```

3. Three subtle pitfalls when writing MCP `PreToolUse` hooks

  1. **Path normalization & traversal:** Always resolve symlinks / `..` segments (or normalize Windows backslashes) before matching paths—otherwise `./configs/../.env` slips past naive substring checks.
  2. **Argument schema variance across MCP servers:** One filesystem MCP server uses `path`, another uses `file_path` or `paths: [...]` (list). Flatten nested dicts/lists in `tool_input` if you want universal secret-path protection.
  3. **Fail-closed on malformed JSON:** If your hook throws an unhandled exception on unexpected `tool_input` types, some clients treat non-zero exit codes other than `2` as "hook error, continue anyway." Catch `Exception` and explicitly deny/log if strict enforcement is required.

Curious how others here are handling argument-level policies for MCP servers—are you validating inside the MCP server itself, via client `PreToolUse` hooks, or through an MCP proxy?


r/MCPservers • • 9h ago

Why does my read only AI agent need OAuth write permissions?

1 Upvotes

A team here is building an agent that reads tickets and summarizes them. Nothing fancy, and it's not supposed to change anything.

Then I looked at the OAuth consent screen. The connector wants permission to edit tickets too, even though the agent doesn't need it.

Google's OAuth guidance says to request only the permissions you actually need, which is exactly what we're trying to do. We could build a narrower integration or use something like newcore to restrict what the agent can do at the tool level. But the connector would still have broader permissions than we'd like.

How are you dealing with AI agents that need read-only access when the available OAuth scopes are too broad?


r/MCPservers • • 12h ago

I built an MCP server that lets Claude drive an iPhone (and Android) — in the terminal

1 Upvotes

I wanted my agents to be able to test on a phone the way they use a shell, so I built TermPhone: the iOS Simulator / Android emulator streamed live into the terminal, plus a built-in MCP server (stdio, `termphone mcp`) with 20 tools.

What the agent gets:

  • `termphone_observe` — accessibility tree + a screenshot with a freshness stamp
  • tap (by label or coordinates), swipe, type, home/button, unlock
  • launch / install / terminate apps
  • `termphone_record_video`, `termphone_run_script` (record & replay flows), `termphone_wait_for`

The piece I'm most happy with is the stale-screen guard: observe returns a screen stamp, and every act tool refuses to run if the screen changed since that observe. No more tapping on a frame from 3 seconds ago.

Under the hood: simctl + Meta's idb for iOS, adb + the device's own H.264 encoder → ffmpeg for Android (~30 fps while the screen moves). iPhone needs a Mac; Android also works on Windows.

It's a paid tool ($39 one-time, free tier for one device) — termphone.com. Also live on Product Hunt today if you want the screenshots tour.

Happy to answer anything about the streaming or the agent loop. What would you automate first if your agent could drive a phone?


r/MCPservers • • 16h ago

sec edgar mcp server (hosted, oauth): full text of every filing, form 4, 13f, 8-k items, xbrl, filter by market cap and sector

1 Upvotes

disclosure: we built it (quantisnow). 44s demo with voice: https://youtu.be/S2trZ7_MVCU

url: https://www.quantisnow.com/api/v1/mcp

no install, it signs in through your client's oauth flow. three tools:

  • full_text_search: words and "quoted phrases" inside filings and exhibits, with form, ticker, date and 8-k item filters, plus proximity ("chief executive resigned"~10)
  • search: lucene-style queries over insider trades, 8-k events, 13d/13g, 13f holdings, xbrl financials and house members' trades. most datasets filter by the company's market cap and sector, e.g. issuer.marketCap:<300000000 AND issuer.sector:"Health Care"
  • describe_dataset: fields and example queries, free

every result links to its filing page. there's also npx quantisnow mcp install cursor (or claude-desktop, vscode, windsurf, codex, gemini) to write the config for you.

repo: https://github.com/quantisnow/sec-edgar-mcp