MCP Servers Explained & Built

2026-11-30来源 dev.toEnglish

MCP Servers Explained & Built – A Practical Guide

TL;DR

MCP (Model Context Protocol) servers let AI models call real‑world tools via a simple JSON‑based API. They’re easy to build with frameworks like fast‑mcp, but to run them in production you must add OAuth 2.1 with PKCE for authentication, scopes for fine‑grained permissions, and dynamic client registration. This post walks through the theory, shows a minimal Python example, and explains how to secure it for real‑world use.

1. What Is an MCP Server?

Term Meaning
MCP Model Context Protocol – a standard that lets an AI model discover and invoke tools.
Tool A function exposed by the server, defined by a name, description, and JSON‑serialisable parameters.
Client The AI application (Claude, Cursor, ChatGPT, VS Code, etc.) that talks to the server.
Server Your code that implements the tools and speaks the MCP protocol.

Key point: The model never executes a tool; it only requests it. Your server runs the function and returns the result.

1.1 Why MCP Matters

Before MCP, every AI platform had to write its own plumbing for tool‑calling. A GitHub integration for Claude didn’t work in Cursor, and vice‑versa. MCP standardises the request/response format so any MCP‑compatible client can use any MCP‑compatible server—think of it as the “USB‑C for AI tools.”

2. How MCP Works

2.1 The Conversation Flow

  1. Client starts → asks server for the list of available tools.
  2. Server replies → JSON array of tool definitions (name, description, parameters).
  3. Model decides → outputs a request to call a tool.
  4. Client forwards → the request to the server.
  5. Server runs → the function, returns the result.
  6. Client sends → the result back to the model.
  7. Model continues → may call more tools or finish.

All communication is JSON‑encoded, making it language‑agnostic.

2.2 Local vs. Remote Servers

Mode How it runs When to use
Local Server launched as a subprocess (e.g., python server.py) and communicates via stdin/stdout. Quick prototyping, personal use.
Remote Server exposes an HTTP endpoint (e.g., https://my‑tool‑server.com). Production, multi‑device access, third‑party clients.

Remote servers introduce access control: anyone with the URL could call your tools unless you secure them.

3. Building a Minimal MCP Server in Python

3.1 Prerequisites

# Create a virtual environment (optional but recommended) python -m venv venv source venv/bin/activate # Install fast-mcp pip install fast-mcp 

3.2 Example: Notes Tool

# server.py from fast_mcp import MCPServer, tool import psycopg2 # --- Database helper (simplified) --------------------------------- def get_conn(): return psycopg2.connect( dbname="notes", user="postgres", password="secret", host="localhost", port=5432 ) # --- Tools --------------------------------------------------------- @tool def create_note(title: str, content: str) -> dict: """Create a new note in the database.""" conn = get_conn() cur = conn.cursor() cur.execute( "INSERT INTO notes (title, content) VALUES (%s, %s) RETURNING id", (title, content) ) note_id = cur.fetchone()[0] conn.commit() cur.close() conn.close() return {"id": note_id, "title": title, "content": content} @tool def list_notes() -> list: """Return all notes.""" conn = get_conn() cur = conn.cursor() cur.execute("SELECT id, title, content FROM notes") rows = cur.fetchall() cur.close() conn.close() return [{"id": r[0], "title": r[1], "content": r[2]} for r in rows] 

3.3 Running the Server

# For a local MCP server python -m fast_mcp.server server.py 

Now any MCP‑compatible client on the same machine can discover create_note and list_notes.

Notice: This server has no authentication. Anyone who can reach it can call your tools.

4. Securing Your MCP Server

4.1 Why Authentication Matters

  • Open URL → Open API: A public endpoint lets anyone read/write data.
  • Static API keys: Many public MCP servers use a single long‑lived key—if compromised, all clients lose control.
  • User attribution: You need to know who is calling which tool.

4.2 The Recommended Solution: OAuth 2.1 with PKCE

Feature What it does
OAuth 2.1 Standard token‑based auth.
PKCE Proof‑Key for Code Exchange; protects against interception.
Scopes Fine‑grained permissions (e.g., notes.read, notes.write).
Dynamic Client Registration Clients register automatically with the auth server.

4.2.1 Flow Overview

  1. Client → requests a token from the authorization server (e.g., Google, Auth0).
  2. User → authenticates, consents to scopes.
  3. Auth server → issues an access token (JWT).
  4. Client → attaches token to every MCP request.
  5. Server → validates the token, checks scopes, runs the tool.

If the token is missing or invalid, the server returns 401 Unauthorized.

4.3 Implementing OAuth in Your MCP Server

You can either:

  • Build it yourself (login page, token issuance, refresh logic) – complex and error‑prone.
  • Use an existing provider (Auth0, Keycloak, Supabase Auth, etc.) – plug‑and‑play.

Below is a minimal example using Supabase Auth (free tier, easy to set up).

# server.py (add to the previous example) from fast_mcp import MCPServer, tool from fastapi import Depends, HTTPException, Header import jwt import os # --- Auth helper -------------------------------------------------- def get_current_user(authorization: str = Header(...)): try: token = authorization.split(" ")[1] # Bearer <token> payload = jwt.decode( token, os.getenv("SUPABASE_JWT_SECRET"), algorithms=["HS256"], audience="your-project-id", ) return payload # contains sub (user id), scopes, etc. except Exception: raise HTTPException(status_code=401, detail="Invalid token") # --- Tools with scope checks ------------------------------------ @tool def create_note( title: str, content: str, user: dict = Depends(get_current_user), ) -> dict: """Create a new note (requires notes.write).""" if "notes.write" not in user.get("scopes", []): raise HTTPException(status_code=403, detail="Insufficient scope") # ... same as before ... @tool def list_notes(user: dict = Depends(get_current_user)) -> list: """List all notes (requires notes.read).""" if "notes.read" not in user.get("scopes", []): raise HTTPException(status_code=403, detail="Insufficient scope") # ... same as before ... 

Key points:

  • Depends(get_current_user) pulls the JWT from the Authorization header.
  • The token’s scopes claim is checked before executing the tool.
  • The server never stores any long‑lived secrets; it only verifies tokens.

5. Deploying the Remote MCP Server

  1. Host: Any cloud provider (AWS, GCP, Azure, Fly.io, Render, etc.).
  2. Expose HTTPS: MCP clients expect a secure endpoint.
  3. Set environment variables:
    • SUPABASE_JWT_SECRET (or your provider’s secret).
    • SUPABASE_URL (if needed).
  4. Configure CORS (if your client is a browser).
  5. Run: uvicorn server:app --host 0.0.0.0 --port 8000.

Once live, any MCP client can discover your tools by pointing

原文:https://www.a8q9.cn/en/article/mcp-servers-explained-built-1a842c.html

相关文章