How to write a secure MCP tool
An MCP tool is a function you hand to a language model that can be steered by whatever the model reads. So the usual "trust the caller" assumptions do not hold. A safe tool treats every input as hostile, makes its side effects explicit, and stays cheap to load. Here is how.
1. Validate every input with a schema
Define the input with a typed schema (zod, pydantic, whatever your SDK uses) and bound it. A string parameter should have a max length. An enum should be an enum, not a free string. This stops both accidental garbage and deliberate injection from reaching your logic.
server.registerTool("echo",
{ inputSchema: { text: z.string().min(1).max(1000) } },
async ({ text }) => ({ content: [{ type: "text", text }] }));
2. If it fetches a URL, fetch it safely
The single most dangerous tool is one that fetches a user-supplied URL, because it can be turned into a proxy into your network and the cloud metadata endpoint. Use an SSRF guard: https only, block private and loopback IPs and metadata hostnames, re-resolve the host to defeat DNS rebinding, do not follow redirects, and cap size and time. Never call a raw fetch on a tool input.
3. Make side effects explicit and reversible
If a tool writes, deletes, or sends, say so in the description, and prefer designs where a destructive action needs an explicit confirmation argument. The model should not be able to delete a database because a web page told it to. Scope what each tool can touch to the minimum it needs.
4. Keep it token-lean
Every tool you expose loads its schema into every request. Fewer, sharper tools cost less context and help the model pick the right one. Keep names and descriptions tight. Ten focused tools beat thirty fuzzy ones.
5. Authenticate and rate-limit at the server
Individual tools should assume the request already passed auth and a rate limit at the server layer. Build those once at the edge so every tool inherits them, rather than scattering checks across handlers.
Skip the boilerplate
MCP Forge Kit gives you all of this as a working base: validated example tools, an SSRF-safe fetch utility, auth and rate limiting at the edge, tests, and CI. Build your tools on top instead of from scratch.
Get MCP Forge Kit, €39Related: SSRF protection · Authentication · Security checklist