休假管理系统

一个基于MCP协议的员工休假管理系统,提供休假余额查询、申请和历史记录查看功能。

  • by PRASADNY
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 PRASADNY/my-first-mcp-server

使用说明

MCP服务器-休假管理系统

MCP(模型上下文协议)服务器,为员工休假跟踪和管理提供休假管理工具。

特性

  • 休假余额跟踪:检查员工的剩余休假天数
  • 请假申请:申请特定日期的休假
  • 离开历史:查看员工的休假历史记录
  • 身份验证支持:可选的API密钥和承载令牌身份验证
  • FastMCP框架:使用FastMCP构建,用于快速服务器开发

安装

看 安装.md 了解详细的安装说明。

快速安装

pip install -e .

或使用 uv:

uv pip install -e .

先决条件

  • Python>=3.13

配置

环境变量

创建一个 .env 服务器目录中的文件:

# Enable/Disable authentication requirement
# Set to "true" to require authentication, "false" to allow unauthenticated connections
MCP_AUTH_REQUIRED=false

# Server API Key
# This is the API key that the server expects from clients
MCP_SERVER_API_KEY=default-api-key-12345

# Server Bearer Token (Optional)
# Uncomment and set if you want to use token-based authentication
# MCP_SERVER_TOKEN=your-server-token-here

身份验证模式

模式1:无身份验证(默认)

MCP_AUTH_REQUIRED=false

允许所有客户端无需身份验证即可连接。

模式2:API密钥认证

MCP_AUTH_REQUIRED=true
MCP_SERVER_API_KEY=your-secure-api-key

客户端必须提供匹配 MCP_API_KEY 在他们的环境中。

模式3:承载令牌认证

MCP_AUTH_REQUIRED=true
MCP_SERVER_TOKEN=your-secure-token

客户端必须提供匹配 MCP_TOKEN 或 MCP_BEARER_TOKEN 在他们的环境中。

用法

运行服务器

python main.py

服务器将启动并通过stdio监听MCP客户端连接。

使用MCP客户端进行测试

从客户端目录连接:

cd ../my-first-mcp-client
python client.py ../my-first-mcp-server/main.py

可用工具

1. get_leave_balance(employee_id: str) -> str

检查员工还剩多少假期。

参数:

  • employee_id:员工ID(例如“E001”、“E002”)

退货:

  • 带假期余额信息的字符串

例子:

Input: "E001"
Output: "E001 has 18 leave days remaining."

2. apply_leave(employee_id: str, leave_dates: List[str]) -> str

申请特定日期的休假。

参数:

  • employee_id:员工ID
  • leave_dates:“YYYY-MM-DD”格式的日期列表(例如,[“2025-04-17”,“2025-05-01”])

退货:

  • 带休假申请结果的字符串

例子:

Input: employee_id="E001", leave_dates=["2025-04-17", "2025-05-01"]
Output: "Leave applied for 2 day(s). Remaining balance: 16."

3. get_leave_history(employee_id: str) -> str

获取员工的休假历史记录。

参数:

  • employee_id:员工ID

退货:

  • 带休假历史记录的字符串

例子:

Input: "E001"
Output: "Leave history for E001: 2024-12-25, 2025-01-01"

可用资源

greeting://{name}

获得个性化问候。

例子:

URI: greeting://John
Output: "Hello, John! How can I assist you with leave management today?"

数据模型

服务器维护一个具有以下结构的内存数据库:

employee_leaves = {
    "E001": {
        "balance": 18,  # Remaining leave days
        "history": ["2024-12-25", "2025-01-01"]  # List of leave dates
    },
    "E002": {
        "balance": 20,
        "history": []
    }
}

备注:数据库在内存中,服务器重新启动时会重置。对于生产使用,实施持久存储。

认证

身份验证的工作原理

  1. 客户端发送凭据:客户端通过环境变量提供凭据
  2. 服务器验证:服务器根据配置值检查凭据
  3. 访问控制:如果需要身份验证但失败,工具将返回错误消息

认证流程

Client                     Server
  |                          |
  |-- Connect with env vars->|
  |                          |
  |<-- Validate credentials--|
  |                          |
  |-- Tool call request----->|
  |                          |
  |<-- Check auth -----------|
  |                          |
  |<-- Tool result ----------|

安全最佳实践

  1. 生产部署:

    • 使用强随机生成的密钥/令牌
    • 永不承诺 .env 文件到版本控制
    • 使用机密管理服务(AWS secrets Manager、HashiCorp Vault等)
  2. 关键点旋转:

    • 定期轮换API密钥和令牌
    • 同时更新客户端和服务器配置
  3. 环境隔离:

    • 使用不同的密钥进行开发、暂存和生产
    • 切勿在开发环境中共享生产密钥

编码结构

main.py
├── Authentication Configuration
│   ├── validate_authentication() - Validates client credentials
│   └── require_auth() - Decorator for protected functions
├── Data Storage
│   └── employee_leaves - In-memory database
├── Tools
│   ├── get_leave_balance()
│   ├── apply_leave()
│   └── get_leave_history()
└── Resources
    └── get_greeting()

扩展服务器

添加新工具

@mcp.tool()
def your_new_tool(param1: str, param2: int) -> str:
    """Description of your tool"""
    # Check authentication if required
    if not validate_authentication():
        return "Error: Authentication required."
    
    # Your tool logic here
    return "Result"

添加新资源

@mcp.resource("resource://{param}")
def get_resource(param: str) -> str:
    """Get resource data"""
    return f"Resource data for {param}"

添加持久存储

用数据库替换内存中的字典:

import sqlite3

# Initialize database connection
conn = sqlite3.connect('leaves.db')
cursor = conn.cursor()

# Create table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS employee_leaves (
        employee_id TEXT PRIMARY KEY,
        balance INTEGER,
        history TEXT
    )
''')

故障排除

身份验证不起作用

  1. 验证 MCP_AUTH_REQUIRED 设置正确
  2. 确保客户端和服务器使用匹配的凭据
  3. 检查环境变量是否正确加载

工具调用失败

  1. 检查服务器日志是否有错误
  2. 验证数据库中是否存在员工ID
  3. 确保日期格式正确(YYYY-MM-DD)

连接问题

  1. 验证服务器脚本是否可执行
  2. 检查是否安装了所有依赖项
  3. 确保Python版本>=3.13

另见