diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts new file mode 100644 index 0000000..ec96e29 --- /dev/null +++ b/src/domains/seal/api.ts @@ -0,0 +1,199 @@ +import { KyInstance } from "ky"; +import { z } from "zod"; +import { + ApprovalDocumentListData, + ApprovalDocumentListDataSchema, + ApprovalDocumentSchema, + ApprovalRulesData, + ApprovalRulesDataSchema, + ApprovalRule, + ApprovalRuleSchema, + ApprovalStylePreferences, + ApprovalStylePreferencesSchema, + MeData, + MeDataSchema, + PublishVersionDataSchema, + RuleSetVersion, + RuleSetVersionSchema +} from "./types.js"; + +async function unwrap(response: Response, schema: z.ZodType): Promise { + const json = (await response.json()) as { data?: unknown }; + return schema.parse(json.data ?? json); +} + +export async function getMe(client: KyInstance): Promise { + return unwrap(await client.get("api/v1/auth/me"), MeDataSchema); +} + +export async function listApprovalRules(client: KyInstance): Promise { + return unwrap(await client.get("api/v1/rules"), ApprovalRulesDataSchema); +} + +export async function createApprovalRule( + client: KyInstance, + params: { description: string; scope: string; strictness: string } +): Promise { + return unwrap(await client.post("api/v1/rules", { json: params }), ApprovalRuleSchema); +} + +export async function updateApprovalRule( + client: KyInstance, + ruleId: string, + params: { description?: string; scope?: string; strictness?: string } +): Promise { + return unwrap(await client.put(`api/v1/rules/${ruleId}`, { json: params }), ApprovalRuleSchema); +} + +export async function deleteApprovalRule(client: KyInstance, ruleId: string): Promise { + await client.delete(`api/v1/rules/${ruleId}`); +} + +export async function listApprovalRuleVersions(client: KyInstance): Promise { + return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema)); +} + +export async function publishApprovalRuleVersion( + client: KyInstance, + versionName: string +): Promise> { + return unwrap( + await client.post("api/v1/rule-set-versions/publish", { json: { versionName } }), + PublishVersionDataSchema + ); +} + +export async function listApprovalDocuments( + client: KyInstance, + params: { + scenarios?: string[]; + offset?: number; + limit?: number; + sortBy?: string; + sortOrder?: string; + } = {} +): Promise { + 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"); + + params.scenarios?.forEach((scenario, index) => { + searchParams.set(`filter[scenarios][${index}]`, scenario); + }); + + return unwrap( + await client.get("api/v1/knowledge/articles", { searchParams }), + ApprovalDocumentListDataSchema + ); +} + +export async function getApprovalDocument(client: KyInstance, documentId: string) { + return unwrap( + await client.get(`api/v1/knowledge/articles/${documentId}`), + ApprovalDocumentSchema + ); +} + +export async function createApprovalDocument( + client: KyInstance, + params: { + title: string; + purpose: string; + content: string; + contentType?: string; + status?: string; + scenarios?: string[]; + tags?: string[]; + } +) { + return unwrap( + await client.post("api/v1/knowledge/articles", { + json: { + ...params, + contentType: params.contentType ?? "policy", + status: params.status ?? "published", + scenarios: params.scenarios ?? [], + tags: params.tags ?? [] + } + }), + ApprovalDocumentSchema + ); +} + +export async function updateApprovalDocument( + client: KyInstance, + documentId: string, + params: { + title?: string; + purpose?: string; + content?: string; + contentType?: string; + status?: string; + enabled?: boolean; + scenarios?: string[]; + tags?: string[]; + } +) { + const attributes = Object.fromEntries( + Object.entries(params).filter(([, value]) => value !== undefined) + ); + + return unwrap( + await client.patch(`api/v1/knowledge/articles/${documentId}`, { + json: { attributes } + }), + ApprovalDocumentSchema + ); +} + +export async function getApprovalStylePreferences( + client: KyInstance, + endpoint = "api/v1/approval/style-preferences" +): Promise { + return unwrap( + await client.get(endpoint), + ApprovalStylePreferencesSchema + ); +} + +export async function updateApprovalStylePreferences( + client: KyInstance, + params: Record, + endpoint = "api/v1/approval/style-preferences" +): Promise { + return unwrap( + await client.patch(endpoint, { json: params }), + ApprovalStylePreferencesSchema + ); +} + +export async function getApprovalContext( + client: KyInstance, + params: { + documentLimit?: number; + stylePreferencesEndpoint?: string; + } = {} +) { + const [rules, documents, stylePreferences] = await Promise.all([ + listApprovalRules(client), + listApprovalDocuments(client, { limit: params.documentLimit ?? 50 }), + getApprovalStylePreferences( + client, + params.stylePreferencesEndpoint + ).then( + (data) => ({ ok: true as const, data }), + (error) => ({ + ok: false as const, + error: error instanceof Error ? error.message : String(error) + }) + ) + ]); + + return { + rules, + documents, + stylePreferences + }; +} diff --git a/src/domains/seal/source.ts b/src/domains/seal/source.ts new file mode 100644 index 0000000..cf93de1 --- /dev/null +++ b/src/domains/seal/source.ts @@ -0,0 +1,35 @@ +import { CorpConfig } from "../../core/config/types.js"; +import { createSealClient } from "../../core/http/factory.js"; +import { resolveSealEnterpriseConfig } from "../../core/auth/seal.js"; +import { SealEnterpriseConfig } from "../../core/auth/types.js"; +import { getMe } from "./api.js"; + +export async function resolveLiveSealEnterpriseConfig( + corp: CorpConfig +): Promise { + const [baseConfig, client] = await Promise.all([ + resolveSealEnterpriseConfig(corp), + createSealClient(corp) + ]); + + const me = await getMe(client); + return { + ...baseConfig, + tenantId: me.tenant.id, + tenantSlug: me.tenant.tenantSlug ?? baseConfig.tenantSlug, + tenantName: me.tenant.name, + raw: { + ...(typeof baseConfig.raw === "object" && baseConfig.raw !== null + ? baseConfig.raw + : {}), + user: { + id: me.user.id, + name: me.user.name, + isAdmin: me.user.isAdmin, + providerUserId: me.user.providerUserId, + hosecloudStaff: me.user.hosecloudStaff + }, + tenant: me.tenant + } + }; +} diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts new file mode 100644 index 0000000..0b2d17b --- /dev/null +++ b/src/domains/seal/tools.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, test } from "bun:test"; +import { z } from "zod"; +import { sealTools } from "./tools.js"; + +describe("sealTools", () => { + test("exposes concrete JSON schemas for parameterized tools", () => { + const createRule = sealTools.find((tool) => tool.name === "seal_approval_rule_create"); + expect(createRule).toBeDefined(); + + const schema = z.toJSONSchema(createRule!.parameters) as { + properties?: Record; + required?: string[]; + }; + + expect(Object.keys(schema.properties ?? {})).toEqual([ + "description", + "scope", + "strictness" + ]); + expect(schema.required).toEqual(["description", "scope", "strictness"]); + }); + + test("includes the approval context aggregation tool", () => { + const tool = sealTools.find((item) => item.name === "seal_approval_context_get"); + expect(tool).toBeDefined(); + }); +}); diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts new file mode 100644 index 0000000..a3c310b --- /dev/null +++ b/src/domains/seal/tools.ts @@ -0,0 +1,209 @@ +import { z } from "zod"; +import { KyInstance } from "ky"; +import * as api from "./api.js"; +import { CorpConfig } from "../../core/config/types.js"; + +type ToolContext = { + corp: CorpConfig; +}; + +export const sealTools = [ + { + name: "seal_whoami", + description: "查询当前 Seal 用户身份及租户信息", + parameters: z.object({}), + handler: async (client: KyInstance) => api.getMe(client) + }, + { + name: "seal_approval_rules_list", + description: "列出 Seal 当前草稿审批规则", + parameters: z.object({}), + handler: async (client: KyInstance) => api.listApprovalRules(client) + }, + { + name: "seal_approval_rule_create", + description: "新建 Seal 草稿审批规则", + 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 } + ) => api.createApprovalRule(client, params) + }, + { + name: "seal_approval_rule_update", + description: "更新 Seal 草稿审批规则", + parameters: z.object({ + ruleId: z.string().describe("规则 ID"), + description: z.string().optional(), + scope: z.string().optional(), + strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional() + }), + handler: async ( + client: KyInstance, + params: { ruleId: string; description?: string; scope?: string; strictness?: string } + ) => { + const { ruleId, ...rest } = params; + return api.updateApprovalRule(client, ruleId, rest); + } + }, + { + name: "seal_approval_rule_delete", + description: "删除 Seal 草稿审批规则", + parameters: z.object({ + ruleId: z.string().describe("规则 ID") + }), + handler: async (client: KyInstance, params: { ruleId: string }) => { + await api.deleteApprovalRule(client, params.ruleId); + return { success: true }; + } + }, + { + name: "seal_approval_rule_versions_list", + description: "列出 Seal 已发布审批规则版本", + parameters: z.object({}), + handler: async (client: KyInstance) => api.listApprovalRuleVersions(client) + }, + { + name: "seal_approval_rule_version_publish", + description: "发布 Seal 草稿审批规则为新版本", + parameters: z.object({ + versionName: z.string().describe("版本名称") + }), + handler: async (client: KyInstance, params: { versionName: string }) => + api.publishApprovalRuleVersion(client, params.versionName) + }, + { + name: "seal_approval_documents_list", + description: "列出 Seal 审批知识文档", + parameters: z.object({ + scenarios: z.array(z.string()).optional().describe("场景过滤"), + offset: z.number().int().nonnegative().optional(), + limit: z.number().int().positive().optional() + }), + handler: async ( + client: KyInstance, + params: { scenarios?: string[]; offset?: number; limit?: number } + ) => api.listApprovalDocuments(client, params) + }, + { + name: "seal_approval_document_get", + description: "获取 Seal 审批知识文档详情", + parameters: z.object({ + documentId: z.string().describe("文档 ID") + }), + handler: async (client: KyInstance, params: { documentId: string }) => + api.getApprovalDocument(client, params.documentId) + }, + { + name: "seal_approval_document_create", + description: "新建 Seal 审批知识文档", + parameters: z.object({ + title: z.string(), + purpose: z.string(), + content: z.string().describe("正文,通常为 Markdown"), + contentType: z.string().optional(), + status: z.string().optional(), + scenarios: z.array(z.string()).optional(), + tags: z.array(z.string()).optional() + }), + handler: async ( + client: KyInstance, + params: { + title: string; + purpose: string; + content: string; + contentType?: string; + status?: string; + scenarios?: string[]; + tags?: string[]; + } + ) => api.createApprovalDocument(client, params) + }, + { + name: "seal_approval_document_update", + description: "更新 Seal 审批知识文档", + parameters: z.object({ + documentId: z.string(), + 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: { + documentId: string; + title?: string; + purpose?: string; + content?: string; + contentType?: string; + status?: string; + enabled?: boolean; + scenarios?: string[]; + tags?: string[]; + } + ) => { + const { documentId, ...rest } = params; + return api.updateApprovalDocument(client, documentId, rest); + } + }, + { + name: "seal_approval_context_get", + description: "聚合获取 Seal 现有审批规则、审批文档和审批风格偏好", + parameters: z.object({ + documentLimit: z.number().int().positive().optional().describe("最多返回的审批文档数量") + }), + handler: async ( + client: KyInstance, + params: { documentLimit?: number }, + context: ToolContext + ) => + api.getApprovalContext(client, { + documentLimit: params.documentLimit, + stylePreferencesEndpoint: context.corp.seal.endpoints.approvalStylePreferences + }) + }, + { + name: "seal_approval_style_preferences_get", + description: "获取 Seal 审批风格偏好配置", + parameters: z.object({}), + handler: async (client: KyInstance, _params: unknown, context: ToolContext) => + api.getApprovalStylePreferences( + client, + context.corp.seal.endpoints.approvalStylePreferences + ) + }, + { + name: "seal_approval_style_preferences_update", + description: "更新 Seal 审批风格偏好配置", + parameters: z.object({ + tone: z.string().optional(), + language: z.string().optional(), + detailLevel: z.string().optional(), + outputFormat: z.string().optional(), + examples: z.array(z.string()).optional(), + prohibitedPhrases: z.array(z.string()).optional(), + customInstructions: z.string().optional() + }), + handler: async ( + client: KyInstance, + params: Record, + context: ToolContext + ) => + api.updateApprovalStylePreferences( + client, + params, + context.corp.seal.endpoints.approvalStylePreferences + ) + } +]; + +export type SealTool = (typeof sealTools)[number]; diff --git a/src/domains/seal/types.ts b/src/domains/seal/types.ts new file mode 100644 index 0000000..1d1e8c0 --- /dev/null +++ b/src/domains/seal/types.ts @@ -0,0 +1,125 @@ +import { z } from "zod"; + +export const HosecloudStaffSchema = z.object({ + staffId: z.string(), + name: z.string().optional(), + code: z.string().default(""), + bindTime: z.number().optional() +}); + +export const SealUserSchema = z.object({ + id: z.string(), + tenantId: z.string(), + name: z.string(), + isAdmin: z.boolean().default(false), + permissions: z.array(z.string()).default([]), + providerUserId: z.string().optional(), + hosecloudStaff: HosecloudStaffSchema.optional() +}); + +export const HoseCorpConfigSchema = z.object({ + apiKey: z.string().optional(), + corporationId: z.string().optional(), + corporationName: z.string().optional() +}); + +export const SealTenantSchema = z.object({ + id: z.string(), + name: z.string(), + tenantSlug: z.string().optional(), + isDemo: z.boolean().default(false), + logoUrl: z.string().optional(), + hoseCorpConfig: HoseCorpConfigSchema.optional() +}); + +export const MeDataSchema = z.object({ + user: SealUserSchema, + tenant: SealTenantSchema +}); + +export const ApprovalRuleSchema = z.object({ + id: z.string(), + tenantId: z.string().optional(), + description: z.string(), + scope: z.string(), + strictness: z.string(), + status: z.string().optional(), + createdAt: z.number().optional(), + updatedAt: z.number().optional() +}); + +export const ApprovalRulesDataSchema = z.object({ + rules: z.array(ApprovalRuleSchema), + 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().optional(), + versionNumber: z.number(), + versionName: z.string(), + publishedBy: z.string().optional(), + publishedByName: z.string().optional(), + rules: z.array(PublishedRuleSnapshotSchema).default([]), + publishedAt: z.number().optional(), + createdAt: z.number().optional() +}); + +export const PublishVersionDataSchema = z.object({ + version: RuleSetVersionSchema, + rulesCount: z.number() +}); + +export const ApprovalDocumentSchema = z.object({ + id: z.string(), + tenantId: z.string().optional(), + title: z.string(), + purpose: z.string().default(""), + contentType: z.string().default("policy"), + content: z.string(), + status: z.string().default("published"), + 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 ApprovalDocumentListDataSchema = z.object({ + articles: z.array(ApprovalDocumentSchema), + total: z.number().optional() +}); + +export const ApprovalStylePreferencesSchema = z.object({ + id: z.string().optional(), + tenantId: z.string().optional(), + tone: z.string().optional(), + language: z.string().optional(), + detailLevel: z.string().optional(), + outputFormat: z.string().optional(), + examples: z.array(z.string()).default([]), + prohibitedPhrases: z.array(z.string()).default([]), + customInstructions: z.string().optional(), + updatedAt: z.number().optional() +}).passthrough(); + +export type MeData = z.infer; +export type ApprovalRule = z.infer; +export type ApprovalRulesData = z.infer; +export type RuleSetVersion = z.infer; +export type ApprovalDocument = z.infer; +export type ApprovalDocumentListData = z.infer; +export type ApprovalStylePreferences = z.infer; diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..e717c7d --- /dev/null +++ b/src/server.ts @@ -0,0 +1,128 @@ +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 { z } from "zod"; +import { loadCorpConfigs } from "./core/config/loader.js"; +import { CorpContext } from "./core/config/manager.js"; +import { createSealClient } from "./core/http/factory.js"; +import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js"; +import { sealTools } from "./domains/seal/tools.js"; + +async function main() { + const corps = loadCorpConfigs(); + const corpContext = new CorpContext(corps); + + const server = new Server( + { + name: "seal-home", + version: "0.1.0" + }, + { + capabilities: { + tools: {} + } + } + ); + + server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: [ + { + name: "seal_corps_list", + description: "列出本地配置的 Seal 企业", + inputSchema: { type: "object", properties: {} } + }, + { + name: "seal_corp_switch", + description: "切换当前 Seal 企业", + inputSchema: { + type: "object", + properties: { + corpId: { type: "string", description: "企业配置 ID" } + }, + required: ["corpId"] + } + }, + { + name: "seal_source_config", + description: "通过当前来源认证并读取 Seal 租户信息,解析 Seal 企业配置", + inputSchema: { type: "object", properties: {} } + }, + ...sealTools.map((tool) => ({ + name: tool.name, + description: tool.description, + inputSchema: z.toJSONSchema(tool.parameters) + })) + ] + })); + + server.setRequestHandler(CallToolRequestSchema, async (request) => { + const { name, arguments: args } = request.params; + + if (name === "seal_corps_list") { + return textResult(corpContext.listCorps()); + } + + if (name === "seal_corp_switch") { + const { corpId } = args as { corpId: string }; + const success = corpContext.switchCorp(corpId); + return textResult( + success ? { success: true, current: corpId } : { success: false, message: `Unknown corp: ${corpId}` }, + !success + ); + } + + const currentCorp = corpContext.getCurrent(); + if (!currentCorp) { + return textResult( + { + error: + "No enterprise config loaded. Add a non-example JSON file under enterprises/." + }, + true + ); + } + + try { + if (name === "seal_source_config") { + return textResult(await resolveLiveSealEnterpriseConfig(currentCorp)); + } + + const tool = sealTools.find((item) => item.name === name); + if (!tool) { + return textResult({ error: `Unknown tool: ${name}` }, true); + } + + const client = await createSealClient(currentCorp); + const result = await tool.handler(client, args as never, { corp: currentCorp }); + return textResult(result); + } catch (error) { + return textResult( + { error: error instanceof Error ? error.message : String(error) }, + true + ); + } + }); + + await server.connect(new StdioServerTransport()); + console.error("seal-home MCP server running on stdio"); +} + +function textResult(value: unknown, isError = false) { + return { + content: [ + { + type: "text" as const, + text: JSON.stringify(value, null, 2) + } + ], + isError + }; +} + +main().catch((error) => { + console.error(error); + process.exit(1); +});