chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1 @@
|
||||
.venv/
|
||||
@@ -0,0 +1,85 @@
|
||||
# Academy 本地 MCP Demo
|
||||
|
||||
最小外部 MCP 服务,用来测试 Academy **作为 MCP 客户端**接入第三方工具。
|
||||
|
||||
提供 6 个演示工具:
|
||||
|
||||
| 工具 | 作用 |
|
||||
| --- | --- |
|
||||
| `echo` | 连通性自检 |
|
||||
| `add` | 两数相加 |
|
||||
| `server_time` | 返回服务器 UTC 时间 |
|
||||
| `lookup_policy` | 查询演示政策(保修、报销、POC 等,与 `website-docs/sample-data/` 一致) |
|
||||
| `list_team_contacts` | 列出演示项目团队成员 |
|
||||
| `send_demo_alert` | 模拟外发通知(适合测工具人工审批) |
|
||||
|
||||
## 1. 启动
|
||||
|
||||
```bash
|
||||
cd examples/mcp-demo
|
||||
chmod +x start.sh
|
||||
./start.sh
|
||||
```
|
||||
|
||||
`start.sh` 会自动创建 `.venv` 并安装依赖。默认监听 `http://127.0.0.1:8010/mcp`,鉴权令牌 `academy-demo-token`。
|
||||
|
||||
自定义:
|
||||
|
||||
```bash
|
||||
export MCP_SERVER_AUTH_TOKEN=my-secret
|
||||
export MCP_PORT=9000
|
||||
./start.sh
|
||||
```
|
||||
|
||||
## 2. 自检
|
||||
|
||||
另开终端:
|
||||
|
||||
```bash
|
||||
cd examples/mcp-demo
|
||||
source .venv/bin/activate
|
||||
python test_tools.py
|
||||
```
|
||||
|
||||
应列出 6 个工具。
|
||||
|
||||
## 3. 接入 Academy
|
||||
|
||||
1. 打开 **设置 → MCP 服务 → 新建**
|
||||
2. 填写:
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| 名称 | `本地 MCP Demo` |
|
||||
| 传输 | **HTTP Streamable** |
|
||||
| URL | `http://127.0.0.1:8010/mcp` |
|
||||
| 认证 | **Bearer** |
|
||||
| 令牌 | `academy-demo-token`(与 `MCP_SERVER_AUTH_TOKEN` 一致) |
|
||||
|
||||
3. 保存后点 **测试连接**,应发现 6 个工具。
|
||||
4. 在 **智能体** 配置里勾选该 MCP 服务(或选全部工具)。
|
||||
5. (可选)对 `send_demo_alert` 开启**人工审批**,对话时 Agent 调用前会弹出确认。
|
||||
|
||||
## 4. 建议试的问题
|
||||
|
||||
在 Agent 对话里问:
|
||||
|
||||
- 「调用 MCP 工具查一下智能家居中控保修多久」→ 应触发 `lookup_policy`
|
||||
- 「研发部 POC 负责人是谁」→ `lookup_policy` 或 `list_team_contacts`
|
||||
- 「现在 MCP Demo 服务器几点」→ `server_time`
|
||||
|
||||
若同时导入了 `website-docs/sample-data/` 里的文档,可以对比 **知识库检索答案** 与 **MCP 工具返回** 是否一致。
|
||||
|
||||
## 5. 注意事项
|
||||
|
||||
- Academy UI **不支持 stdio** 传输;必须用 **HTTP Streamable** 或 **SSE**。
|
||||
- Demo 只绑定 `127.0.0.1`,不要暴露到公网。
|
||||
- `send_demo_alert` 不会真正发送消息,仅返回模拟结果。
|
||||
|
||||
## 6. SSE 模式(可选)
|
||||
|
||||
```bash
|
||||
MCP_TRANSPORT=sse MCP_PORT=8011 ./start.sh
|
||||
```
|
||||
|
||||
Academy 里传输选 **SSE**,URL 填 `http://127.0.0.1:8011/sse`。
|
||||
@@ -0,0 +1,4 @@
|
||||
mcp>=2,<3
|
||||
starlette>=0.27.0
|
||||
uvicorn>=0.24.0
|
||||
httpx>=0.27.0
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Academy 本地 MCP Demo Server
|
||||
|
||||
最小可运行的外部 MCP 服务,用于在 Academy「设置 → MCP 服务」里测试客户端接入。
|
||||
默认以 Streamable HTTP 监听 http://127.0.0.1:8010/mcp
|
||||
|
||||
启动:
|
||||
export MCP_SERVER_AUTH_TOKEN=academy-demo-token
|
||||
python server.py
|
||||
|
||||
Academy 配置:
|
||||
传输:HTTP Streamable
|
||||
URL:http://127.0.0.1:8010/mcp
|
||||
认证:Bearer,令牌与 MCP_SERVER_AUTH_TOKEN 一致
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from mcp.server import MCPServer
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
logger = logging.getLogger("mcp-demo")
|
||||
|
||||
mcp = MCPServer("academy-mcp-demo", version="0.1.0")
|
||||
|
||||
# 与 website-docs/sample-data/ 配套的演示语料,方便 Agent 调用后对照知识库答案。
|
||||
DEMO_POLICIES: dict[str, str] = {
|
||||
"warranty": "智能家居中控 Pro 整机保修 24 个月,电池类配件 12 个月;人为拆解、进水不在保修范围。",
|
||||
"offline_voice": "若语音走云端识别,断外网后仅支持 App 与本地触摸屏;配置本地语音包后可继续使用基础指令。",
|
||||
"device_limit": "个人版账号最多绑定 3 台中控;企业版按合同授权,默认 50 台。",
|
||||
"travel_hotel_tier1": "一线城市(北上广深)出差住宿报销上限 600 元/晚(含税)。",
|
||||
"travel_meal": "出差期间餐饮费不单独报销;一线城市差旅补贴 150 元/天。",
|
||||
"poc_owner": "售后知识库 POC 技术负责人是研发部张明,产品对接人是李薇,测试负责人是赵磊。",
|
||||
"poc_deadline": "售后知识库 POC 目标 2024-03-01 前完成内网演示。",
|
||||
"matter_cert": "固件 3.5 计划在 2024 年 3 月底前发布灰度,完成 Matter 1.2 认证。",
|
||||
}
|
||||
|
||||
DEMO_CONTACTS: list[dict[str, str]] = [
|
||||
{"name": "陈浩", "role": "产品总监", "department": "产品部"},
|
||||
{"name": "张明", "role": "知识库与 AI 模块负责人", "department": "研发部"},
|
||||
{"name": "李薇", "role": "产品运营", "department": "产品部"},
|
||||
{"name": "王雪", "role": "交互设计负责人", "department": "设计部"},
|
||||
{"name": "赵磊", "role": "测试经理", "department": "测试部"},
|
||||
]
|
||||
|
||||
|
||||
def network_transport_auth_token() -> str:
|
||||
return os.getenv("MCP_SERVER_AUTH_TOKEN", "").strip()
|
||||
|
||||
|
||||
def require_network_transport_auth(transport: str) -> str:
|
||||
token = network_transport_auth_token()
|
||||
if transport in ("sse", "http") and not token:
|
||||
logger.error(
|
||||
"MCP_SERVER_AUTH_TOKEN is required for %s transport. "
|
||||
"Example: export MCP_SERVER_AUTH_TOKEN=academy-demo-token",
|
||||
transport,
|
||||
)
|
||||
sys.exit(1)
|
||||
return token
|
||||
|
||||
|
||||
class MCPAuthMiddleware:
|
||||
"""SSE / HTTP 传输的 Bearer 鉴权中间件。"""
|
||||
|
||||
def __init__(self, app, token: str):
|
||||
self.app = app
|
||||
self.token = token
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope.get("type") != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
headers = {
|
||||
k.decode("latin-1").lower(): v.decode("latin-1")
|
||||
for k, v in scope.get("headers", [])
|
||||
}
|
||||
provided = ""
|
||||
auth = headers.get("authorization", "")
|
||||
if auth.lower().startswith("bearer "):
|
||||
provided = auth[7:].strip()
|
||||
elif "x-mcp-auth-token" in headers:
|
||||
provided = headers["x-mcp-auth-token"]
|
||||
|
||||
if not provided or not secrets.compare_digest(provided, self.token):
|
||||
body = b'{"error":"unauthorized"}'
|
||||
await send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": 401,
|
||||
"headers": [[b"content-type", b"application/json"]],
|
||||
}
|
||||
)
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
return
|
||||
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def echo(message: str) -> dict[str, Any]:
|
||||
"""回显一条消息,用于验证 MCP 连通性。"""
|
||||
return {"echo": message}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def add(a: float, b: float) -> dict[str, Any]:
|
||||
"""计算两个数字之和。"""
|
||||
return {"a": a, "b": b, "sum": a + b}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def server_time() -> dict[str, str]:
|
||||
"""返回 MCP Demo 服务器当前 UTC 时间。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
return {
|
||||
"iso": now.isoformat(),
|
||||
"unix": str(int(now.timestamp())),
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def lookup_policy(topic: str) -> dict[str, Any]:
|
||||
"""查询演示政策/项目信息。topic 可用 warranty/offline_voice/device_limit/travel_hotel_tier1/travel_meal/poc_owner/poc_deadline/matter_cert,或中文关键词如「保修」「报销」「POC」。"""
|
||||
key = topic.strip().lower().replace(" ", "_")
|
||||
aliases = {
|
||||
"保修": "warranty",
|
||||
"质保": "warranty",
|
||||
"离线": "offline_voice",
|
||||
"语音": "offline_voice",
|
||||
"设备数": "device_limit",
|
||||
"住宿": "travel_hotel_tier1",
|
||||
"报销": "travel_hotel_tier1",
|
||||
"餐饮": "travel_meal",
|
||||
"补贴": "travel_meal",
|
||||
"负责人": "poc_owner",
|
||||
"张明": "poc_owner",
|
||||
"poc": "poc_owner",
|
||||
"验收": "poc_deadline",
|
||||
"matter": "matter_cert",
|
||||
"认证": "matter_cert",
|
||||
}
|
||||
for alias, mapped in aliases.items():
|
||||
if alias in topic:
|
||||
key = mapped
|
||||
break
|
||||
|
||||
if key in DEMO_POLICIES:
|
||||
return {"topic": key, "answer": DEMO_POLICIES[key], "source": "mcp-demo/static"}
|
||||
|
||||
matches = {
|
||||
k: v
|
||||
for k, v in DEMO_POLICIES.items()
|
||||
if key in k or any(ch in k for ch in key if len(key) >= 2)
|
||||
}
|
||||
if len(matches) == 1:
|
||||
only_key = next(iter(matches))
|
||||
return {"topic": only_key, "answer": matches[only_key], "source": "mcp-demo/static"}
|
||||
|
||||
return {
|
||||
"topic": topic,
|
||||
"available_topics": sorted(DEMO_POLICIES.keys()),
|
||||
"hint": "传入 topic 为上述键名,或中文关键词如「保修」「报销」「POC」。",
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def list_team_contacts(department: str = "") -> dict[str, Any]:
|
||||
"""列出演示项目团队成员;可按部门名过滤(产品部 / 研发部 / 设计部 / 测试部)。"""
|
||||
rows = DEMO_CONTACTS
|
||||
if department.strip():
|
||||
needle = department.strip()
|
||||
rows = [c for c in rows if needle in c["department"]]
|
||||
return {"count": len(rows), "contacts": rows}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def send_demo_alert(channel: str, message: str) -> dict[str, Any]:
|
||||
"""模拟向外部渠道发送通知(演示用,不会真正外发)。
|
||||
|
||||
适合在 Academy 里测试 MCP 工具人工审批:建议把此工具标记为需要审批。
|
||||
"""
|
||||
return {
|
||||
"ok": True,
|
||||
"simulated": True,
|
||||
"channel": channel,
|
||||
"message": message,
|
||||
"sent_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
async def run_http(host: str, port: int) -> None:
|
||||
auth_token = require_network_transport_auth("http")
|
||||
try:
|
||||
import uvicorn
|
||||
except ImportError as e:
|
||||
raise ImportError("HTTP transport requires: pip install starlette uvicorn") from e
|
||||
|
||||
starlette_app = MCPAuthMiddleware(
|
||||
mcp.streamable_http_app(host=host, stateless_http=True),
|
||||
auth_token,
|
||||
)
|
||||
logger.info("Streamable HTTP MCP demo listening on http://%s:%d/mcp", host, port)
|
||||
config = uvicorn.Config(starlette_app, host=host, port=port, log_level="info")
|
||||
server = uvicorn.Server(config)
|
||||
await server.serve()
|
||||
|
||||
|
||||
async def run_sse(host: str, port: int) -> None:
|
||||
auth_token = require_network_transport_auth("sse")
|
||||
try:
|
||||
import uvicorn
|
||||
except ImportError as e:
|
||||
raise ImportError("SSE transport requires: pip install starlette uvicorn") from e
|
||||
|
||||
starlette_app = MCPAuthMiddleware(
|
||||
mcp.sse_app(host=host, message_path="/sse/messages/"),
|
||||
auth_token,
|
||||
)
|
||||
logger.info("SSE MCP demo listening on http://%s:%d/sse", host, port)
|
||||
config = uvicorn.Config(starlette_app, host=host, port=port, log_level="info")
|
||||
server = uvicorn.Server(config)
|
||||
await server.serve()
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Academy local MCP demo server")
|
||||
parser.add_argument(
|
||||
"--transport",
|
||||
choices=["http", "sse"],
|
||||
default=os.getenv("MCP_TRANSPORT", "http"),
|
||||
help="Network transport (default: http / Streamable HTTP)",
|
||||
)
|
||||
parser.add_argument("--host", default=os.getenv("MCP_HOST", "127.0.0.1"))
|
||||
parser.add_argument("--port", type=int, default=int(os.getenv("MCP_PORT", "8010")))
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
args = parse_args()
|
||||
if args.transport == "http":
|
||||
await run_http(args.host, args.port)
|
||||
else:
|
||||
await run_sse(args.host, args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
logger.info("stopped")
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
export MCP_SERVER_AUTH_TOKEN="${MCP_SERVER_AUTH_TOKEN:-academy-demo-token}"
|
||||
export MCP_HOST="${MCP_HOST:-127.0.0.1}"
|
||||
export MCP_PORT="${MCP_PORT:-8010}"
|
||||
export MCP_TRANSPORT="${MCP_TRANSPORT:-http}"
|
||||
|
||||
VENV_DIR=".venv"
|
||||
if [[ ! -d "$VENV_DIR" ]]; then
|
||||
echo "Creating virtualenv in $VENV_DIR ..."
|
||||
python3 -m venv "$VENV_DIR"
|
||||
fi
|
||||
# shellcheck disable=SC1091
|
||||
source "$VENV_DIR/bin/activate"
|
||||
|
||||
if ! python -c "import mcp" 2>/dev/null; then
|
||||
echo "Installing dependencies..."
|
||||
pip install -r requirements.txt
|
||||
fi
|
||||
|
||||
echo "MCP Demo"
|
||||
echo " transport : ${MCP_TRANSPORT}"
|
||||
echo " endpoint : http://${MCP_HOST}:${MCP_PORT}/$([ "$MCP_TRANSPORT" = http ] && echo mcp || echo sse)"
|
||||
echo " auth token: ${MCP_SERVER_AUTH_TOKEN}"
|
||||
echo
|
||||
echo "Academy UI → 设置 → MCP 服务 → 新建"
|
||||
echo " 传输: HTTP Streamable"
|
||||
echo " URL : http://${MCP_HOST}:${MCP_PORT}/mcp"
|
||||
echo " 认证: Bearer / ${MCP_SERVER_AUTH_TOKEN}"
|
||||
echo
|
||||
|
||||
exec python server.py --transport "$MCP_TRANSPORT" --host "$MCP_HOST" --port "$MCP_PORT"
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""列出 MCP Demo 暴露的工具(需先启动 server.py)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
import httpx
|
||||
from mcp import ClientSession
|
||||
from mcp.client.streamable_http import streamable_http_client
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
base = os.getenv("MCP_DEMO_URL", "http://127.0.0.1:8010/mcp")
|
||||
token = os.getenv("MCP_SERVER_AUTH_TOKEN", "academy-demo-token")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=30.0,
|
||||
) as http_client:
|
||||
async with streamable_http_client(base, http_client=http_client) as (read, write):
|
||||
async with ClientSession(read, write) as session:
|
||||
await session.initialize()
|
||||
tools = await session.list_tools()
|
||||
print(f"connected: {base}")
|
||||
print(f"tools ({len(tools.tools)}):")
|
||||
for tool in tools.tools:
|
||||
print(f" - {tool.name}: {tool.description}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(asyncio.run(main()))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"failed: {exc}", file=sys.stderr)
|
||||
print("start the server first: ./start.sh", file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
@@ -0,0 +1,92 @@
|
||||
# Skills 示例
|
||||
|
||||
本目录包含 Agent Skills 功能的示例。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
skills/
|
||||
├── README.md # 本文件
|
||||
└── pdf-processing/ # PDF 处理技能示例
|
||||
├── SKILL.md # 主文件(Level 2)
|
||||
├── FORMS.md # 补充文档(Level 3)
|
||||
└── scripts/ # 可执行脚本
|
||||
├── analyze_form.py
|
||||
└── extract_text.py
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 运行 Demo
|
||||
|
||||
```bash
|
||||
go run ./cmd/skills-demo/main.go
|
||||
```
|
||||
|
||||
### 创建新 Skill
|
||||
|
||||
1. 在本目录创建新文件夹:
|
||||
|
||||
```bash
|
||||
mkdir my-new-skill
|
||||
```
|
||||
|
||||
2. 创建 `SKILL.md`:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: my-new-skill
|
||||
description: Description of what this skill does and when to use it.
|
||||
---
|
||||
|
||||
# My New Skill
|
||||
|
||||
Instructions for the agent...
|
||||
```
|
||||
|
||||
3. 添加脚本(可选):
|
||||
|
||||
```bash
|
||||
mkdir my-new-skill/scripts
|
||||
# 添加你的脚本
|
||||
```
|
||||
|
||||
## 详细文档
|
||||
|
||||
完整文档请参阅:[Agent Skills 文档](../../website-docs/03-features/22-skills-sandbox.md)
|
||||
|
||||
## 示例:pdf-processing
|
||||
|
||||
这是一个功能完整的示例技能,展示了:
|
||||
|
||||
- **SKILL.md**: 包含 YAML frontmatter 的主文件
|
||||
- **FORMS.md**: 补充参考文档
|
||||
- **scripts/**: 可在沙箱中执行的 Python 脚本
|
||||
|
||||
### 技能描述
|
||||
|
||||
```yaml
|
||||
name: pdf-processing
|
||||
description: Extract text and tables from PDF files, fill forms, merge documents.
|
||||
```
|
||||
|
||||
### 包含的脚本
|
||||
|
||||
| 脚本 | 功能 |
|
||||
|------|------|
|
||||
| `analyze_form.py` | 分析 PDF 表单字段 |
|
||||
| `extract_text.py` | 从 PDF 提取文本 |
|
||||
|
||||
### 使用示例
|
||||
|
||||
Agent 会根据用户请求自动调用:
|
||||
|
||||
```
|
||||
用户: "分析一下这个 PDF 表单有哪些字段"
|
||||
|
||||
Agent:
|
||||
1. 识别匹配 pdf-processing 技能
|
||||
2. 调用 read_file(path="skill://pdf-processing/SKILL.md") 加载技能内容
|
||||
3. 调用 shell_exec(skill_name="pdf-processing", command=...) 执行 analyze_form.py
|
||||
4. 返回表单字段分析结果
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
# PDF Form Filling Guide
|
||||
|
||||
This guide covers how to fill PDF forms programmatically.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Install required packages:
|
||||
```bash
|
||||
pip install pypdf pdfrw
|
||||
```
|
||||
|
||||
## Basic Form Filling
|
||||
|
||||
```python
|
||||
from pypdf import PdfReader, PdfWriter
|
||||
|
||||
def fill_form(input_path, output_path, field_data):
|
||||
reader = PdfReader(input_path)
|
||||
writer = PdfWriter()
|
||||
|
||||
# Clone the original PDF
|
||||
writer.clone_document_from_reader(reader)
|
||||
|
||||
# Fill form fields
|
||||
for page in writer.pages:
|
||||
writer.update_page_form_field_values(page, field_data)
|
||||
|
||||
# Save the filled PDF
|
||||
with open(output_path, "wb") as f:
|
||||
writer.write(f)
|
||||
```
|
||||
|
||||
## Supported Field Types
|
||||
|
||||
- Text fields
|
||||
- Checkboxes
|
||||
- Radio buttons
|
||||
- Dropdown lists
|
||||
|
||||
## Tips
|
||||
|
||||
1. Use `scripts/analyze_form.py` to discover available fields
|
||||
2. Field names are case-sensitive
|
||||
3. Always verify output after filling
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
name: pdf-processing
|
||||
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
|
||||
---
|
||||
# PDF Processing
|
||||
|
||||
This skill provides utilities for working with PDF documents.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Use pdfplumber to extract text from PDFs:
|
||||
|
||||
```python
|
||||
import pdfplumber
|
||||
|
||||
with pdfplumber.open("document.pdf") as pdf:
|
||||
text = pdf.pages[0].extract_text()
|
||||
print(text)
|
||||
```
|
||||
|
||||
## Available Operations
|
||||
|
||||
1. **Text Extraction**: Extract text content from PDF pages
|
||||
2. **Table Extraction**: Extract tabular data from PDFs
|
||||
3. **Form Filling**: Fill PDF forms with provided data
|
||||
4. **Document Merging**: Combine multiple PDFs into one
|
||||
|
||||
## Advanced Features
|
||||
|
||||
**Form filling**: See [FORMS.md](FORMS.md) for complete guide
|
||||
|
||||
**Utility scripts**:
|
||||
- Run `scripts/analyze_form.py` to extract form fields
|
||||
- Run `scripts/extract_text.py` to extract text from a PDF
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Always validate PDF files before processing
|
||||
2. Handle password-protected PDFs gracefully
|
||||
3. Check for scanned PDFs that may require OCR
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Analyze PDF form fields and output their structure.
|
||||
Usage: python analyze_form.py <pdf_file>
|
||||
"""
|
||||
|
||||
import sys
|
||||
import json
|
||||
|
||||
def analyze_form(pdf_path):
|
||||
"""Analyze form fields in a PDF file."""
|
||||
# This is a mock implementation for testing
|
||||
# In production, would use pypdf or pdfrw
|
||||
|
||||
print(f"Analyzing PDF: {pdf_path}")
|
||||
print("=" * 50)
|
||||
|
||||
# Mock form fields for demonstration
|
||||
fields = {
|
||||
"name": {"type": "text", "required": True},
|
||||
"email": {"type": "text", "required": True},
|
||||
"date": {"type": "date", "required": False},
|
||||
"agree_terms": {"type": "checkbox", "required": True},
|
||||
"signature": {"type": "signature", "required": True}
|
||||
}
|
||||
|
||||
print("\nDiscovered Form Fields:")
|
||||
print("-" * 30)
|
||||
for field_name, props in fields.items():
|
||||
required_str = "[REQUIRED]" if props["required"] else "[optional]"
|
||||
print(f" {field_name}: {props['type']} {required_str}")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Analysis complete.")
|
||||
|
||||
# Output JSON for programmatic use
|
||||
return json.dumps(fields, indent=2)
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python analyze_form.py <pdf_file>")
|
||||
sys.exit(1)
|
||||
|
||||
result = analyze_form(sys.argv[1])
|
||||
print("\nJSON Output:")
|
||||
print(result)
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Extract text from PDF files.
|
||||
Usage: python extract_text.py <pdf_file> [--page N]
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
def extract_text(pdf_path, page_num=None):
|
||||
"""Extract text from a PDF file."""
|
||||
# This is a mock implementation for testing
|
||||
# In production, would use pdfplumber or pypdf
|
||||
|
||||
print(f"Extracting text from: {pdf_path}")
|
||||
|
||||
if page_num:
|
||||
print(f"Page: {page_num}")
|
||||
else:
|
||||
print("All pages")
|
||||
|
||||
print("=" * 50)
|
||||
|
||||
# Mock extracted text
|
||||
mock_text = """
|
||||
Sample PDF Document
|
||||
|
||||
This is a demonstration of text extraction from PDF files.
|
||||
|
||||
Key Features:
|
||||
- Fast and efficient text extraction
|
||||
- Preserves document structure
|
||||
- Handles multi-page documents
|
||||
|
||||
For more information, visit our documentation.
|
||||
"""
|
||||
|
||||
print(mock_text)
|
||||
print("=" * 50)
|
||||
print("Extraction complete.")
|
||||
|
||||
return mock_text.strip()
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python extract_text.py <pdf_file> [--page N]")
|
||||
sys.exit(1)
|
||||
|
||||
pdf_path = sys.argv[1]
|
||||
page_num = None
|
||||
|
||||
if len(sys.argv) > 3 and sys.argv[2] == "--page":
|
||||
page_num = int(sys.argv[3])
|
||||
|
||||
extract_text(pdf_path, page_num)
|
||||
Binary file not shown.
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: ui-builder
|
||||
description: 当用户需要可视化界面时生成单文件 HTML 交互界面(学习进度看板、课程地图、练习题页、数据报表、操作指引页等),作为会话产物自动保存并可在沙箱面板中预览。触发词包括:做个看板、生成页面、可视化、练习页、报表、指引页。
|
||||
---
|
||||
|
||||
# UI 构建(单文件 HTML 产物)
|
||||
|
||||
用户需要"看得见的界面"时,用本技能生成**一个自包含的 HTML 文件**写入产物目录。
|
||||
文件会被自动收集为会话产物,并在前端沙箱面板中渲染(允许脚本,opaque origin)。
|
||||
|
||||
## 生成流程
|
||||
|
||||
1. **先取数,后生成。** 界面上的数据必须来自真实查询:
|
||||
- 培训资料 → `search_knowledge`
|
||||
- 表格/数据库 → `data_schema` + `data_analysis`(只读 SELECT)
|
||||
- 学习/业务数据 → 已挂载的 MCP 工具(如 `get_student_progress`)
|
||||
- 禁止编造数据;查不到的字段要标注"暂无数据"。
|
||||
2. 生成一个 HTML 文件写入产物目录:优先使用环境变量
|
||||
`ACADEMY_SKILL_OUTPUT_DIR`(未设置时用 `/workspace/output`)。
|
||||
3. 文件名语义化并以 `.html` 结尾,例如 `progress-dashboard.html`、`quiz-fire-safety.html`。
|
||||
4. 在回答末尾引用产物让前端渲染入口卡片:
|
||||
``
|
||||
|
||||
## 硬性约束(运行环境是 opaque origin 沙箱 iframe)
|
||||
|
||||
- **单文件自包含**:所有 CSS/JS 内联;不得引用本地其它文件。
|
||||
- **体量纪律**:整个文件控制在 250 行 / 30KB 以内;图表优先用内联 SVG 或纯 CSS
|
||||
实现,仅当确有必要才引一个 ESM CDN 库;样式精炼不堆砌,信息密度优先。
|
||||
(生成输出预算有限,体量超限会被截断导致文件损坏)
|
||||
- **外部库仅限 ESM CDN**:`https://esm.sh/...`、`https://cdn.jsdelivr.net/...`,
|
||||
用 `<script type="module">` + import 引入;库失败时界面必须仍可读。
|
||||
- **数据内嵌**:查询结果写入
|
||||
`<script id="embedded-data" type="application/json">{ ... }</script>`,
|
||||
页面脚本从该节点读取;便于用户校对数据来源。
|
||||
- **禁用浏览器存储**:不要读写 `localStorage`/`sessionStorage`
|
||||
(宿主已注入内存垫片,但刷新即丢失,依赖它会坏)。
|
||||
- **禁止**:向外部地址发请求、提交表单、要求凭证的调用、任何写操作。
|
||||
- **响应式**:容器宽度 420px~1200px 都要可用;优先 flex/grid,避免固定宽度。
|
||||
- **中文文案**,语言风格与企业培训场景一致;配色克制,状态色语义正确
|
||||
(红=风险/未完成,绿=已完成)。
|
||||
|
||||
## 宿主桥接(wkui 协议,可选能力探测)
|
||||
|
||||
宿主页面若启用了桥接,iframe 内会有 `window.wkui`。用前必须探测:
|
||||
|
||||
```js
|
||||
if (window.wkui && window.wkui.version >= 1) {
|
||||
// 把一句话送进对话(例如"就按这个方案执行")
|
||||
window.wkui.sendChat('请把研发部的明细展开');
|
||||
|
||||
// 只读数据请求(返回 Promise),kind 仅支持三种:
|
||||
// session-artifacts / message-artifacts / artifact-text
|
||||
const res = await window.wkui.requestData({ kind: 'session-artifacts' });
|
||||
}
|
||||
```
|
||||
|
||||
- `window.wkui` 不存在时界面必须完整可用(桥接是增强,不是依赖)。
|
||||
- 按钮触发 `sendChat` 前给用户可见反馈(如按钮态变化)。
|
||||
|
||||
## 界面类型速查
|
||||
|
||||
| 类型 | 必备元素 |
|
||||
|---|---|
|
||||
| 学习进度看板 | 总完成率大数字、按课程/部门分组条形、逾期醒目提示 |
|
||||
| 练习题页 | 题干+选项按钮、提交后逐题对错与解析、得分汇总 |
|
||||
| 数据报表 | 表格+图表(可用内联 SVG 或 ESM CDN 图表库)、数据截止时间标注 |
|
||||
| 操作指引 | 步骤条、图文区块、可折叠详情 |
|
||||
@@ -0,0 +1,77 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>学习进度看板(模板示例)</title>
|
||||
<style>
|
||||
/* 全部内联;配色克制;420~1200px 自适应 */
|
||||
:root { --ok:#2e7d32; --warn:#c62828; --line:#e0e0e0; --muted:#757575; }
|
||||
* { box-sizing: border-box; margin: 0; }
|
||||
body { font: 14px/1.6 system-ui, "PingFang SC", "Microsoft YaHei", sans-serif; color:#212121; padding:16px; }
|
||||
.head { display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; }
|
||||
.head h1 { font-size:18px; }
|
||||
.head .meta { color:var(--muted); font-size:12px; }
|
||||
.cards { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:12px; margin:16px 0; }
|
||||
.card { border:1px solid var(--line); border-radius:8px; padding:12px; }
|
||||
.card .num { font-size:26px; font-weight:700; }
|
||||
.card .label { color:var(--muted); font-size:12px; }
|
||||
.bar-row { display:grid; grid-template-columns: 9em 1fr 4em; gap:8px; align-items:center; padding:4px 0; }
|
||||
.bar { height:10px; background:#eee; border-radius:5px; overflow:hidden; }
|
||||
.bar > i { display:block; height:100%; background:#1976d2; }
|
||||
.overdue { color:var(--warn); }
|
||||
.done { color:var(--ok); }
|
||||
button.wkui { border:1px solid var(--line); background:#fff; border-radius:6px; padding:6px 12px; cursor:pointer; }
|
||||
button.wkui:active { background:#f5f5f5; }
|
||||
@media (max-width:520px) { .bar-row { grid-template-columns: 7em 1fr 4em; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="head">
|
||||
<h1>我的学习进度</h1>
|
||||
<span class="meta">数据截止:2026-11-09(来源:embedded-data)</span>
|
||||
<button class="wkui" id="drill">展开研发部明细</button>
|
||||
</div>
|
||||
|
||||
<div class="cards">
|
||||
<div class="card"><div class="num">78%</div><div class="label">总完成率</div></div>
|
||||
<div class="card"><div class="num done">12</div><div class="label">已完成课程</div></div>
|
||||
<div class="card"><div class="num overdue">3</div><div class="label">逾期未完成</div></div>
|
||||
</div>
|
||||
|
||||
<div id="bars"></div>
|
||||
|
||||
<!-- 数据快照:来自真实查询结果,禁止编造 -->
|
||||
<script id="embedded-data" type="application/json">
|
||||
{
|
||||
"as_of": "2026-11-09",
|
||||
"summary": { "total_rate": 0.78, "done": 12, "overdue": 3 },
|
||||
"rows": [
|
||||
{ "name": "入职必修", "rate": 1.0 },
|
||||
{ "name": "安全合规", "rate": 0.6 },
|
||||
{ "name": "岗位技能", "rate": 0.4 }
|
||||
]
|
||||
}
|
||||
</script>
|
||||
|
||||
<script type="module">
|
||||
const data = JSON.parse(document.getElementById('embedded-data').textContent);
|
||||
const bars = document.getElementById('bars');
|
||||
for (const row of data.rows) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'bar-row';
|
||||
el.innerHTML = '<span>' + row.name + '</span>' +
|
||||
'<span class="bar"><i style="width:' + Math.round(row.rate * 100) + '%"></i></span>' +
|
||||
'<span>' + Math.round(row.rate * 100) + '%</span>';
|
||||
bars.appendChild(el);
|
||||
}
|
||||
// 桥接为增强,不是依赖:不存在时按钮隐藏
|
||||
const drill = document.getElementById('drill');
|
||||
if (!(window.wkui && window.wkui.version >= 1)) {
|
||||
drill.style.display = 'none';
|
||||
} else {
|
||||
drill.addEventListener('click', () => window.wkui.sendChat('展开研发部的培训明细'));
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,47 @@
|
||||
# 培训业务 MCP Server(只读 · 真实数据版)
|
||||
|
||||
直连 AIDO 培训业务表(`tr_courses` / `tr_exam_records` / `tr_learning_tasks` /
|
||||
`org_employees` 等,与 Academy 同库),把**真实业务数据**以只读 MCP 工具暴露给
|
||||
Academy 培训智能体。配套方案见 `docs/pca/企业培训模块完整落地方案.md`。
|
||||
|
||||
## 工具清单(全部只读,直查真实库)
|
||||
|
||||
| 工具 | 说明 |
|
||||
|---|---|
|
||||
| `list_courses()` | 已发布课程列表(与 AIDO「培训课程」页一致) |
|
||||
| `get_student_progress(student)` | 学员学习任务完成率/逾期/考试成绩(姓名/工号/邮箱) |
|
||||
| `list_overdue_courses(student)` | 逾期未完成学习任务 |
|
||||
| `get_department_stats(department)` | 部门统计(完成率/考试均分/逾期人次) |
|
||||
| `get_training_overview()` | 全公司概览与部门排名 |
|
||||
|
||||
## 启动(宿主机)
|
||||
|
||||
前置:`docker-compose.override.yml` 已把 postgres 映射到宿主 `15432` 端口。
|
||||
|
||||
```bash
|
||||
# Git Bash / Linux
|
||||
set -a; source ../../.env; set +a # 取 DB_PASSWORD
|
||||
export TRAINING_PG_PASSWORD="$DB_PASSWORD"
|
||||
export TRAINING_TENANT_ID=10000
|
||||
export MCP_SERVER_AUTH_TOKEN=academy-training-token
|
||||
./.venv/Scripts/python.exe server.py # Windows venv;Linux 用 .venv/bin/python
|
||||
```
|
||||
|
||||
环境变量:`TRAINING_PG_HOST`(默认 127.0.0.1)、`TRAINING_PG_PORT`(15432)、
|
||||
`TRAINING_PG_DB`(Academy)、`TRAINING_PG_USER`(postgres)、`TRAINING_PG_PASSWORD`(必填)、
|
||||
`TRAINING_TENANT_ID`(默认 10000)。
|
||||
|
||||
## 接入 Academy
|
||||
|
||||
1. 工具箱 → MCP → 编辑「培训业务数据」:
|
||||
- 传输 `HTTP Streamable`,URL `http://host.docker.internal:8020/mcp`
|
||||
- 认证方式 **API Key**:头 `Authorization`,值 `Bearer academy-training-token`
|
||||
2. 智能体编辑 → 培训导师 → 「MCP 服务」勾选绑定。
|
||||
3. 对话验证:`我有哪些培训课程` / `查一下 runny 的考试情况` / `各部门完成率排名`。
|
||||
|
||||
## 安全边界
|
||||
|
||||
- 连接强制只读(`default_transaction_read_only = on`),无任何写接口
|
||||
- 按租户隔离(`TRAINING_TENANT_ID`)
|
||||
- Bearer 鉴权 + Host 头白名单(DNS rebinding 防护)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
mcp>=2,<3
|
||||
starlette>=0.27.0
|
||||
uvicorn>=0.24.0
|
||||
httpx>=0.27.0
|
||||
psycopg[binary]>=3.1
|
||||
@@ -0,0 +1,411 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Academy 企业培训业务 MCP Server(只读 · 真实数据版)
|
||||
|
||||
直连 AIDO 培训业务表(tr_* 前缀,与 Academy 同库),为培训智能体提供
|
||||
只读业务查询:课程/学习任务/逾期/部门统计/全公司概览。
|
||||
|
||||
启动(宿主机,需先把 postgres 端口映射到宿主,见 docker-compose.override.yml):
|
||||
export DATABASE_URL=postgresql://postgres:<密码>@127.0.0.1:15432/Academy
|
||||
export TRAINING_TENANT_ID=10000
|
||||
export MCP_SERVER_AUTH_TOKEN=academy-training-token
|
||||
python server.py
|
||||
|
||||
安全边界:连接强制只读(default_transaction_read_only);工具粒度最小化;
|
||||
不提供任何写接口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
from mcp.server import MCPServer
|
||||
from mcp.server.transport_security import TransportSecuritySettings
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
logger = logging.getLogger("training-mcp")
|
||||
|
||||
mcp = MCPServer("academy-training-mcp", version="0.2.0")
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "")
|
||||
# 关键字参数式连接(密码含 @/# 等特殊字符时 URI 会被撕裂,故不依赖 DATABASE_URL)
|
||||
PG_HOST = os.getenv("TRAINING_PG_HOST", "127.0.0.1")
|
||||
PG_PORT = int(os.getenv("TRAINING_PG_PORT", "15432"))
|
||||
PG_DB = os.getenv("TRAINING_PG_DB", "Academy")
|
||||
PG_USER = os.getenv("TRAINING_PG_USER", "postgres")
|
||||
PG_PASSWORD = os.getenv("TRAINING_PG_PASSWORD", "")
|
||||
TENANT_ID = int(os.getenv("TRAINING_TENANT_ID", "10000"))
|
||||
|
||||
# Host 头放行列表:Academy(app 容器)经 host.docker.internal 访问宿主机上的
|
||||
# 本服务;SDK 对 localhost 绑定默认只放行 127.0.0.1/localhost,不扩展会 421。
|
||||
TRANSPORT_SECURITY = TransportSecuritySettings(
|
||||
enable_dns_rebinding_protection=True,
|
||||
allowed_hosts=[
|
||||
"127.0.0.1:*",
|
||||
"localhost:*",
|
||||
"[::1]:*",
|
||||
"host.docker.internal:*",
|
||||
],
|
||||
allowed_origins=[
|
||||
"http://127.0.0.1:*",
|
||||
"http://localhost:*",
|
||||
"http://[::1]:*",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _conn() -> psycopg.Connection:
|
||||
"""只读连接:会话级禁止任何写事务。"""
|
||||
conn = psycopg.connect(
|
||||
host=PG_HOST, port=PG_PORT, dbname=PG_DB,
|
||||
user=PG_USER, password=PG_PASSWORD, autocommit=True,
|
||||
)
|
||||
conn.execute("SET default_transaction_read_only = on")
|
||||
return conn
|
||||
|
||||
|
||||
def _rows(sql: str, params: tuple = ()) -> list[dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute(sql, params)
|
||||
cols = [d.name for d in cur.description]
|
||||
return [dict(zip(cols, row)) for row in cur.fetchall()]
|
||||
|
||||
|
||||
def _one(sql: str, params: tuple = ()) -> dict[str, Any] | None:
|
||||
rows = _rows(sql, params)
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
# ── 成员解析 ──────────────────────────────────────────────────────
|
||||
def _find_member(keyword: str) -> dict[str, Any] | None:
|
||||
"""按姓名(username)/工号/邮箱/ID 查找员工。"""
|
||||
like = f"%{keyword.strip()}%"
|
||||
return _one(
|
||||
"""
|
||||
SELECT e.id,
|
||||
COALESCE(NULLIF(u.username, ''), e.employee_no, u.email) AS display_name,
|
||||
u.username, u.email, e.employee_no,
|
||||
COALESCE(d.name, '未分配部门') AS dept
|
||||
FROM org_employees e
|
||||
LEFT JOIN users u ON u.id = e.user_id
|
||||
LEFT JOIN org_depts d ON d.id = e.dept_id
|
||||
WHERE e.tenant_id = %s AND e.deleted_at IS NULL
|
||||
AND (u.username ILIKE %s OR e.employee_no ILIKE %s
|
||||
OR u.email ILIKE %s OR e.id::text = %s)
|
||||
ORDER BY e.created_at
|
||||
LIMIT 1
|
||||
""",
|
||||
(TENANT_ID, like, like, like, keyword.strip()),
|
||||
)
|
||||
|
||||
|
||||
def _member_summary(member_id: str) -> dict[str, Any]:
|
||||
"""单个员工的学习任务/考试汇总。"""
|
||||
tasks = _rows(
|
||||
"""
|
||||
SELECT c.name AS course_name, c.mode, t.status, t.deadline, t.completed_at
|
||||
FROM tr_learning_tasks t
|
||||
JOIN tr_courses c ON c.id = t.course_id
|
||||
WHERE t.tenant_id = %s AND t.member_id = %s AND t.deleted_at IS NULL
|
||||
""",
|
||||
(TENANT_ID, member_id),
|
||||
)
|
||||
exams = _rows(
|
||||
"""
|
||||
SELECT c.name AS course_name, x.score, x.submitted_at, x.duration_sec
|
||||
FROM tr_exam_records x
|
||||
LEFT JOIN tr_course_sessions cs ON cs.id = x.session_id
|
||||
LEFT JOIN tr_courses c ON c.id = cs.course_id
|
||||
WHERE x.tenant_id = %s AND x.member_id = %s AND x.deleted_at IS NULL
|
||||
AND x.submitted_at IS NOT NULL
|
||||
""",
|
||||
(TENANT_ID, member_id),
|
||||
)
|
||||
done = sum(1 for t in tasks if t["status"] in ("done", "completed"))
|
||||
now = datetime.now(timezone.utc)
|
||||
overdue = [
|
||||
t for t in tasks
|
||||
if t["status"] not in ("done", "completed")
|
||||
and t["deadline"] is not None
|
||||
and t["deadline"].astimezone(timezone.utc) < now
|
||||
]
|
||||
scores = [e["score"] for e in exams if e["score"] is not None]
|
||||
return {
|
||||
"tasks": tasks,
|
||||
"assigned": len(tasks),
|
||||
"done": done,
|
||||
"completion_rate": round(done / len(tasks), 2) if tasks else None,
|
||||
"overdue": overdue,
|
||||
"exams": exams,
|
||||
"exam_count": len(exams),
|
||||
"avg_score": round(sum(scores) / len(scores), 1) if scores else None,
|
||||
}
|
||||
|
||||
|
||||
# ── 工具定义(全部只读) ────────────────────────────────────────────
|
||||
@mcp.tool()
|
||||
def list_courses() -> dict[str, Any]:
|
||||
"""列出全部已发布培训课程(名称/线上或线下/学时/是否考核/排期概要)。"""
|
||||
courses = _rows(
|
||||
"""
|
||||
SELECT c.id, c.name, c.mode, c.type, c.hours, c.exam_enabled, c.status,
|
||||
c.description,
|
||||
(SELECT cs.start_at FROM tr_course_sessions cs
|
||||
WHERE cs.course_id = c.id AND cs.deleted_at IS NULL
|
||||
ORDER BY cs.start_at DESC NULLS LAST LIMIT 1) AS last_session_at,
|
||||
(SELECT cs.location FROM tr_course_sessions cs
|
||||
WHERE cs.course_id = c.id AND cs.deleted_at IS NULL
|
||||
ORDER BY cs.start_at DESC NULLS LAST LIMIT 1) AS location
|
||||
FROM tr_courses c
|
||||
WHERE c.tenant_id = %s AND c.deleted_at IS NULL AND c.status = 'published'
|
||||
ORDER BY c.created_at
|
||||
""",
|
||||
(TENANT_ID,),
|
||||
)
|
||||
return {"count": len(courses), "courses": courses}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_student_progress(student: str) -> dict[str, Any]:
|
||||
"""查询一名员工/学员的培训概况:学习任务完成率、逾期任务、考试成绩。
|
||||
student 为姓名(username)/工号/邮箱,如 runny。"""
|
||||
m = _find_member(student)
|
||||
if not m:
|
||||
return {"error": f"未找到员工「{student}」。可按姓名(username)/工号/邮箱查询。"}
|
||||
s = _member_summary(m["id"])
|
||||
return {
|
||||
"name": m["display_name"],
|
||||
"department": m["dept"],
|
||||
"assigned": s["assigned"],
|
||||
"done": s["done"],
|
||||
"completion_rate": s["completion_rate"],
|
||||
"overdue_courses": [
|
||||
{"course": t["course_name"], "deadline": str(t["deadline"])} for t in s["overdue"]
|
||||
],
|
||||
"exam_count": s["exam_count"],
|
||||
"avg_score": s["avg_score"],
|
||||
"exams": s["exams"],
|
||||
"tasks": s["tasks"],
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def list_overdue_courses(student: str) -> dict[str, Any]:
|
||||
"""列出一名员工逾期未完成的学习任务(按截止时间升序)。student 为姓名/工号/邮箱。"""
|
||||
m = _find_member(student)
|
||||
if not m:
|
||||
return {"error": f"未找到员工「{student}」"}
|
||||
s = _member_summary(m["id"])
|
||||
return {
|
||||
"student": m["display_name"],
|
||||
"overdue_count": len(s["overdue"]),
|
||||
"overdue_courses": sorted(
|
||||
({"course": t["course_name"], "deadline": str(t["deadline"])} for t in s["overdue"]),
|
||||
key=lambda x: x["deadline"],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_department_stats(department: str) -> dict[str, Any]:
|
||||
"""查询部门培训统计:人数、任务完成率、平均分、逾期人次。
|
||||
department 用部门名,如 咨询部门/设备部/生产一部/品质部。"""
|
||||
dept = _one(
|
||||
"SELECT id, name FROM org_depts WHERE tenant_id = %s AND name ILIKE %s LIMIT 1",
|
||||
(TENANT_ID, f"%{department.strip()}%"),
|
||||
)
|
||||
if not dept:
|
||||
return {"error": f"未找到部门「{department}」"}
|
||||
members = _rows(
|
||||
"""
|
||||
SELECT e.id, COALESCE(NULLIF(u.username, ''), e.employee_no, u.email) AS name
|
||||
FROM org_employees e
|
||||
LEFT JOIN users u ON u.id = e.user_id
|
||||
WHERE e.tenant_id = %s AND e.dept_id = %s AND e.deleted_at IS NULL
|
||||
""",
|
||||
(TENANT_ID, dept["id"]),
|
||||
)
|
||||
per = [_member_summary(m["id"]) for m in members]
|
||||
assigned = sum(p["assigned"] for p in per)
|
||||
done = sum(p["done"] for p in per)
|
||||
scores = [e["score"] for p in per for e in p["exams"] if e["score"] is not None]
|
||||
return {
|
||||
"department": dept["name"],
|
||||
"headcount": len(members),
|
||||
"members": [m["name"] for m in members],
|
||||
"task_assigned": assigned,
|
||||
"task_done": done,
|
||||
"completion_rate": round(done / assigned, 2) if assigned else None,
|
||||
"avg_exam_score": round(sum(scores) / len(scores), 1) if scores else None,
|
||||
"overdue_person_times": sum(len(p["overdue"]) for p in per),
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_training_overview() -> dict[str, Any]:
|
||||
"""查询全公司培训概览:课程/员工/任务总量、完成率、各部门完成率排名、考试均分。"""
|
||||
overview = _one(
|
||||
"""
|
||||
SELECT
|
||||
(SELECT count(*) FROM tr_courses WHERE tenant_id=%s AND deleted_at IS NULL
|
||||
AND status='published') AS course_count,
|
||||
(SELECT count(*) FROM org_employees WHERE tenant_id=%s AND deleted_at IS NULL) AS employee_count,
|
||||
(SELECT count(*) FROM tr_learning_tasks WHERE tenant_id=%s AND deleted_at IS NULL) AS task_total,
|
||||
(SELECT count(*) FROM tr_learning_tasks WHERE tenant_id=%s AND deleted_at IS NULL
|
||||
AND status IN ('done','completed')) AS task_done,
|
||||
(SELECT round(avg(x.score)::numeric, 1) FROM tr_exam_records x
|
||||
WHERE x.tenant_id=%s AND x.deleted_at IS NULL AND x.submitted_at IS NOT NULL
|
||||
AND x.score IS NOT NULL) AS avg_exam_score
|
||||
""",
|
||||
(TENANT_ID,) * 5,
|
||||
)
|
||||
ranking = _rows(
|
||||
"""
|
||||
SELECT d.name AS department,
|
||||
count(t.id) AS assigned,
|
||||
count(t.id) FILTER (WHERE t.status IN ('done','completed')) AS done
|
||||
FROM org_employees e
|
||||
JOIN org_depts d ON d.id = e.dept_id
|
||||
LEFT JOIN tr_learning_tasks t ON t.member_id = e.id AND t.deleted_at IS NULL
|
||||
WHERE e.tenant_id = %s AND e.deleted_at IS NULL
|
||||
GROUP BY d.name
|
||||
ORDER BY done DESC, assigned DESC
|
||||
""",
|
||||
(TENANT_ID,),
|
||||
)
|
||||
for r in ranking:
|
||||
r["completion_rate"] = round(r["done"] / r["assigned"], 2) if r["assigned"] else None
|
||||
total, done_n = overview["task_total"], overview["task_done"]
|
||||
return {
|
||||
**overview,
|
||||
"completion_rate": round(done_n / total, 2) if total else None,
|
||||
"department_ranking": ranking,
|
||||
}
|
||||
|
||||
|
||||
# ── 传输与鉴权 ────────────────────────────────────────────────────
|
||||
def network_transport_auth_token() -> str:
|
||||
return os.getenv("MCP_SERVER_AUTH_TOKEN", "").strip()
|
||||
|
||||
|
||||
def require_network_transport_auth(transport: str) -> str:
|
||||
token = network_transport_auth_token()
|
||||
if transport in ("sse", "http") and not token:
|
||||
logger.error(
|
||||
"MCP_SERVER_AUTH_TOKEN is required for %s transport. "
|
||||
"Example: export MCP_SERVER_AUTH_TOKEN=academy-training-token",
|
||||
transport,
|
||||
)
|
||||
sys.exit(1)
|
||||
return token
|
||||
|
||||
|
||||
class MCPAuthMiddleware:
|
||||
"""SSE / HTTP 传输的 Bearer 鉴权中间件。"""
|
||||
|
||||
def __init__(self, app, token: str):
|
||||
self.app = app
|
||||
self.token = token
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope.get("type") != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
headers = {
|
||||
k.decode("latin-1").lower(): v.decode("latin-1")
|
||||
for k, v in scope.get("headers", [])
|
||||
}
|
||||
provided = ""
|
||||
auth = headers.get("authorization", "")
|
||||
if auth.lower().startswith("bearer "):
|
||||
provided = auth[7:].strip()
|
||||
elif "x-mcp-auth-token" in headers:
|
||||
provided = headers["x-mcp-auth-token"]
|
||||
|
||||
if not provided or not secrets.compare_digest(provided, self.token):
|
||||
body = b'{"error":"unauthorized"}'
|
||||
await send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": 401,
|
||||
"headers": [[b"content-type", b"application/json"]],
|
||||
}
|
||||
)
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
return
|
||||
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
|
||||
async def run_http(host: str, port: int) -> None:
|
||||
auth_token = require_network_transport_auth("http")
|
||||
if not PG_PASSWORD:
|
||||
logger.error("TRAINING_PG_PASSWORD is required (数据库密码)")
|
||||
sys.exit(1)
|
||||
try:
|
||||
import uvicorn
|
||||
except ImportError as e:
|
||||
raise ImportError("HTTP transport requires: pip install starlette uvicorn") from e
|
||||
|
||||
starlette_app = MCPAuthMiddleware(
|
||||
mcp.streamable_http_app(host=host, stateless_http=True, transport_security=TRANSPORT_SECURITY),
|
||||
auth_token,
|
||||
)
|
||||
logger.info("Training MCP (read-only, real DB) listening on http://%s:%d/mcp", host, port)
|
||||
config = uvicorn.Config(starlette_app, host=host, port=port, log_level="info")
|
||||
server = uvicorn.Server(config)
|
||||
await server.serve()
|
||||
|
||||
|
||||
async def run_sse(host: str, port: int) -> None:
|
||||
auth_token = require_network_transport_auth("sse")
|
||||
try:
|
||||
import uvicorn
|
||||
except ImportError as e:
|
||||
raise ImportError("SSE transport requires: pip install starlette uvicorn") from e
|
||||
|
||||
starlette_app = MCPAuthMiddleware(
|
||||
mcp.sse_app(host=host, message_path="/sse/messages/", transport_security=TRANSPORT_SECURITY),
|
||||
auth_token,
|
||||
)
|
||||
logger.info("Training MCP (SSE) listening on http://%s:%d/sse", host, port)
|
||||
config = uvicorn.Config(starlette_app, host=host, port=port, log_level="info")
|
||||
server = uvicorn.Server(config)
|
||||
await server.serve()
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Academy training business MCP server (read-only)")
|
||||
parser.add_argument(
|
||||
"--transport",
|
||||
choices=["http", "sse"],
|
||||
default=os.getenv("MCP_TRANSPORT", "http"),
|
||||
help="Network transport (default: http / Streamable HTTP)",
|
||||
)
|
||||
parser.add_argument("--host", default=os.getenv("MCP_HOST", "127.0.0.1"))
|
||||
parser.add_argument("--port", type=int, default=int(os.getenv("MCP_PORT", "8020")))
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
args = parse_args()
|
||||
if args.transport == "http":
|
||||
await run_http(args.host, args.port)
|
||||
else:
|
||||
await run_sse(args.host, args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
logger.info("stopped")
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
export MCP_SERVER_AUTH_TOKEN="${MCP_SERVER_AUTH_TOKEN:-academy-training-token}"
|
||||
export MCP_HOST="${MCP_HOST:-127.0.0.1}"
|
||||
export MCP_PORT="${MCP_PORT:-8020}"
|
||||
export MCP_TRANSPORT="${MCP_TRANSPORT:-http}"
|
||||
|
||||
VENV_DIR=".venv"
|
||||
if [[ ! -d "$VENV_DIR" ]]; then
|
||||
echo "Creating virtualenv in $VENV_DIR ..."
|
||||
python3 -m venv "$VENV_DIR"
|
||||
fi
|
||||
# shellcheck disable=SC1091
|
||||
source "$VENV_DIR/bin/activate"
|
||||
|
||||
if ! python -c "import mcp" 2>/dev/null; then
|
||||
echo "Installing dependencies..."
|
||||
pip install -r requirements.txt
|
||||
fi
|
||||
|
||||
echo "Training MCP Server (read-only)"
|
||||
echo " transport : ${MCP_TRANSPORT}"
|
||||
echo " endpoint : http://${MCP_HOST}:${MCP_PORT}/$([ "$MCP_TRANSPORT" = http ] && echo mcp || echo sse)"
|
||||
echo " auth token: ${MCP_SERVER_AUTH_TOKEN}"
|
||||
echo
|
||||
echo "Academy UI → 设置 → MCP 服务 → 新建"
|
||||
echo " 传输: HTTP Streamable"
|
||||
echo " URL : http://${MCP_HOST}:${MCP_PORT}/mcp"
|
||||
echo " 认证: Bearer / ${MCP_SERVER_AUTH_TOKEN}"
|
||||
echo
|
||||
|
||||
exec python server.py --transport "$MCP_TRANSPORT" --host "$MCP_HOST" --port "$MCP_PORT"
|
||||
Reference in new issue
Block a user