Skip to main content

pymcp-auth-server

Python 3.10+ License: MIT Version: 0.2.0

基于 FastMCP 的 MCP 认证服务器,提供 Token 认证与工具权限控制。认证/权限逻辑与工具业务代码完全解耦。

Author: thirsd | License: MIT | Repo: Gitee

特性

  • Token 认证 — 通过 Bearer Token 鉴别用户身份
  • 权限控制 — 不同用户只能看到和使用被授权的工具
  • 运行时过滤 — 工具列表根据用户权限动态生成
  • 业务解耦 — 工具函数不感知认证,只声明所需权限
  • 多存储后端 — 支持 JSON 文件和 SQLite,可扩展
  • 双传输模式 — SSE(HTTP)和 stdio

快速开始

安装

git clone https://gitee.com/thirsd/pymcp_auth_server.git
cd pymcp_auth_server
uv sync

30 秒示例

1. 编写认证配置 data/auth_config.json

{
  "users": [
    {"username": "admin", "tokens": ["my-admin-token"], "permissions": ["*"]},
    {"username": "guest", "tokens": ["guest-token"], "permissions": ["calculator.add"]}
  ]
}

2. 编写服务器 my_server.py

from mcp_auth_server import AuthMCPServer, JsonAuthStore

store = JsonAuthStore("data/auth_config.json")
server = AuthMCPServer("my-server", store=store)

@server.tool(permission="calculator.add")
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

@server.tool(permission="calculator.multiply")
def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

@server.tool()  # 所有认证用户可用
def echo(message: str) -> str:
    """Echo a message."""
    return message

server.run(transport="sse", port=8000)

3. 启动服务器

uv run python my_server.py

4. 使用 MCP 客户端连接(见下方 Claude Code 配置)。

权限模型

权限采用点分层级命名空间,支持三种匹配方式:

用户权限 说明 示例匹配
* 全部权限 匹配所有工具
calculator.* 前缀通配 匹配 calculator.add, calculator.multiply
calculator.add 精确匹配 仅匹配 calculator.add

工具不声明 permission 时,所有认证用户均可访问。

Claude Code 客户端配置

SSE 传输(推荐)

{
  "mcpServers": {
    "auth-server": {
      "url": "http://localhost:8000/sse",
      "headers": {
        "Authorization": "Bearer my-admin-token"
      }
    }
  }
}

stdio 传输

{
  "mcpServers": {
    "auth-server": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/pymcp_auth_server", "python", "main.py"],
      "env": {
        "MCP_AUTH_TOKEN": "my-admin-token",
        "PYTHONPATH": "/path/to/pymcp_auth_server/src"
      }
    }
  }
}

项目结构

src/mcp_auth_server/
├── __init__.py               # 公共 API
├── __main__.py               # CLI 入口
├── server.py                 # AuthMCPServer 主类
├── examples.py               # 示例工具
├── auth/                     # 认证与权限模块
│   ├── models.py             #   UserInfo 数据模型
│   ├── manager.py            #   AuthManager 认证管理器
│   └── middleware.py         #   FastMCP 权限中间件
└── store/                    # 存储后端模块
    ├── base.py               #   AuthStore 抽象基类
    ├── json_store.py         #   JSON 文件存储
    └── sqlite_store.py       #   SQLite 数据库存储

作为库使用

from mcp_auth_server import AuthMCPServer, JsonAuthStore, SQLiteAuthStore

# JSON 存储
store = JsonAuthStore("auth.json")

# 或 SQLite 存储
store = SQLiteAuthStore("auth.db")

# 管理用户
store.add_user("alice", "alice-token", ["file.read", "file.write"])
store.add_user("bob", "bob-token", ["file.read"])

# 创建服务器
server = AuthMCPServer("my-app", store=store)

@server.tool(permission="file.read")
def read_file(path: str) -> str:
    with open(path) as f:
        return f.read()

@server.tool(permission="file.write")
def write_file(path: str, content: str) -> str:
    with open(path, "w") as f:
        f.write(content)
    return "ok"

server.run(transport="sse", port=8000)

CLI 使用

# 启动服务器
python -m mcp_auth_server serve --config data/auth_example.json --transport sse --port 8000

# 管理用户
python -m mcp_auth_server add-user --config auth.json --username admin --token xxx --permissions "*"
python -m mcp_auth_server list-users --config auth.json
python -m mcp_auth_server remove-user --config auth.json --username admin

# 使用 SQLite 后端
python -m mcp_auth_server serve --config auth.db --store sqlite --transport sse

扩展存储后端

src/mcp_auth_server/store/ 下新建文件,继承 AuthStore

# store/redis_store.py
from .base import AuthStore

class RedisAuthStore(AuthStore):
    def __init__(self, url: str):
        ...

    def get_user_by_token(self, token: str):
        ...
    def add_user(self, username, token, permissions):
        ...
    def remove_user(self, username):
        ...
    def list_users(self):
        ...

store/__init__.py 中导出即可。

运行测试

uv run python tests/test_integration.py

文档

依赖

  • Python >= 3.10
  • fastmcp >= 3.4.0(自带 Starlette / uvicorn)

许可证

MIT License

Copyright (c) 2025 thirsd (thirsd@sina.com)

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pymcp_auth_server-0.2.0.tar.gz (103.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pymcp_auth_server-0.2.0-py3-none-any.whl (14.6 kB view details)

Uploaded Python 3

File details

Details for the file pymcp_auth_server-0.2.0.tar.gz.

File metadata

  • Download URL: pymcp_auth_server-0.2.0.tar.gz
  • Upload date:
  • Size: 103.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.2

File hashes

Hashes for pymcp_auth_server-0.2.0.tar.gz
Algorithm Hash digest
SHA256 eafb7a767f54a87f290028cf2454577b2170e60b1bc8e2681698aa2c0f838dd7
MD5 36341c37ebdfb01ed0729d85d86437f8
BLAKE2b-256 8ac550652782fe486d70377ce13a903311affca1c04412d15a430ed7876ca32d

See more details on using hashes here.

File details

Details for the file pymcp_auth_server-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pymcp_auth_server-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 21fb222ee58c098f84a8259cdd82d66cad6c2e8a70d9d0c8894fcc2adc833178
MD5 08f789e997c8221e4659c4374e5eb035
BLAKE2b-256 c362951eb4514c022a7e8fc405495f8b9009ec9ccdde090c7e360fc6609b5b67

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 files

0.1.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page