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)

Metadata

Release files for pymcp-auth-server 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pymcp-auth-server 0.2.0
File Size Uploaded Provenance Actions
pymcp_auth_server-0.2.0.tar.gz 103.2 kB Without provenance Details for pymcp_auth_server-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pymcp-auth-server 0.2.0
File Interpreter ABI Platform Actions
pymcp_auth_server-0.2.0-py3-none-any.whl Python 3 none any Details for pymcp_auth_server-0.2.0-py3-none-any.whl

Total release size: 117.8 kB

Release files / pymcp_auth_server-0.2.0.tar.gz

Download URL pymcp_auth_server-0.2.0.tar.gz
Size 103.2 kB
Tags Source
SHA-256 checksum
How to use checksums
eafb7a767f54a87f290028cf2454577b2170e60b1bc8e2681698aa2c0f838dd7
BLAKE2b-256 checksum
How to use checksums
8ac550652782fe486d70377ce13a903311affca1c04412d15a430ed7876ca32d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.2

Release files / pymcp_auth_server-0.2.0-py3-none-any.whl

Download URL pymcp_auth_server-0.2.0-py3-none-any.whl
Size 14.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
21fb222ee58c098f84a8259cdd82d66cad6c2e8a70d9d0c8894fcc2adc833178
BLAKE2b-256 checksum
How to use checksums
c362951eb4514c022a7e8fc405495f8b9009ec9ccdde090c7e360fc6609b5b67
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.2

Security for pymcp-auth-server 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page