Files
cowork-local/mcp_servers/ms365_server.py
T
anhtnm1andClaude Opus 5 e29a0ccdbd refactor: vá 4 hồi quy, tách 4 file chạm trần LOC, docstring lên 100%
Hồi quy đã vá
-------------
F-12  Kéo–thả hoặc dán tệp vào ô chat ném NameError. R08 tách `_Input` sang
      `chat_input_box.py` nhưng để `_paths_from_mime()` ở lại
      `composer_widget.py`, nên hai hàm sự kiện Qt gọi một cái tên không tồn
      tại. Bốn hàm dùng chung chuyển sang `composer_mime.py` — module thứ ba
      là chỗ duy nhất không lặp lại được lỗi này. Đo lại: cả thả lẫn dán đều
      gắn 1 tệp, khớp bản trước refactor.

F-01  Đổi provider thì bộ chọn model AI-Edit không làm gì. Hook cũ kiểm
      `folder.ai_model_combo`, thuộc tính R08-T12 đã dời sang
      `ai_panel.resolver`. Làm mới vô điều kiện, đúng như tab cũ: lần lấy đầu
      tiên hỏng thì đổi provider chính là lúc phải thử lại.

F-07  Hàng chọn kỳ của Dashboard bị đẩy xuống dưới các thẻ số liệu. Hàng này
      lọc CẢ BA thẻ con chứ không riêng biểu đồ, nên để nó nằm dưới là bắt
      người dùng đọc con số trước khi thấy con số đó tính cho kỳ nào. Kèm
      theo: `TokenUsageCardWidget` bị bỏ sót `setContentsMargins(0,0,0,0)`
      mà hai thẻ con còn lại đã có, đẩy cả hàng thẻ lệch 9px.
      `check_layout_geometry` nay khớp TỪNG BYTE với bản trước refactor.

F-11  Hai lớp khai trùng tên phương thức; Python giữ bản sau nên bản đầu là
      mã chết. `co4e_tab.py::showEvent` bản đầu gọi `_narrow_guard.attach()`
      và không bao giờ chạy.

Tách file (F-09)
----------------
Bốn file chạm trần 400 dòng, mỗi lần cắt ra một trách nhiệm thật:

    graph_renderer.py         -> graph_scene_builder.py + graph_export.py
    co4e_workflow_service.py  -> co4e_run_history.py
    json_config_repository.py -> config_sections.py
    agents_admin_tab.py       -> shared/agent_kind_visuals.py

File cuối còn xoá 3 bản sao của hàm đã có trong `shared/formatters.py`,
giống hệt đến từng dòng — nay định dạng thời gian và avatar không lệch nhau
giữa các bảng Giám sát nữa.

Docstring
---------
41,6% -> 100% (3.478/3.478 định nghĩa production), kể cả module dormant và
phương thức dunder. Toàn bộ phần bổ sung viết bằng tiếng Việt; comment tiếng
Anh có sẵn giữ nguyên — dịch ngược là một đợt riêng.

Seam chưa nối dây (F-05)
------------------------
9 seam mang nhãn `SEAM · dựng <ngày>` kèm hai câu: được nối khi nào, và để
dormant thì hỏng gì. Ngày lấy từ lịch sử git, không phải hạn tự đặt. Gate O
đọc nhãn đó và nhắc khi quá 30 ngày.

859 test xanh · 4/4 cổng CASAN · 19/24 checker khớp từng byte bản cũ.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 10:41:45 +09:00

107 lines
4.1 KiB
Python

"""Built-in MCP server for Microsoft 365 — ``python -m
cowork_local.mcp_servers.ms365_server``.
Wraps the existing Graph integration (``core/ms365_tools.build_ms365_tools``
→ ``core/ms365_graph``) as a standard stdio MCP server, so M365 tools reach
agents through the SAME MCP client layer as every external server
(``core/mcp_client.py``): calls are audited as ``kind="mcp_call"``, appear in
Monitoring's MCP Call History, and tool names arrive namespaced as
``ms365__<tool>`` (e.g. ``ms365__send_mail``).
Auth needs nothing new: the MSAL token cache lives in the OS credential
store (``core/ms365_auth.py``), which this subprocess shares with the GUI —
signing in via Settings → "Kết nối Microsoft 365" is enough.
Config is re-read from ``~/.cowork_local/config.json`` on EVERY list/call, so
toggling a connector (or signing out) in Settings applies on the next agent
turn without restarting this server.
"""
from __future__ import annotations
from typing import Any, Dict, List, Tuple
# Tool names inside this server drop the legacy "ms365_" prefix — the MCP
# client namespaces them "ms365__<name>", and "ms365__ms365_send_mail" would
# be silly. The legacy executor still dispatches by the prefixed name, so we
# strip on the way out and re-add on the way in.
_PREFIX = "ms365_"
def _strip(name: str) -> str:
"""Bỏ tiền tố ``ms365_`` khỏi tên tool.
MCP đã gom tool theo tên máy chủ nên để tiền tố nữa thành thừa; bộ thực
thi cũ vẫn dispatch theo tên có tiền tố, nên gỡ lúc ra và gắn lại lúc vào.
"""
return name[len(_PREFIX):] if name.startswith(_PREFIX) else name
def _fresh_tools() -> Tuple[list, Any]:
"""(specs, executor) from a FRESH config read — see module docstring."""
from cowork_local.config import AppConfig
from cowork_local.core.ms365_tools import build_ms365_tools
return build_ms365_tools(AppConfig.load())
def _tool_list() -> List[Dict[str, Any]]:
"""Plain-dict tool descriptions (name/description/inputSchema) — kept
SDK-type-free so tests can call it without an MCP session."""
specs, _executor = _fresh_tools()
return [{"name": _strip(s.name), "description": s.description,
"inputSchema": s.parameters} for s in specs]
def _dispatch(name: str, args: Dict[str, Any]) -> str:
"""Run one tool through the legacy executor; returns its output text or
raises RuntimeError (the MCP SDK turns that into an isError result)."""
_specs, executor = _fresh_tools()
if executor is None:
raise RuntimeError(
"Microsoft 365 is not available: not signed in, no connector enabled, "
"or external internet access is off (see Settings).")
result = executor(_PREFIX + _strip(name), args or {})
output = str(result.get("output", ""))
if not result.get("ok"):
raise RuntimeError(output or f"MS365 tool '{name}' failed.")
return output
def build_server():
"""Dựng máy chủ MCP cho nhóm tool MS365 và đăng ký hai handler của giao thức."""
import mcp.types as types
from mcp.server.lowlevel import Server
app = Server("ms365")
@app.list_tools()
async def list_tools() -> List["types.Tool"]:
"""Trả về danh sách tool MS365 hiện có, đọc từ cấu hình mới nhất."""
return [types.Tool(**t) for t in _tool_list()]
@app.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]) -> List["types.TextContent"]:
"""Chạy một tool MS365 và trả kết quả về dưới dạng văn bản."""
return [types.TextContent(type="text", text=_dispatch(name, arguments or {}))]
return app
def main() -> None:
"""Điểm vào khi chạy như tiến trình con: phục vụ MCP qua stdio."""
import anyio
from mcp.server.stdio import stdio_server
app = build_server()
async def _run() -> None:
"""Vòng lặp phục vụ, đọc/ghi trên stdio cho tới khi tiến trình cha đóng."""
async with stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())
anyio.run(_run)
if __name__ == "__main__":
main()