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.