Defensive MCP Server Coding: Stopping ReDoS, Indirect Prompt Injection & SSRF
A practical security checklist for Go, TypeScript, and Python MCP authors building custom tools over untrusted web and repository inputs.
Executive Architecture Summary (TL;DR)
Every MCP tool that fetches URLs, parses user regexes, or reads external GitHub issues processes untrusted input. Hardening requires linear-time regex engines (Go regexp RE2), custom net.Dialer CIDR blocks against SSRF, and clear XML/JSON untrusted-data framing.
When an MCP server fetches a third-party issue or webpage, malicious hidden text inside that document can attempt indirect prompt injection—instructing the host LLM to invoke sibling tools or exfiltrate workspace files.
1. Linear-Time Regular Expressions (Zero Catastrophic Backtracking)
Backtracking regex engines in Node/Python can freeze an STDIO server on crafted inputs. Test patterns inside SyndiPath's Live Regex Debugger and prefer Go's guaranteed O(n) RE2 engine for server-side log and secret scanning.
2. Socket-Level SSRF Verification
Verify resolved IP addresses inside net.Dialer.Control rather than pre-validating hostnames to defeat DNS-rebinding attacks—complementing defensive AI engineering research on NeuroBulletin and MDN Web Security references.
Production Benchmark & Trade-off Matrix
| Engineering Dimension | Naive Setup | Hardened Production Pattern | Impact |
|---|---|---|---|
| Regex Engine Complexity | Exponential PCRE backtracking | Guaranteed O(n) RE2 / bounded input | Immune to ReDoS hangs |
| Outbound HTTP SSRF Check | Naive URL string prefix check | Post-DNS socket IP CIDR blocklist | Defeats DNS rebinding |
| Untrusted Output Wrapping | Raw concatenated prose | Structured data boundaries + read-only scope | Contains prompt injection |
Frequently Asked Technical Questions
Why does URL hostname checking fail against DNS rebinding?
An attacker domain can resolve to a public IP during validation and flip to 127.0.0.1 or 169.254.169.254 with a 0-second TTL during the actual HTTP socket connect.
Should MCP tools execute shell strings via sh -c?
Never pass LLM-controlled strings to sh -c or cmd /c; always pass argument arrays directly to execve / exec.Command without shell interpolation.