跳到正文
DEV Community· longdang2072·· 52 分鐘前AI 評分64

構建安全 Claude MCP 伺服器的 6 項經驗

6 lessons from building safe MCP servers for Claude

AI 導讀

作者分享構建安全 Claude MCP 伺服器的 6 項經驗,涵蓋 SQL、REST API、Notion、Google Sheets、本機文件及 CSV/Excel。

正文

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.

1. Start from a minimal server

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.

2. Read-only by default, writes behind a switch

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.

3. Allowlists, not blocklists

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.

4. Never eval model input

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.

5. Errors are instructions

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.

6. Small things that break in real use

  • Working directory: Claude Desktop starts servers from another folder, so ./data and .env silently fail. Call os.chdir(Path(__file__).resolve().parent) at startup.
  • Never print to stdout in a stdio server. It corrupts the protocol; log to stderr.
  • Cap results (200 to 500 rows) so one query doesn't flood the conversation.
  • Few, well-named tools. 3 to 8 per server, named after tasks (find_customer), plus a cheap "start here" tool like list_tables.
  • Test offline. Keep logic in a plain module and inject the HTTP transport, so tests pass a fake one. Then smoke-test the real server over stdio, exactly like Claude launches it.

Try it

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.

來源:DEV Community · dev.to