feat: 新增 ekb-mcp — 易快报 MCP Server (TS + Bun)
完整迁移 SealAI 和 Platform 域: Core: - 多企业配置管理 (enterprises/*.json) - Token 自动刷新(内存 + 持久化 ~/.cache/ekb-mcp/tokens.json) - 动态域名支持 - 统一错误处理 Auth: - SealAI: SSO → JWT 换取 - EASO: 四步认证链路 (hose-token → UNITY JWT → EASO realm token) - Piper: 三步认证链路 (hose-token → EASO JWT) SealAI (12 tools): - 用户身份、计费查询 - 审核规则 CRUD - 规则版本发布 - 知识文档 CRUD Platform (2 tools): - 自建应用列表 - 工作流列表(EASO 认证) 废弃: - HAB 智能审核 (Agent/Rule) - AI 审批配置 技术栈: Bun + ky + Zod + MCP SDK
This commit is contained in:
1 parent
39122c83eb
commit
79af2c1363
26 files changed
+1784
No files matched your search
@@ -0,0 +1 @@
|
||||
../../CLAUDE.md
|
||||
@@ -0,0 +1,34 @@
|
||||
# dependencies (bun install)
|
||||
node_modules
|
||||
|
||||
# output
|
||||
out
|
||||
dist
|
||||
*.tgz
|
||||
|
||||
# code coverage
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# logs
|
||||
logs
|
||||
_.log
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# caches
|
||||
.eslintcache
|
||||
.cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
description: Use Bun instead of Node.js, npm, pnpm, or vite.
|
||||
globs: "*.ts, *.tsx, *.html, *.css, *.js, *.jsx, package.json"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Default to using Bun instead of Node.js.
|
||||
|
||||
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
|
||||
- Use `bun test` instead of `jest` or `vitest`
|
||||
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
|
||||
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
|
||||
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
|
||||
- Use `bunx <package> <command>` instead of `npx <package> <command>`
|
||||
- Bun automatically loads .env, so don't use dotenv.
|
||||
|
||||
## APIs
|
||||
|
||||
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
|
||||
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
|
||||
- `Bun.redis` for Redis. Don't use `ioredis`.
|
||||
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
|
||||
- `WebSocket` is built-in. Don't use `ws`.
|
||||
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
|
||||
- Bun.$`ls` instead of execa.
|
||||
|
||||
## Testing
|
||||
|
||||
Use `bun test` to run tests.
|
||||
|
||||
```ts#index.test.ts
|
||||
import { test, expect } from "bun:test";
|
||||
|
||||
test("hello world", () => {
|
||||
expect(1).toBe(1);
|
||||
});
|
||||
```
|
||||
|
||||
## Frontend
|
||||
|
||||
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
|
||||
|
||||
Server:
|
||||
|
||||
```ts#index.ts
|
||||
import index from "./index.html"
|
||||
|
||||
Bun.serve({
|
||||
routes: {
|
||||
"/": index,
|
||||
"/api/users/:id": {
|
||||
GET: (req) => {
|
||||
return new Response(JSON.stringify({ id: req.params.id }));
|
||||
},
|
||||
},
|
||||
},
|
||||
// optional websocket support
|
||||
websocket: {
|
||||
open: (ws) => {
|
||||
ws.send("Hello, world!");
|
||||
},
|
||||
message: (ws, message) => {
|
||||
ws.send(message);
|
||||
},
|
||||
close: (ws) => {
|
||||
// handle close
|
||||
}
|
||||
},
|
||||
development: {
|
||||
hmr: true,
|
||||
console: true,
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
|
||||
|
||||
```html#index.html
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, world!</h1>
|
||||
<script type="module" src="./frontend.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
With the following `frontend.tsx`:
|
||||
|
||||
```tsx#frontend.tsx
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
// import .css files directly and it works
|
||||
import './index.css';
|
||||
|
||||
const root = createRoot(document.body);
|
||||
|
||||
export default function Frontend() {
|
||||
return <h1>Hello, world!</h1>;
|
||||
}
|
||||
|
||||
root.render(<Frontend />);
|
||||
```
|
||||
|
||||
Then, run index.ts
|
||||
|
||||
```sh
|
||||
bun --hot ./index.ts
|
||||
```
|
||||
|
||||
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.mdx`.
|
||||
@@ -0,0 +1,90 @@
|
||||
# ekb-mcp
|
||||
|
||||
易快报(ekuaibao)MCP Server,面向 AI Agent 设计。
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
## 配置
|
||||
|
||||
在 `enterprises/` 目录下创建企业配置:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "corp-id",
|
||||
"name": "企业名称",
|
||||
"credentials": {
|
||||
"accessToken": "your-access-token",
|
||||
"corpId": "your-corp-id",
|
||||
"staffId": "your-staff-id"
|
||||
},
|
||||
"auth": {
|
||||
"refreshTtl": 300
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
bun run dev # 开发模式(热重载)
|
||||
bun run start # 生产模式
|
||||
```
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
src/
|
||||
├── core/ # 基础设施
|
||||
│ ├── config/ # 企业配置管理
|
||||
│ ├── auth/ # 认证(Token 缓存/刷新)
|
||||
│ │ ├── sealai.ts # SealAI SSO → JWT
|
||||
│ │ ├── easo.ts # EASO 四步认证
|
||||
│ │ └── piper.ts # Piper 三步认证
|
||||
│ └── http/ # HTTP 客户端工厂
|
||||
├── domains/ # 业务域
|
||||
│ ├── sealai/ # SealAI 域
|
||||
│ │ ├── types.ts
|
||||
│ │ ├── api.ts
|
||||
│ │ └── tools.ts
|
||||
│ └── platform/ # 自建应用/工作流域
|
||||
│ ├── types.ts
|
||||
│ ├── api.ts
|
||||
│ └── tools.ts
|
||||
└── server.ts # MCP Server 入口
|
||||
```
|
||||
|
||||
## 已迁移功能
|
||||
|
||||
### SealAI
|
||||
- [x] 认证(SSO → JWT,内存+持久化缓存)
|
||||
- [x] 用户身份查询
|
||||
- [x] 计费/订阅查询
|
||||
- [x] 审核规则 CRUD
|
||||
- [x] 规则版本发布
|
||||
- [x] 知识文档 CRUD
|
||||
|
||||
### Platform
|
||||
- [x] 自建应用列表
|
||||
- [x] EASO 四步认证
|
||||
- [x] Piper 三步认证
|
||||
- [x] 工作流列表/统计/配额/详情
|
||||
|
||||
### Core
|
||||
- [x] 多企业切换
|
||||
- [x] Token 自动刷新(内存 + 持久化)
|
||||
- [x] 动态域名配置
|
||||
|
||||
## 废弃功能
|
||||
- [ ] HAB 智能审核(Agent/Rule)— 业务废弃
|
||||
- [ ] AI 审批配置 — 业务废弃
|
||||
|
||||
## 技术栈
|
||||
|
||||
- **Runtime**: Bun
|
||||
- **HTTP Client**: ky
|
||||
- **Schema**: Zod
|
||||
- **MCP SDK**: @modelcontextprotocol/sdk
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "ekb-mcp",
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
|
||||
|
||||
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
|
||||
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "ID01Jdq2yIDnMr",
|
||||
"name": "测试企业",
|
||||
"credentials": {
|
||||
"accessToken": "yMRMo7AIkQpMm6Z0TtehS0",
|
||||
"corpId": "ID01Jdq2yIDnMr",
|
||||
"staffId": "ID01Jdq2yIDnMr:ID01KsDgHaH5nN"
|
||||
},
|
||||
"auth": {
|
||||
"refreshTtl": 300
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "ekb-mcp",
|
||||
"version": "0.1.0",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run --watch src/server.ts",
|
||||
"start": "bun run src/server.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"ky": "^2.0.2",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.3.14",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { getCorpTokens, setCorpTokens } from "../../core/auth/token-store.js";
|
||||
|
||||
const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
const EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
// 内存缓存
|
||||
const easoMemoryCache = new Map<string, { token: string; expiresAt: number }>();
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
async function fetchHoseToken(accessToken: string, corpId: string): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async function fetchUnityJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
return response.id || response.value || "";
|
||||
}
|
||||
|
||||
async function fetchEasoRealmToken(
|
||||
corpId: string,
|
||||
unityJwt: string,
|
||||
hoseToken: string
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EASO_BASE_URL}/api/realms/EASO`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
hoseaccesstoken: hoseToken,
|
||||
},
|
||||
})
|
||||
.json<{ value?: { accessToken?: string } }>();
|
||||
return response.value?.accessToken || "";
|
||||
}
|
||||
|
||||
export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
client: typeof ky;
|
||||
corpId: string;
|
||||
}> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:easo`;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = easoMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return {
|
||||
client: ky.create({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${mem.token}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: mem.hoseToken,
|
||||
},
|
||||
}),
|
||||
corpId: corp.credentials.corpId,
|
||||
};
|
||||
}
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId
|
||||
);
|
||||
const unityJwt = await fetchUnityJwt(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId,
|
||||
corp.credentials.staffId
|
||||
);
|
||||
const easoToken = await fetchEasoRealmToken(
|
||||
corp.credentials.corpId,
|
||||
unityJwt,
|
||||
hoseToken
|
||||
);
|
||||
|
||||
const entry = {
|
||||
token: easoToken,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
};
|
||||
|
||||
easoMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return {
|
||||
client: ky.create({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${easoToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
},
|
||||
}),
|
||||
corpId: corp.credentials.corpId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { CorpConfig } from "../config/types";
|
||||
|
||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
return {
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corpid: corp.credentials.corpId,
|
||||
staffid: corp.credentials.staffId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
const PIPER_BASE_URL = "https://piper.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
const EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
// 内存缓存
|
||||
const piperMemoryCache = new Map<
|
||||
string,
|
||||
{ jwt: string; hoseToken: string; expiresAt: number }
|
||||
>();
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
async function fetchHoseToken(accessToken: string, corpId: string): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async function fetchEasoJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
return response.id || response.value || "";
|
||||
}
|
||||
|
||||
export async function getPiperClient(
|
||||
corp: CorpConfig,
|
||||
platformId: string
|
||||
): Promise<typeof ky> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:${platformId}:piper`;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = piperMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return ky.create({
|
||||
prefixUrl: PIPER_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${mem.jwt}`,
|
||||
platformid: platformId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId
|
||||
);
|
||||
const easoJwt = await fetchEasoJwt(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId,
|
||||
corp.credentials.staffId
|
||||
);
|
||||
|
||||
const entry = {
|
||||
jwt: easoJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
};
|
||||
|
||||
piperMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return ky.create({
|
||||
prefixUrl: PIPER_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${easoJwt}`,
|
||||
platformid: platformId,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../config/types";
|
||||
import { TokenEntry } from "./types";
|
||||
import { getCorpTokens, setCorpTokens, clearCorpTokens } from "./token-store";
|
||||
|
||||
// 内存缓存
|
||||
const memoryCache = new Map<string, TokenEntry>();
|
||||
|
||||
function isExpired(entry: TokenEntry, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
export async function getSealaiToken(corp: CorpConfig): Promise<string> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:sealai`;
|
||||
|
||||
// 1. 检查内存缓存
|
||||
const mem = memoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return mem.token;
|
||||
}
|
||||
|
||||
// 2. 检查持久化缓存
|
||||
const stored = getCorpTokens(corp.id);
|
||||
if (stored?.sealai && !isExpired(stored.sealai, refreshTtl)) {
|
||||
memoryCache.set(cacheKey, stored.sealai);
|
||||
return stored.sealai.token;
|
||||
}
|
||||
|
||||
// 3. 重新换取
|
||||
const sealaiUrl = corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
const response = await ky
|
||||
.get(`${sealaiUrl}/api/auth/oauth2/session/oem-hosecloud`, {
|
||||
searchParams: {
|
||||
token: corp.credentials.accessToken,
|
||||
returnToken: "1",
|
||||
},
|
||||
})
|
||||
.json<{ token: string; expiresIn: number }>();
|
||||
|
||||
const entry: TokenEntry = {
|
||||
token: response.token,
|
||||
expiresAt: Date.now() + response.expiresIn * 1000,
|
||||
};
|
||||
|
||||
// 4. 更新内存 + 持久化
|
||||
memoryCache.set(cacheKey, entry);
|
||||
setCorpTokens(corp.id, {
|
||||
...stored,
|
||||
sealai: entry,
|
||||
});
|
||||
|
||||
return entry.token;
|
||||
}
|
||||
|
||||
export function clearSealaiToken(corpId: string): void {
|
||||
const cacheKey = `${corpId}:sealai`;
|
||||
memoryCache.delete(cacheKey);
|
||||
clearCorpTokens(corpId);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
||||
import { join, dirname } from "path";
|
||||
import { homedir } from "os";
|
||||
import { TokenStore, TokenStoreSchema } from "./types";
|
||||
|
||||
const TOKEN_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
"tokens.json"
|
||||
);
|
||||
|
||||
function ensureDir(path: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
}
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
try {
|
||||
const content = readFileSync(TOKEN_CACHE_PATH, "utf-8");
|
||||
return TokenStoreSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function saveTokenStore(store: TokenStore): void {
|
||||
ensureDir(TOKEN_CACHE_PATH);
|
||||
writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(store, null, 2));
|
||||
}
|
||||
|
||||
export function getCorpTokens(corpId: string): TokenStore[string] | undefined {
|
||||
const store = loadTokenStore();
|
||||
return store[corpId];
|
||||
}
|
||||
|
||||
export function setCorpTokens(corpId: string, tokens: TokenStore[string]): void {
|
||||
const store = loadTokenStore();
|
||||
store[corpId] = tokens;
|
||||
saveTokenStore(store);
|
||||
}
|
||||
|
||||
export function clearCorpTokens(corpId: string): void {
|
||||
const store = loadTokenStore();
|
||||
delete store[corpId];
|
||||
saveTokenStore(store);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const TokenEntrySchema = z.object({
|
||||
token: z.string(),
|
||||
expiresAt: z.number(), // timestamp (ms)
|
||||
});
|
||||
|
||||
export const CorpTokensSchema = z.object({
|
||||
sealai: TokenEntrySchema.optional(),
|
||||
eas: z.object({
|
||||
hoseToken: z.string(),
|
||||
unityJwt: z.string(),
|
||||
easToken: z.string(),
|
||||
expiresAt: z.number(),
|
||||
}).optional(),
|
||||
piper: z.object({
|
||||
hoseToken: z.string(),
|
||||
easJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export const TokenStoreSchema = z.record(z.string(), CorpTokensSchema);
|
||||
|
||||
export type TokenEntry = z.infer<typeof TokenEntrySchema>;
|
||||
export type CorpTokens = z.infer<typeof CorpTokensSchema>;
|
||||
export type TokenStore = z.infer<typeof TokenStoreSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readFileSync, readdirSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { CorpConfig, CorpConfigSchema } from "./types";
|
||||
|
||||
const ENTERPRISES_DIR = "./enterprises";
|
||||
|
||||
export function loadCorpConfigs(): CorpConfig[] {
|
||||
try {
|
||||
const files = readdirSync(ENTERPRISES_DIR).filter((f) =>
|
||||
f.endsWith(".json")
|
||||
);
|
||||
|
||||
return files.map((file) => {
|
||||
const content = readFileSync(join(ENTERPRISES_DIR, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
return CorpConfigSchema.parse(parsed);
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CorpConfig } from "./types";
|
||||
|
||||
export class CorpContext {
|
||||
private current: CorpConfig | null = null;
|
||||
private corps: Map<string, CorpConfig> = new Map();
|
||||
|
||||
constructor(corps: CorpConfig[]) {
|
||||
for (const corp of corps) {
|
||||
this.corps.set(corp.id, corp);
|
||||
}
|
||||
if (corps.length > 0) {
|
||||
this.current = corps[0];
|
||||
}
|
||||
}
|
||||
|
||||
getCurrent(): CorpConfig | null {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
switchCorp(corpId: string): boolean {
|
||||
const corp = this.corps.get(corpId);
|
||||
if (!corp) return false;
|
||||
this.current = corp;
|
||||
return true;
|
||||
}
|
||||
|
||||
listCorps(): Array<{ id: string; name: string; current: boolean }> {
|
||||
return Array.from(this.corps.values()).map((corp) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
current: corp.id === this.current?.id,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const CorpCredentialsSchema = z.object({
|
||||
accessToken: z.string(),
|
||||
corpId: z.string(),
|
||||
staffId: z.string(),
|
||||
});
|
||||
|
||||
export const CorpAuthConfigSchema = z.object({
|
||||
refreshTtl: z.number().default(300), // 提前多少秒刷新,默认 5 分钟
|
||||
});
|
||||
|
||||
export const CorpConfigSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
baseUrl: z.string().url().optional(), // 默认 https://app.ekuaibao.com
|
||||
sealaiUrl: z.string().optional(), // 默认 https://{corpId}.sealai.cc
|
||||
credentials: CorpCredentialsSchema,
|
||||
auth: CorpAuthConfigSchema.optional(),
|
||||
});
|
||||
|
||||
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
@@ -0,0 +1,22 @@
|
||||
export class EkbError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly code: string,
|
||||
public readonly status?: number
|
||||
) {
|
||||
super(message);
|
||||
this.name = "EkbError";
|
||||
}
|
||||
}
|
||||
|
||||
export class NotLoggedInError extends EkbError {
|
||||
constructor(message = "No corp selected") {
|
||||
super(message, "NOT_LOGGED_IN", 401);
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticationError extends EkbError {
|
||||
constructor(message = "Authentication failed") {
|
||||
super(message, "AUTH_FAILED", 401);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import ky, { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { getEkbHeaders } from "../auth/ekb.js";
|
||||
import { getSealaiToken, clearSealaiToken } from "../auth/sealai.js";
|
||||
|
||||
type ClientType = "ekb" | "sealai";
|
||||
|
||||
export async function createClient(
|
||||
corp: CorpConfig,
|
||||
type: ClientType
|
||||
): Promise<KyInstance> {
|
||||
if (type === "sealai") {
|
||||
const sealaiUrl =
|
||||
corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
return ky.create({
|
||||
prefix: sealaiUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${await getSealaiToken(corp)}`,
|
||||
},
|
||||
hooks: {
|
||||
beforeError: [
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
clearSealaiToken(corp.id);
|
||||
}
|
||||
return error;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return ky.create({
|
||||
prefix: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
headers: getEkbHeaders(corp),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { KyInstance } from "ky";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
WorkflowStatsSchema,
|
||||
WorkflowChargeSchema,
|
||||
WorkflowDetailSchema,
|
||||
} from "./types";
|
||||
|
||||
// Helper to unwrap { data: T } response
|
||||
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const json = await response.json();
|
||||
return schema.parse(json.data);
|
||||
}
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 自建应用 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listPlatforms(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<import("./types").Platform[]> {
|
||||
const response = await client.get("api/v2/datalink/platform/search", {
|
||||
searchParams: { scope: "enable", corpId },
|
||||
});
|
||||
const json = (await response.json()) as { items: unknown[] };
|
||||
return z.array(PlatformSchema).parse(json.items);
|
||||
}
|
||||
|
||||
// ── 工作流(EASO)─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listWorkflows(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string,
|
||||
page: number = 1,
|
||||
pageSize: number = 20
|
||||
): Promise<import("./types").WorkflowPage> {
|
||||
const response = await client.get("api/easo/pipelines/logs", {
|
||||
searchParams: {
|
||||
corpId,
|
||||
platformId,
|
||||
number: String(page),
|
||||
pageSize: String(pageSize),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowPageSchema);
|
||||
}
|
||||
|
||||
export async function getWorkflowStats(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
platformId: string
|
||||
): Promise<import("./types").WorkflowStats> {
|
||||
const response = await client.get("api/easo/stats", {
|
||||
searchParams: { corpId, platformId },
|
||||
});
|
||||
return unwrap(response, WorkflowStatsSchema);
|
||||
}
|
||||
|
||||
export async function getWorkflowCharge(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<import("./types").WorkflowCharge> {
|
||||
const response = await client.get("api/easo/charge", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
return unwrap(response, WorkflowChargeSchema);
|
||||
}
|
||||
|
||||
// ── 工作流详情(Piper)────────────────────────────────────────────────────────
|
||||
|
||||
export async function getWorkflowDetail(
|
||||
client: KyInstance,
|
||||
pipelineId: string
|
||||
): Promise<import("./types").WorkflowDetail> {
|
||||
const response = await client.get(`api/easo/pipelines/${pipelineId}`);
|
||||
return unwrap(response, WorkflowDetailSchema);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import * as api from "./api";
|
||||
|
||||
export const platformTools = [
|
||||
{
|
||||
name: "platform_list",
|
||||
description: "列出企业下所有启用的自建应用",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
return await api.listPlatforms(client);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "platform_workflow_list",
|
||||
description: "列出指定自建应用下的工作流",
|
||||
parameters: z.object({
|
||||
platformId: z.string().describe("自建应用 ID"),
|
||||
page: z.number().optional().describe("页码,默认 1"),
|
||||
pageSize: z.number().optional().describe("每页数量,默认 20"),
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { platformId: string; page?: number; pageSize?: number }
|
||||
) => {
|
||||
// 需要从 corp 获取 corpId,这里简化处理
|
||||
return { message: "需要使用 EASO 客户端" };
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type PlatformTool = (typeof platformTools)[number];
|
||||
@@ -0,0 +1,126 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 通用响应包装 ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const EkbResponseSchema = <T extends z.ZodType>(dataSchema: T) =>
|
||||
z.object({
|
||||
code: z.number(),
|
||||
msg: z.string().default(""),
|
||||
data: dataSchema.optional(),
|
||||
});
|
||||
|
||||
// ── 自建应用(DataLink Platform)─────────────────────────────
|
||||
|
||||
export const PlatformSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
nameSpell: z.string().default(""),
|
||||
enName: z.string().nullable().optional(),
|
||||
code: z.string().default(""),
|
||||
corporationId: z.string(),
|
||||
active: z.boolean().default(true),
|
||||
type: z.string().default(""),
|
||||
groupType: z.string().default(""),
|
||||
platformType: z.string().default(""),
|
||||
source: z.string().default(""),
|
||||
adminIds: z.array(z.string()).default([]),
|
||||
desc: z.string().nullable().optional(),
|
||||
importMethod: z.array(z.string()).default([]),
|
||||
createTime: z.number().default(0),
|
||||
updateTime: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 工作流(EASO Pipeline)───────────────────────────────────
|
||||
|
||||
export const WorkflowTaskSchema = z.object({
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
desc: z.string().optional(),
|
||||
groupName: z.string().default(""),
|
||||
orderIndex: z.number().default(0),
|
||||
status: z.string().default(""),
|
||||
});
|
||||
|
||||
export const WorkflowSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineName: z.string().default(""),
|
||||
state: z.number().default(0),
|
||||
runningCount: z.number().default(0),
|
||||
errorCount: z.number().default(0),
|
||||
updateTime: z.string().default(""),
|
||||
updateUser: z.string().optional(),
|
||||
tasks: z.array(z.any()).default([]),
|
||||
desc: z.string().optional(),
|
||||
customDesc: z.string().optional(),
|
||||
});
|
||||
|
||||
export const WorkflowPageSchema = z.object({
|
||||
pipelineNum: z.number().default(0),
|
||||
runningNum: z.number().default(0),
|
||||
allRunCount: z.number().default(0),
|
||||
errorCount: z.number().default(0),
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(20),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
pipelineList: z.array(WorkflowSchema).default([]),
|
||||
});
|
||||
|
||||
export const WorkflowStatsSchema = z.object({
|
||||
total: z.number().default(0),
|
||||
completed: z.number().default(0),
|
||||
failed: z.number().default(0),
|
||||
started: z.number().default(0),
|
||||
pipelineOpenCount: z.number().default(0),
|
||||
pipelineCloseCount: z.number().default(0),
|
||||
pipelineAllCount: z.number().default(0),
|
||||
});
|
||||
|
||||
export const WorkflowAlarmSchema = z.object({
|
||||
alarmUser: z.array(z.any()).default([]),
|
||||
alarmType: z.array(z.string()).default([]),
|
||||
active: z.boolean().default(true),
|
||||
alarmScope: z.string().default(""),
|
||||
});
|
||||
|
||||
export const WorkflowDetailSchema = z.object({
|
||||
id: z.string(),
|
||||
label: z.string().default(""),
|
||||
desc: z.string().optional(),
|
||||
customDesc: z.string().optional(),
|
||||
state: z.number().default(0),
|
||||
debugState: z.number().default(0),
|
||||
runTimes: z.number().default(0),
|
||||
errorTimes: z.number().default(0),
|
||||
updateTime: z.string().default(""),
|
||||
updateUser: z.string().optional(),
|
||||
staffName: z.string().optional(),
|
||||
version: z.string().default(""),
|
||||
dataLimit: z.number().default(20),
|
||||
source: z.number().default(0),
|
||||
queueJobs: z.boolean().default(false),
|
||||
tasksVersion: z.number().default(0),
|
||||
tasks: z.array(WorkflowTaskSchema).default([]),
|
||||
alarm: WorkflowAlarmSchema.optional(),
|
||||
});
|
||||
|
||||
export const WorkflowChargeSchema = z.object({
|
||||
corporationId: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
orderType: z.string().default(""),
|
||||
total: z.number().default(0),
|
||||
used: z.number().default(0),
|
||||
remaining: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 类型导出 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type Platform = z.infer<typeof PlatformSchema>;
|
||||
export type WorkflowTask = z.infer<typeof WorkflowTaskSchema>;
|
||||
export type Workflow = z.infer<typeof WorkflowSchema>;
|
||||
export type WorkflowPage = z.infer<typeof WorkflowPageSchema>;
|
||||
export type WorkflowStats = z.infer<typeof WorkflowStatsSchema>;
|
||||
export type WorkflowAlarm = z.infer<typeof WorkflowAlarmSchema>;
|
||||
export type WorkflowDetail = z.infer<typeof WorkflowDetailSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
@@ -0,0 +1,183 @@
|
||||
import { KyInstance } from "ky";
|
||||
import {
|
||||
MeDataSchema,
|
||||
BillingStatusDataSchema,
|
||||
DraftRulesDataSchema,
|
||||
DraftRuleSchema,
|
||||
RuleSetVersionSchema,
|
||||
PublishVersionDataSchema,
|
||||
KnowledgeArticleListDataSchema,
|
||||
KnowledgeArticleSchema,
|
||||
} from "./types";
|
||||
|
||||
// Helper to unwrap { data: T } response
|
||||
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const json = await response.json();
|
||||
return schema.parse(json.data);
|
||||
}
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 认证 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getMe(client: KyInstance): Promise<import("./types").MeData> {
|
||||
const response = await client.get("api/v1/auth/me");
|
||||
return unwrap(response, MeDataSchema);
|
||||
}
|
||||
|
||||
// ── 计费 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getBillingStatus(
|
||||
client: KyInstance
|
||||
): Promise<import("./types").BillingStatusData> {
|
||||
const response = await client.get("api/v1/billing/status");
|
||||
return unwrap(response, BillingStatusDataSchema);
|
||||
}
|
||||
|
||||
// ── 审核规则 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listRules(
|
||||
client: KyInstance
|
||||
): Promise<import("./types").DraftRulesData> {
|
||||
const response = await client.get("api/v1/rules");
|
||||
return unwrap(response, DraftRulesDataSchema);
|
||||
}
|
||||
|
||||
export async function createRule(
|
||||
client: KyInstance,
|
||||
params: {
|
||||
description: string;
|
||||
scope: string;
|
||||
strictness: string;
|
||||
}
|
||||
): Promise<import("./types").DraftRule> {
|
||||
const response = await client.post("api/v1/rules", {
|
||||
json: params,
|
||||
});
|
||||
return unwrap(response, DraftRuleSchema);
|
||||
}
|
||||
|
||||
export async function updateRule(
|
||||
client: KyInstance,
|
||||
ruleId: string,
|
||||
params: {
|
||||
description?: string;
|
||||
scope?: string;
|
||||
strictness?: string;
|
||||
}
|
||||
): Promise<import("./types").DraftRule> {
|
||||
const response = await client.put(`api/v1/rules/${ruleId}`, {
|
||||
json: params,
|
||||
});
|
||||
return unwrap(response, DraftRuleSchema);
|
||||
}
|
||||
|
||||
export async function deleteRule(client: KyInstance, ruleId: string): Promise<void> {
|
||||
await client.delete(`api/v1/rules/${ruleId}`);
|
||||
}
|
||||
|
||||
export async function listRuleSetVersions(
|
||||
client: KyInstance
|
||||
): Promise<import("./types").RuleSetVersion[]> {
|
||||
const response = await client.get("api/v1/rule-set-versions");
|
||||
return unwrap(response, z.array(RuleSetVersionSchema));
|
||||
}
|
||||
|
||||
export async function publishRuleSetVersion(
|
||||
client: KyInstance,
|
||||
versionName: string
|
||||
): Promise<import("./types").PublishVersionData> {
|
||||
const response = await client.post("api/v1/rule-set-versions/publish", {
|
||||
json: { versionName },
|
||||
});
|
||||
return unwrap(response, PublishVersionDataSchema);
|
||||
}
|
||||
|
||||
// ── 知识文档 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listArticles(
|
||||
client: KyInstance,
|
||||
params: {
|
||||
scenarios?: string[];
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
sortBy?: string;
|
||||
sortOrder?: string;
|
||||
} = {}
|
||||
): Promise<import("./types").KnowledgeArticleListData> {
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("offset", String(params.offset ?? 0));
|
||||
searchParams.set("limit", String(params.limit ?? 20));
|
||||
searchParams.set("sortBy", params.sortBy ?? "createdAt");
|
||||
searchParams.set("sortOrder", params.sortOrder ?? "desc");
|
||||
|
||||
if (params.scenarios) {
|
||||
for (let i = 0; i < params.scenarios.length; i++) {
|
||||
searchParams.set(`filter[scenarios][${i}]`, params.scenarios[i]);
|
||||
}
|
||||
}
|
||||
|
||||
const response = await client.get("api/v1/knowledge/articles", {
|
||||
searchParams,
|
||||
});
|
||||
return unwrap(response, KnowledgeArticleListDataSchema);
|
||||
}
|
||||
|
||||
export async function getArticle(
|
||||
client: KyInstance,
|
||||
articleId: string
|
||||
): Promise<import("./types").KnowledgeArticle> {
|
||||
const response = await client.get(`api/v1/knowledge/articles/${articleId}`);
|
||||
return unwrap(response, KnowledgeArticleSchema);
|
||||
}
|
||||
|
||||
export async function createArticle(
|
||||
client: KyInstance,
|
||||
params: {
|
||||
title: string;
|
||||
purpose: string;
|
||||
content: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
): Promise<import("./types").KnowledgeArticle> {
|
||||
const response = await client.post("api/v1/knowledge/articles", {
|
||||
json: {
|
||||
...params,
|
||||
contentType: params.contentType ?? "policy",
|
||||
status: params.status ?? "published",
|
||||
scenarios: params.scenarios ?? [],
|
||||
tags: params.tags ?? [],
|
||||
},
|
||||
});
|
||||
return unwrap(response, KnowledgeArticleSchema);
|
||||
}
|
||||
|
||||
export async function patchArticle(
|
||||
client: KyInstance,
|
||||
articleId: string,
|
||||
params: {
|
||||
title?: string;
|
||||
purpose?: string;
|
||||
content?: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
enabled?: boolean;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
): Promise<import("./types").KnowledgeArticle> {
|
||||
const attributes: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value !== undefined) {
|
||||
attributes[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const response = await client.patch(`api/v1/knowledge/articles/${articleId}`, {
|
||||
json: { attributes },
|
||||
});
|
||||
return unwrap(response, KnowledgeArticleSchema);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import * as api from "./api";
|
||||
|
||||
// ── Tool 定义 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const sealaiTools = [
|
||||
{
|
||||
name: "sealai_whoami",
|
||||
description: "查询当前 SealAI 用户身份及租户信息",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
return await api.getMe(client);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_billing",
|
||||
description: "查询 SealAI 订阅状态及功能配额",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
return await api.getBillingStatus(client);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_rules_list",
|
||||
description: "列出 SealAI 草稿区审核规则",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
return await api.listRules(client);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_rule_create",
|
||||
description: "新建 SealAI 草稿审核规则",
|
||||
parameters: z.object({
|
||||
description: z.string().describe("规则描述"),
|
||||
scope: z.string().describe("适用场景"),
|
||||
strictness: z
|
||||
.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"])
|
||||
.describe("严格程度"),
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { description: string; scope: string; strictness: string }
|
||||
) => {
|
||||
return await api.createRule(client, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_rule_update",
|
||||
description: "更新 SealAI 草稿审核规则",
|
||||
parameters: z.object({
|
||||
ruleId: z.string().describe("规则 ID"),
|
||||
description: z.string().optional().describe("规则描述"),
|
||||
scope: z.string().optional().describe("适用场景"),
|
||||
strictness: z
|
||||
.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"])
|
||||
.optional()
|
||||
.describe("严格程度"),
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
ruleId: string;
|
||||
description?: string;
|
||||
scope?: string;
|
||||
strictness?: string;
|
||||
}
|
||||
) => {
|
||||
const { ruleId, ...rest } = params;
|
||||
return await api.updateRule(client, ruleId, rest);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_rule_delete",
|
||||
description: "删除 SealAI 草稿审核规则",
|
||||
parameters: z.object({
|
||||
ruleId: z.string().describe("规则 ID"),
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { ruleId: string }) => {
|
||||
await api.deleteRule(client, params.ruleId);
|
||||
return { success: true };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_versions_list",
|
||||
description: "列出 SealAI 已发布规则集版本历史",
|
||||
parameters: z.object({}),
|
||||
handler: async (client: KyInstance) => {
|
||||
return await api.listRuleSetVersions(client);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_version_publish",
|
||||
description: "发布 SealAI 草稿规则为新版本",
|
||||
parameters: z.object({
|
||||
versionName: z.string().describe("版本名称"),
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { versionName: string }) => {
|
||||
return await api.publishRuleSetVersion(client, params.versionName);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_knowledge_list",
|
||||
description: "列出 SealAI 知识文档",
|
||||
parameters: z.object({
|
||||
scenarios: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe("场景过滤,如 [\"audit\", \"fill\"]"),
|
||||
offset: z.number().optional().describe("分页偏移量"),
|
||||
limit: z.number().optional().describe("每页数量"),
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
scenarios?: string[];
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
}
|
||||
) => {
|
||||
return await api.listArticles(client, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_knowledge_get",
|
||||
description: "获取 SealAI 知识文档详情",
|
||||
parameters: z.object({
|
||||
articleId: z.string().describe("文档 ID"),
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { articleId: string }) => {
|
||||
return await api.getArticle(client, params.articleId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_knowledge_create",
|
||||
description: "新建 SealAI 知识文档",
|
||||
parameters: z.object({
|
||||
title: z.string().describe("文档标题"),
|
||||
purpose: z.string().describe("适用说明"),
|
||||
content: z.string().describe("正文内容(Markdown)"),
|
||||
contentType: z.string().optional().describe("内容类型,默认 policy"),
|
||||
status: z.string().optional().describe("published 或 draft"),
|
||||
scenarios: z.array(z.string()).optional().describe("适用场景"),
|
||||
tags: z.array(z.string()).optional().describe("标签"),
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
title: string;
|
||||
purpose: string;
|
||||
content: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
) => {
|
||||
return await api.createArticle(client, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sealai_knowledge_update",
|
||||
description: "更新 SealAI 知识文档",
|
||||
parameters: z.object({
|
||||
articleId: z.string().describe("文档 ID"),
|
||||
title: z.string().optional(),
|
||||
purpose: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
contentType: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
scenarios: z.array(z.string()).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
articleId: string;
|
||||
title?: string;
|
||||
purpose?: string;
|
||||
content?: string;
|
||||
contentType?: string;
|
||||
status?: string;
|
||||
enabled?: boolean;
|
||||
scenarios?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
) => {
|
||||
const { articleId, ...rest } = params;
|
||||
return await api.patchArticle(client, articleId, rest);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type SealAiTool = (typeof sealaiTools)[number];
|
||||
@@ -0,0 +1,166 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 通用包装 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const SealAiResponseSchema = <T extends z.ZodType>(dataSchema: T) =>
|
||||
z.object({
|
||||
data: dataSchema,
|
||||
});
|
||||
|
||||
// ── 认证 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const HosecloudStaffSchema = z.object({
|
||||
staffId: z.string(),
|
||||
name: z.string(),
|
||||
code: z.string().default(""),
|
||||
bindTime: z.number(),
|
||||
});
|
||||
|
||||
export const SealAiUserSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string(),
|
||||
name: z.string(),
|
||||
isAdmin: z.boolean(),
|
||||
permissions: z.array(z.string()),
|
||||
providerUserId: z.string(),
|
||||
hosecloudStaff: HosecloudStaffSchema.optional(),
|
||||
});
|
||||
|
||||
export const HoseCorpConfigSchema = z.object({
|
||||
apiKey: z.string(),
|
||||
corporationId: z.string(),
|
||||
corporationName: z.string(),
|
||||
});
|
||||
|
||||
export const SealAiTenantSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
tenantSlug: z.string(),
|
||||
isDemo: z.boolean(),
|
||||
logoUrl: z.string().optional(),
|
||||
hoseCorpConfig: HoseCorpConfigSchema,
|
||||
});
|
||||
|
||||
export const MeDataSchema = z.object({
|
||||
user: SealAiUserSchema,
|
||||
tenant: SealAiTenantSchema,
|
||||
});
|
||||
|
||||
// ── 计费 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const SubscriptionSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string(),
|
||||
planId: z.string(),
|
||||
status: z.string(), // "active" | "expired"
|
||||
startDate: z.string(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
});
|
||||
|
||||
export const FeatureSchema = z.object({
|
||||
code: z.string(),
|
||||
name: z.string(),
|
||||
enabled: z.boolean().optional(),
|
||||
quota: z.number().optional(),
|
||||
used: z.number().optional(),
|
||||
remaining: z.number().optional(),
|
||||
balance: z.number().optional(),
|
||||
totalQuota: z.number().optional(),
|
||||
totalUsed: z.number().optional(),
|
||||
nextResetDate: z.string().optional(),
|
||||
});
|
||||
|
||||
export const BillingStatusDataSchema = z.object({
|
||||
subscriptions: z.array(SubscriptionSchema),
|
||||
features: z.array(FeatureSchema),
|
||||
});
|
||||
|
||||
// ── 审核规则草稿 ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const DraftRuleSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string(),
|
||||
description: z.string(),
|
||||
scope: z.string(),
|
||||
strictness: z.string(), // MUST_FOLLOW / SHOULD_FOLLOW / SUGGESTION
|
||||
status: z.string(), // DRAFT
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
});
|
||||
|
||||
export const DraftRulesDataSchema = z.object({
|
||||
rules: z.array(DraftRuleSchema),
|
||||
hasPendingDeletes: z.boolean().default(false),
|
||||
});
|
||||
|
||||
// ── 已发布版本 ────────────────────────────────────────────────────────────────
|
||||
|
||||
export const PublishedRuleSnapshotSchema = z.object({
|
||||
description: z.string(),
|
||||
scope: z.string(),
|
||||
strictness: z.string(),
|
||||
});
|
||||
|
||||
export const RuleSetVersionSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string(),
|
||||
versionNumber: z.number(),
|
||||
versionName: z.string(),
|
||||
publishedBy: z.string(),
|
||||
publishedByName: z.string(),
|
||||
rules: z.array(PublishedRuleSnapshotSchema),
|
||||
publishedAt: z.number(),
|
||||
createdAt: z.number(),
|
||||
});
|
||||
|
||||
export const PublishVersionDataSchema = z.object({
|
||||
version: RuleSetVersionSchema,
|
||||
rulesCount: z.number(),
|
||||
});
|
||||
|
||||
// ── 知识文档 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const KnowledgeArticleSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string(),
|
||||
title: z.string(),
|
||||
purpose: z.string(),
|
||||
contentType: z.string(),
|
||||
content: z.string(),
|
||||
status: z.string(), // "published" | "draft"
|
||||
enabled: z.boolean().default(true),
|
||||
scenarios: z.array(z.string()).default([]),
|
||||
tags: z.array(z.string()).default([]),
|
||||
category: z.string().optional(),
|
||||
categoryTags: z.array(z.string()).default([]),
|
||||
createdBy: z.string().optional(),
|
||||
createdByName: z.string().optional(),
|
||||
createdAt: z.number().optional(),
|
||||
updatedAt: z.number().optional(),
|
||||
updatedBy: z.string().optional(),
|
||||
updatedByName: z.string().optional(),
|
||||
isDeleted: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const KnowledgeArticleListDataSchema = z.object({
|
||||
articles: z.array(KnowledgeArticleSchema),
|
||||
total: z.number().optional(),
|
||||
});
|
||||
|
||||
// ── 类型导出 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type HosecloudStaff = z.infer<typeof HosecloudStaffSchema>;
|
||||
export type SealAiUser = z.infer<typeof SealAiUserSchema>;
|
||||
export type SealAiTenant = z.infer<typeof SealAiTenantSchema>;
|
||||
export type MeData = z.infer<typeof MeDataSchema>;
|
||||
export type Subscription = z.infer<typeof SubscriptionSchema>;
|
||||
export type Feature = z.infer<typeof FeatureSchema>;
|
||||
export type BillingStatusData = z.infer<typeof BillingStatusDataSchema>;
|
||||
export type DraftRule = z.infer<typeof DraftRuleSchema>;
|
||||
export type DraftRulesData = z.infer<typeof DraftRulesDataSchema>;
|
||||
export type PublishedRuleSnapshot = z.infer<typeof PublishedRuleSnapshotSchema>;
|
||||
export type RuleSetVersion = z.infer<typeof RuleSetVersionSchema>;
|
||||
export type PublishVersionData = z.infer<typeof PublishVersionDataSchema>;
|
||||
export type KnowledgeArticle = z.infer<typeof KnowledgeArticleSchema>;
|
||||
export type KnowledgeArticleListData = z.infer<typeof KnowledgeArticleListDataSchema>;
|
||||
@@ -0,0 +1,187 @@
|
||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import { zodToJsonSchema } from "zod-to-json-schema";
|
||||
import { loadCorpConfigs } from "./core/config/loader.js";
|
||||
import { CorpContext } from "./core/config/manager.js";
|
||||
import { createClient } from "./core/http/factory.js";
|
||||
import { getEasoClient } from "./core/auth/easo.js";
|
||||
import { getPiperClient } from "./core/auth/piper.js";
|
||||
import { sealaiTools } from "./domains/sealai/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
import * as platformApi from "./domains/platform/api.js";
|
||||
|
||||
async function main() {
|
||||
// 加载企业配置
|
||||
const corps = loadCorpConfigs();
|
||||
const corpContext = new CorpContext(corps);
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: "ekb-mcp",
|
||||
version: "0.1.0",
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: {},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 注册工具列表
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
||||
return {
|
||||
tools: [
|
||||
// 企业切换工具
|
||||
{
|
||||
name: "switch_corp",
|
||||
description: "切换到指定企业",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
corpId: {
|
||||
type: "string",
|
||||
description: "企业 ID",
|
||||
},
|
||||
},
|
||||
required: ["corpId"],
|
||||
},
|
||||
},
|
||||
// SealAI 工具
|
||||
...sealaiTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
inputSchema: zodToJsonSchema(t.parameters),
|
||||
})),
|
||||
// Platform 工具
|
||||
...platformTools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
inputSchema: zodToJsonSchema(t.parameters),
|
||||
})),
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// 处理工具调用
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
|
||||
// 企业切换
|
||||
if (name === "switch_corp") {
|
||||
const { corpId } = args as { corpId: string };
|
||||
const success = corpContext.switchCorp(corpId);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: success
|
||||
? `已切换到企业: ${corpId}`
|
||||
: `企业 ${corpId} 不存在`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// 获取当前企业
|
||||
const currentCorp = corpContext.getCurrent();
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "未配置企业,请先添加企业配置",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// SealAI 工具
|
||||
const sealaiTool = sealaiTools.find((t) => t.name === name);
|
||||
if (sealaiTool) {
|
||||
const client = await createClient(currentCorp, "sealai");
|
||||
const result = await sealaiTool.handler(client, args as never);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Platform 工具
|
||||
if (name === "platform_list") {
|
||||
const client = await createClient(currentCorp, "ekb");
|
||||
const result = await platformApi.listPlatforms(
|
||||
client,
|
||||
currentCorp.credentials.corpId
|
||||
);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (name === "platform_workflow_list") {
|
||||
const { platformId, page, pageSize } = args as {
|
||||
platformId: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
};
|
||||
const { client, corpId } = await getEasoClient(currentCorp);
|
||||
const result = await platformApi.listWorkflows(
|
||||
client,
|
||||
corpId,
|
||||
platformId,
|
||||
page,
|
||||
pageSize
|
||||
);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `未知工具: ${name}`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `错误: ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
console.error("EKB MCP Server running on stdio");
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext"],
|
||||
"module": "ESNext",
|
||||
"target": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"paths": {
|
||||
"@core/*": ["./src/core/*"],
|
||||
"@domains/*": ["./src/domains/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
Reference in new issue
Block a user