Security

Why Security Matters in MCP Servers

December 5, 20253 min readBy Nikhil Tiwari

MCP servers let AI agents access tools like file systems, APIs, databases, and automation workflows. That also means an insecure MCP server can expose your entire system — often without you realizing until it's too late.

Because AI agents act automatically, a small misconfiguration can lead to:

  • Unintended file access
  • Data leaks
  • Harmful actions (delete/update)
  • Unauthorized users calling your tools

If you're hosting a remote MCP server, it's effectively a public API — security is non-negotiable.

What Exactly Is an MCP Server?

An MCP server is basically a gateway that exposes tools, data, or operations an AI can use.

  • A local MCP server runs on your machine
  • A remote MCP server is hosted somewhere on the internet

In simple terms: your MCP server gives your AI superpowers. But if not secured properly, it might give those superpowers to the wrong people too.

Why Security Matters So Much

1️⃣ MCP Servers Can Access Sensitive Data

MCP servers often expose:

  • File system access
  • Database queries
  • Internal APIs
  • User secrets
  • Business workflows

If a malicious actor gets into your MCP server, they can misuse everything your AI has access to. Think of an MCP server as a toolbox — you must lock the toolbox when you're not around.

2️⃣ AI Agents Act Automatically — Mistakes Spread Fast

Unlike humans, AI agents don't hesitate. If your MCP server is misconfigured, an AI agent might:

  • Delete files
  • Overwrite records
  • Run unintended automation
  • Leak private data to the wrong place

AI works at machine speed, so a small mistake can become a big disaster quickly.

3️⃣ Remote MCP Servers Are Basically Public APIs

Hosting your MCP server online means:

  • Anyone can find it
  • Anyone can attempt to call it
  • Bots will try brute forcing it
  • Attackers will probe for open endpoints

If you don't enforce authentication, you might unintentionally expose your internal operations to the world.

The Essentials You Must Implement

1. Authentication

Never expose a remote MCP server without verifying the client. Use API keys, OAuth, or signed tokens.

2. Authorization

Even authenticated clients should only get access to allowed tools. Least-privilege is the rule.

3. Input Validation

Check paths, queries, user inputs — avoid command injection or misuse.

4. Rate Limits & Logging

Protect against floods, loops, and track suspicious activity.

Secure Node.js MCP Server Example

Here's a minimal example showing API key authentication + restricted tool access:

import { Server } from "@modelcontextprotocol/sdk/server";
import express from "express";
import { readFile } from "fs/promises";
import { join } from "path";

const app = express();
app.use(express.json());

const API_KEY = process.env.MCP_API_KEY;
const SAFE_DIR = process.env.SAFE_DIR || "./safe";

// Middleware for authentication
app.use((req, res, next) => {
  const key = req.headers["x-api-key"];
  if (key !== API_KEY) {
    return res.status(401).json({ 
      error: "Unauthorized MCP client" 
    });
  }
  next();
});

const mcpServer = new Server({
  name: "secure-mcp-server",
  version: "1.0.0",
});

// Expose a safe tool (read-only, restricted path)
mcpServer.tool("readFileSafe", {
  description: "Reads a file but only from the safe folder",
  input: {
    type: "object",
    properties: { 
      filename: { 
        type: "string",
        description: "Filename relative to safe directory"
      } 
    },
    required: ["filename"],
  },
  async handler({ filename }) {
    // Input validation: prevent path traversal
    if (filename.includes("..") || filename.includes("/")) {
      throw new Error("Invalid filename. Path traversal not allowed.");
    }

    // Restrict to safe directory only
    const safePath = join(SAFE_DIR, filename);
    
    // Additional check: ensure path is within safe directory
    if (!safePath.startsWith(join(process.cwd(), SAFE_DIR))) {
      throw new Error("Access denied. Only files in safe directory allowed.");
    }

    try {
      const content = await readFile(safePath, "utf-8");
      return {
        content: [{ type: "text", text: content }],
      };
    } catch (error) {
      throw new Error(`File not found: ${filename}`);
    }
  },
});

app.post("/mcp", (req, res) => mcpServer.handle(req, res));

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`Secure MCP server running on port ${PORT}`);
});

Common Security Mistakes to Avoid

  • ❌ Exposing internal tools (like full filesystem access) to remote clients
  • ❌ No authentication on production servers
  • ❌ AI agents allowed to delete or modify critical data
  • ❌ Logging sensitive data directly (PII, tokens, file contents)
  • ❌ Hosting MCP on HTTP instead of HTTPS
  • ❌ Forgetting to sandbox risky tools

Best Practices

Area Best Practice
Server Hosting Always use HTTPS, secure hosting, firewalls
Tool Access Expose only what's absolutely required
Secrets Never hardcode — use environment variables or KMS
AI Agent Safety Sandbox risky tool calls
Deployment Follow least-privilege principle
Error Handling Do not leak server internals in responses

Final Thoughts

MCP is powerful because it lets AI interact with the real world — your files, your systems, your workflows. But that power also makes it risky if not handled carefully.

A secure MCP server:

  • Protects your users
  • Protects your data
  • Protects your business
  • Prevents accidental AI disasters

If you're planning to build with MCP (local or remote), start with this mindset:

"Connectivity is optional. Security is not."

Want to test your MCP server security? Test Remote MCP Server →

NT

Nikhil Tiwari

15+ years of experience in product development, AI enthusiast, and passionate about building innovative solutions that bridge the gap between technology and real-world applications. Specializes in creating developer tools and platforms that make complex technologies accessible to everyone.

MCP Playground - Test MCP Server Online | Test MCP Client