{"slug": "6-lessons-from-building-safe-mcp-servers-for-claude", "title": "6 lessons from building safe MCP servers for Claude", "summary": "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.", "body_md": "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.\n\nAll examples use the official Python SDK 2.x.\n\n``` python\nfrom mcp.server.mcpserver import MCPServer\n\nmcp = MCPServer(\"crm-demo\")\n\n@mcp.tool()\ndef find_customer(query: str) -> list[dict]:\n    \"\"\"Search customers by part of their name or email address.\"\"\"\n    ...\n\nif __name__ == \"__main__\":\n    mcp.run()\n```\n\nNote: in SDK 2.x, `FastMCP` became `MCPServer` in `mcp.server.mcpserver`. Type hints and the docstring become the tool schema Claude sees.\n\nDon't just check permissions *inside* a write tool. Don't register it at all unless the user opted in:\n\n```\nALLOW_WRITES = os.environ.get(\"ALLOW_WRITES\", \"false\").lower() == \"true\"\n\nif ALLOW_WRITES:\n    @mcp.tool()\n    def execute(sql: str) -> dict:\n        \"\"\"Run one INSERT, UPDATE or DELETE. DROP/ALTER/TRUNCATE are blocked.\"\"\"\n        return db.execute(sql)\n```\n\nThen 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.\n\nFor a REST API bridge, list the endpoints Claude may call in a config file and reject everything else:\n\n```\nendpoints:\n  - name: get_post\n    method: GET\n    path: /posts/{id}\n  - name: create_post\n    method: POST\n    path: /posts\n    body_params: [title, body]\n    confirm: true   # tell the model to ask the user first\n```\n\nTwo 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.\n\nThe same idea applies to files: resolve every path and check it's still inside the root folder, and skip symlinks that point outside.\n\nFor CSV/Excel analysis it's tempting to accept a pandas query string. Don't. Accept structured filters and validate them:\n\n``` python\nOPS = {\"==\", \"!=\", \">\", \">=\", \"<\", \"<=\", \"contains\", \"in\"}\n\ndef filter_rows(name: str, filters: list[dict]) -> dict:\n    \"\"\"Each filter is {\"column\", \"op\", \"value\"}.\"\"\"\n    for f in filters:\n        if f[\"op\"] not in OPS:\n            raise ValueError(f\"Unknown op '{f['op']}'. Use one of {sorted(OPS)}.\")\n```\n\nClaude handles structured parameters very well, and you never execute code it wrote.\n\nThe model reads your error messages. Make them actionable:\n\n```\nraise ValueError(f\"Unknown column '{col}'. Columns are: {', '.join(df.columns)}\")\n```\n\nWith 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.\n\n`./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`.\nA complete, free example (CRM server with search, orders and invoices, tests and Docker):\n\n[https://github.com/longdang2072/mcp-crm-demo](https://github.com/longdang2072/mcp-crm-demo)\n\nIf 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](https://longdang3.gumroad.com/l/mcp-server-templates).\n\nWhat integration would you connect Claude to first? Happy to answer questions in the comments.", "url": "https://wpnews.pro/news/6-lessons-from-building-safe-mcp-servers-for-claude", "canonical_source": "https://dev.to/longdang2072/6-lessons-from-building-safe-mcp-servers-for-claude-162f", "published_at": "2026-11-26 01:03:53+00:00", "updated_at": "2026-11-26 01:18:00.447674+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "ai-tools", "ai-safety", "developer-tools"], "entities": ["Claude", "Model Context Protocol", "Anthropic", "Notion", "Google Sheets", "GitHub", "PostgreSQL", "SQLite"], "also_reported_by": [], "takeaway": "Register write tools only when an ALLOW_WRITES flag is set and back it with a read-only database mode, so a WITH ... DELETE that slips past keyword checks is still refused at the data source.", "recommendation": {"advice": "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.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/6-lessons-from-building-safe-mcp-servers-for-claude", "markdown": "https://wpnews.pro/news/6-lessons-from-building-safe-mcp-servers-for-claude.md", "text": "https://wpnews.pro/news/6-lessons-from-building-safe-mcp-servers-for-claude.txt", "jsonld": "https://wpnews.pro/news/6-lessons-from-building-safe-mcp-servers-for-claude.jsonld"}}