Microsoft 365数据接口服务

通过MCP工具提供Microsoft 365数据的FastMCP服务器示例,支持Outlook日历、邮件、Teams、OneDrive/SharePoint和Microsoft To Do数据的查询、创建、修改和删除。

  • by leodev901
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 jinsoooooooo/mcp-sample

使用说明

MCP样品(FastMCP)

FastMCP服务器示例,使用MCP工具提供Microsoft 365数据。
目前的实现使用MS Graph API查看Outlook Calendar、Mail、Teams、OneDrive/Sharpoint、Microsoft To Do数据或创建/修改/删除一些数据。

当前集成功能

  • /mcp 在路径中提供基于Streamable HTTP的MCP服务器
  • HTTP请求头的 x-request-id, mcp_user_token 处理
  • 记录MCP工具运行日志、HTTP日志和Graph API调用日志
  • MS Graph App-only基于令牌的API调用
  • calendar_list 基准的 Tool -> Service -> Schema 应用阵列
  • 在所有工具中 user_email -> current_user -> DEFAULT_* 按顺序确定查询目标用户

请求处理流程

sequenceDiagram
    participant Client
    participant HTTP as HttpMiddleware
    participant ASGI as HttpLoggingASGIMiddleware
    participant MCP as MCPLoggingMiddleware
    participant Tool as MCP Tool
    participant Service as Service
    participant Graph as MS Graph API

    Client->>HTTP: POST /mcp
    HTTP->>ASGI: trace_id, user_token 저장
    ASGI->>MCP: HTTP 요청/응답 로깅
    MCP->>Tool: 도구 호출
    Tool->>Service: 파라미터와 사용자 정보 전달
    Service->>Graph: graph_request(...)
    Graph-->>Service: JSON 응답
    Service-->>Tool: Pydantic 모델 반환
    Tool-->>MCP: 도구 결과 반환
    MCP-->>Client: MCP 응답

Tool是暴露在MCP中的函数。
Service配置Graph API路径和请求正文。
Schema使用Pydantic模型验证返回值。
Pydantic:Python数据验证库。

项目结构

app/
  main.py                     # FastMCP 앱 생성 및 도구 등록

  clients/
    graph_client.py           # MS Graph API 공통 호출
    http_client.py            # 공통 HTTP 클라이언트
    mcp_client.py             # MCP 도구 로그 저장 클라이언트

  common/
    graph_error_wrapper.py    # Graph 예외를 MCP 응답으로 변환
    logger.py                 # Loguru/OpenTelemetry 로거 초기화

  core/
    config.py                 # 환경변수 및 MS365 설정
    http_middleware.py        # trace_id, user_token 저장
    http_asgi_middleware.py   # HTTP 요청/응답 로깅
    mcp_midleware.py          # MCP 도구 실행 로깅

  models/
    logging.py                # MCP 도구 로그 모델
    user_info.py              # 인증 사용자 정보 모델

  schemas/
    calendar.py               # Calendar 반환 스키마
    mail.py                   # Mail 반환 스키마
    sharepoint.py             # Drive 반환 스키마
    teams.py                  # Teams 반환 스키마
    todo.py                   # To Do 반환 스키마

  services/
    calendar_service.py       # Calendar Graph API 로직
    mail_service.py           # Mail Graph API 로직
    sharepoint_service.py     # OneDrive/SharePoint Graph API 로직
    teams_service.py          # Teams Graph API 로직
    todo_service.py           # To Do Graph API 로직

  tools/
    calendar_tools.py         # Calendar MCP 도구
    mail_tools.py             # Mail MCP 도구
    sharepoint_tools.py       # Drive MCP 도구
    teams_tools.py            # Teams MCP 도구
    to_do_tools.py            # To Do MCP 도구
    tool_context.py           # 현재 사용자 해석 공통 유틸

通用用户决策规则

所有工具都按以下顺序确定Graph API调用目标:

current_user = get_request_current_user()
query_email, query_company_cd = resolve_graph_user(user_email, current_user)

