MCP OAuth 服务器
一个Python库,可为MCP服务器添加OAuth 2.0认证,且设置简便。
安装
pip install -e .
# or
uv pip install -e .快速入门
1. 决定如何存储用户信息
例如,制作一个 users.txt 文件类似:
alice:cows
bob:dogs2. 创建您的MCP服务器
from mcp_base import create_oauth_server
def check_user(username: str, password: str) -> int:
with open("users.txt") as f:
for i, line in enumerate(f.readlines()):
if line == f"{username}:{password}":
return i
# Create server with defaults
mcp = create_oauth_server("my-app", check_user)
# Add your tools
@mcp.tool()
def echo(message: str) -> str:
"""Echo back the input message."""
return f"Echo: {message}"
# Run the server
if __name__ == "__main__":
mcp.run(transport="streamable-http")3. 运行它
python your_server.py就是这么简单!您的MCP服务器现在已运行OAuth认证 http://localhost:3000。
用户配置
OAuth 需要一系列复杂的流程,但很多时候你可能只需要用户名和密码。这 这就是这个库的用途。你可以根据自己的需求来设计用户验证的方式,并提供 一个函数,如果用户和密码组合有效,则返回该有效用户的ID;如果无效,则返回None 错误。库会为你处理其余部分。
登录界面
OAuth流程要求您验证通过该流程的用户是否为有效用户。 系统默认提供一个HTML登录页面,要求输入用户名和密码。 如果您想对此进行自定义,您可以提供自己的HTML代码来使用,通过 the login_template 参数,或者提供一个自定义处理程序来处理传入的请求。
登录模板
登录模板是一段HTML代码。它将显示给用户,以便用户输入凭据。 默认处理程序期望一个包含(某元素)的表单 state 对于OAuth相关内容的值,以及一个 username 并且 password 使用用户凭据。以下宏将在HTML中被替换(通过使用一个非常简单的 字符串替换,所以请确保使用这些确切的字符串):
{state}- OAuth状态,如在GET URL或POST表单数据中提供{username}- 如果提供了无效密码,您可以使用此功能来保留用户名{app_name}- 您的应用名称,如提供给(某方/平台等)的名称create_oauth_server{error_message}- 验证过程中发生的任何异常
自定义登录处理程序
OAuth流程需要 /oauth/login 通过GET请求被调用,并随后进行重定向 将流程引导至适当的终端以继续进行。第一部分是硬编码的,而重定向部分 当任何客户端初始化流程时,会提供这个(信息)。话虽如此,你可以控制这一过程如何进行。
要使用您自己的处理程序,请提供一个具有以下签名的函数给 login_handler 的 create_oauth_server 呼叫;打电话
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
async def login_handler(request: Request, complete_user_checker: Callable[[str, str, str], str]) -> HTMLResponse | RedirectResponse:
(...)request 这是Starlette请求。 complete_user_checker 是一个接收OAuth的函数 状态、用户名和密码,如果正确则返回重定向URL,否则抛出ValueError异常(如果任何一项不匹配) 是错误的。
基本上,你从请求中提取状态(request.query_params.get("state")), 提取 随意设置用户名和密码,然后执行:
try:
redirect_url = complete_user_checker(state, username, password)
return RedirectResponse(url=redirect_url, status_code=302)
except ValueError as e:
# handle the error自定义配置
from mcp_base import create_oauth_server, ServerConfig
config = ServerConfig(
host="localhost",
port=8000,
db_path="my_auth.db",
supported_scopes=["read", "write", "admin"],
required_scopes=["read"],
debug=True,
)
mcp = create_oauth_server("my-app", config=config)示例
见 示例/ 完整示例目录:
simple_server.py- 基本用法custom_server.py- 自定义配置file_credentials_server.py- 用户在……中定义users.txt
部署
如果你想通过Nginx代理运行,那么以下方法应该能解决问题:
server {
server_name ;
# Basic security headers
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
add_header X-XSS-Protection "1; mode=block" always;
# Rate limiting (optional)
# limit_req zone=api burst=20 nodelay;
# Handle MCP endpoint redirect internally
# Proxy everything to your memory app
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}哪里 ` 应替换为您实际的域名,并且 http://localhost:3000` 到;向;朝 无论你在哪里运行你的MCP服务器。
测试
手动测试MCP(可能指某种系统或组件,如“多控制器协议”等,具体需根据上下文确定)相关内容并非易事,因此你可能需要类似这样的工具或方法 MCP检查员 在你真正(做某事)之前 尝试使用包含各种元素的模型。
