cd /news/ai-agents/6-lessons-from-building-safe-mcp-ser… · home › topics › ai-agents › article
[ARTICLE · art-176454] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

6 lessons from building safe MCP servers for Claude

A developer published a set of six lessons for building safe MCP servers that connect Claude to SQL databases, REST APIs, Notion, Google Sheets and local files, using the official Python SDK 2.x. The guidance covers conditional tool registration gated on an ALLOW_WRITES flag, read-only database modes as a second layer of defense, endpoint allowlists with URL-encoded path values, structured filter validation instead of raw pandas queries, actionable error messages the model can recover from, and anchoring working directories at startup. A free CRM example server with tests and Docker is on GitHub, alongside a paid set of six server templates.

recommendation

Gate write tools behind an opt-in flag and enforce read-only modes at the database, then allowlist REST endpoints, URL-encode path values and reject unknown parameters.

more in playbook: Securing agents and AI tools
by read2 min views11 publishedNov 26, 2026

Connecting Claude to a database or an internal API through MCP (Model Context Protocol) takes about 20 lines of Python. Making it safe to leave connected takes a bit more thought. Here are six lessons from building MCP servers for SQL databases, REST APIs, Notion, Google Sheets, local documents and spreadsheets.

All examples use the official Python SDK 2.x.

from mcp.server.mcpserver import MCPServer

mcp = MCPServer("crm-demo")

@mcp.tool()
def find_customer(query: str) -> list[dict]:
    """Search customers by part of their name or email address."""
    ...

if __name__ == "__main__":
    mcp.run()

Note: in SDK 2.x, FastMCP became MCPServer in mcp.server.mcpserver. Type hints and the docstring become the tool schema Claude sees.

Don't just check permissions inside a write tool. Don't register it at all unless the user opted in:

ALLOW_WRITES = os.environ.get("ALLOW_WRITES", "false").lower() == "true"

if ALLOW_WRITES:
    @mcp.tool()
    def execute(sql: str) -> dict:
        """Run one INSERT, UPDATE or DELETE. DROP/ALTER/TRUNCATE are blocked."""
        return db.execute(sql)

Then add a second layer at the data source: open SQLite with mode=ro and set PostgreSQL sessions to read-only. If the model sneaks a WITH ... DELETE past your keyword check, the database still refuses.

For a REST API bridge, list the endpoints Claude may call in a config file and reject everything else:

endpoints:
  - name: get_post
    method: GET
    path: /posts/{id}
  - name: create_post
    method: POST
    path: /posts
    body_params: [title, body]
    confirm: true   # tell the model to ask the user first

Two details that matter: URL-encode path values (so id = "7/../admin" can't reach another route) and reject unknown parameters instead of silently passing them through.

The same idea applies to files: resolve every path and check it's still inside the root folder, and skip symlinks that point outside.

For CSV/Excel analysis it's tempting to accept a pandas query string. Don't. Accept structured filters and validate them:

OPS = {"==", "!=", ">", ">=", "<", "<=", "contains", "in"}

def filter_rows(name: str, filters: list[dict]) -> dict:
    """Each filter is {"column", "op", "value"}."""
    for f in filters:
        if f["op"] not in OPS:
            raise ValueError(f"Unknown op '{f['op']}'. Use one of {sorted(OPS)}.")

Claude handles structured parameters very well, and you never execute code it wrote.

The model reads your error messages. Make them actionable:

raise ValueError(f"Unknown column '{col}'. Columns are: {', '.join(df.columns)}")

With a message like this, Claude fixes its own call on the next try instead of giving up. For APIs, add the likely fix: a Notion 404 usually means "share the page with your integration", so say that.

./data and .env silently fail. Call os.chdir(Path(__file__).resolve().parent) at startup.find_customer), plus a cheap "start here" tool like list_tables. A complete, free example (CRM server with search, orders and invoices, tests and Docker):

https://github.com/longdang2072/mcp-crm-demo

If you'd rather skip the boilerplate, I packaged six servers built on these patterns (SQL, REST API, Notion, Google Sheets, local docs, CSV/Excel) plus a blank template: MCP Server Templates for Claude.

What integration would you connect Claude to first? Happy to answer questions in the comments.

── more in #ai-agents 4 stories · sorted by recency
── more on @claude 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/6-lessons-from-build…] indexed:0 read:2min 2026-11-26 · —