优先级:

  1. 工具参数的 user_email
  2. 从HTTP请求的JWT解析的 current_user
  3. .env的 DEFAULT_USER_EMAIL, DEFAULT_COMPANY_CD

为什么这样做:当LLM直接调用MCP工具时 user_email可以指定,在实际服务请求中可以自动使用JWT用户信息。在本地测试中,可以使用默认值快速验证。

工具列表

日历

工具名 说明 Graph API
calendar_list 查看日历日历的时间线列表 GET /calendarView
calendar_detail 查看单个日程表的详细信息 GET /events/{id}
calendar_create 创建新日程表 POST /events
calendar_update 修改现有的日历部分 PATCH /events/{id}
calendar_delete 删除现有日历 DELETE /events/{id}
search_email_by_name 使用M365用户名搜索电子邮件 GET /users

邮件

工具名 说明 Graph API
mail_recent_list 收件箱查看最近的邮件 GET /mailFolders/inbox/messages
mail_unread_list 查看未读邮件 GET /mailFolders/inbox/messages
mail_important_or_flagged_list 查看重要或标志邮件 GET /mailFolders/inbox/messages
mail_search_by_keyword 搜索标题/正文关键字 GET /messages?$search=...
mail_search_by_sender 根据发件人姓名/邮件搜索 GET /messages?$filter=...
mail_search_by_attachment 搜索带有附件的邮件 GET /messages?$filter=hasAttachments eq true
mail_sent_list 收件箱查看最近的邮件 GET /mailFolders/sentitems/messages
mail_detail 查看单个邮件的详细信息和附件 GET /messages/{id}, GET /messages/{id}/attachments

团队

工具名 说明 Graph API
teams_list_chats 查看您参与的Teams聊天室列表 GET /chats
teams_list_chat_messages 查看特定聊天室的最新消息 GET /chats/{id}/messages
teams_send_chat_message 向Teams聊天室发送消息 POST /chats/{id}/messages

OneDrive/SharePoint

工具名 说明 Graph API
drive_list_files 查看根目录或特定文件夹的文件/文件夹列表 GET /drive/root/children, GET /drive/items/{id}/children
drive_search_files 搜索驱动器文件 GET /drive/root/search(q='...')
drive_get_file_info 查看文件/文件夹详细信息和下载URL GET /drive/items/{id}

微软待办

工具名 说明 Graph API
todo_list_task_lists 查询待办事项列表 GET /todo/lists
todo_list_tasks 查看特定列表中的待办事项 GET /todo/lists/{id}/tasks
todo_create_task 创建新待办事宜 POST /todo/lists/{id}/tasks
todo_update_task 修改现有待办事宜部分 PATCH /todo/lists/{id}/tasks/{id}
todo_delete_task 删除现有待办事宜 DELETE /todo/lists/{id}/tasks/{id}

执行方法

前提条件:

  • Python 3.10或更高版本
  • .venv 虚拟环境
  • .env在中设置MS365
.\.venv\Scripts\pip.exe install -r requirements.txt
.\.venv\Scripts\uvicorn.exe app.main:app --host 0.0.0.0 --port 8002

通过MCP Inspector验证:

npx @modelcontextprotocol/inspector
  • 运输类型: streamable-http
  • 网址: http://127.0.0.1:8002/mcp

环境变量示例

LOG_LEVEL=DEBUG
ENV=local
AUTH_JWT_USER_TOKEN=false
DEFAULT_USER_EMAIL=admin@leodev901.onmicrosoft.com
DEFAULT_COMPANY_CD=leodev901
MS365_CONFIGS={"leodev901":{"tenant_id":"...","client_id":"...","client_secret":"...","default_user_email":"admin@leodev901.onmicrosoft.com"}}

验证命令

.\.venv\Scripts\python -m compileall app
.\.venv\Scripts\python -c "import app.main; print('main import ok')"

预期结果:

  • 所有的Python文件都会编译,没有语法错误。
  • main import ok将输出。

参考文档