webMcpService.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import { blockService } from './blockService';
  2. import { documentService } from './documentService';
  3. import { exportRecordService, listExportRecords } from './exportRecordService';
  4. import { exportToWord } from './exportService';
  5. import type { BlockType, CreateBlockRequest, UpdateBlockRequest } from '../types/editor';
  6. import type { DocumentListFilters } from '../types/document';
  7. import { useUIStore } from '../stores/uiStore';
  8. import { finishWebMcpActivity, startWebMcpActivity } from './webMcpActivityService';
  9. import { BLOCK_CREATED_EVENT, BLOCK_DELETED_EVENT, BLOCK_UPDATED_EVENT } from './blockService';
  10. export interface WebMcpToolResult {
  11. ok: boolean;
  12. data?: unknown;
  13. error?: string;
  14. }
  15. export interface WebMcpToolInputSchema {
  16. type: 'object';
  17. properties: Record<string, Record<string, unknown>>;
  18. required?: string[];
  19. additionalProperties?: boolean;
  20. }
  21. export interface WebMcpTool {
  22. name: string;
  23. title: string;
  24. description: string;
  25. inputSchema: WebMcpToolInputSchema;
  26. requiresConfirmation?: boolean;
  27. readOnlyHint?: boolean;
  28. untrustedContentHint?: boolean;
  29. execute: (input: Record<string, unknown>) => Promise<WebMcpToolResult>;
  30. }
  31. interface ModelContext {
  32. registerTool?: (tool: Omit<WebMcpTool, 'requiresConfirmation'>) => void | Promise<void>;
  33. provideContext?: (context: { tools: ReadonlyArray<Omit<WebMcpTool, 'requiresConfirmation'>> }) =>
  34. | void
  35. | Promise<void>;
  36. }
  37. interface WebMcpNavigator extends Navigator {
  38. modelContext?: ModelContext;
  39. }
  40. export interface WebMcpRegistrationResult {
  41. supported: boolean;
  42. registeredTools: string[];
  43. error?: string;
  44. }
  45. export interface WebMcpExecutionOptions {
  46. confirmed?: boolean;
  47. }
  48. const DEFAULT_USER_ID = import.meta.env.VITE_WEBMCP_USER_ID || 'default-user';
  49. let registrationPromise: Promise<WebMcpRegistrationResult> | undefined;
  50. const text = (data: unknown): WebMcpToolResult => ({ ok: true, data });
  51. const isRecord = (value: unknown): value is Record<string, unknown> =>
  52. typeof value === 'object' && value !== null && !Array.isArray(value);
  53. const failed = (error: unknown): WebMcpToolResult => ({
  54. ok: false,
  55. error: error instanceof Error ? error.message : 'WebMCP 工具执行失败',
  56. });
  57. const requiredString = (input: Record<string, unknown>, key: string): string => {
  58. const value = input[key];
  59. if (typeof value !== 'string' || !value.trim()) {
  60. throw new Error(`${key} 不能为空`);
  61. }
  62. const hasUnsafeCharacter = Array.from(value).some((character) => {
  63. const codePoint = character.codePointAt(0) ?? 0;
  64. return codePoint < 32 || codePoint === 127 || character === '/' || character === '\\';
  65. });
  66. if (value.length > 128 || hasUnsafeCharacter) {
  67. throw new Error(`${key} 无效`);
  68. }
  69. return value.trim();
  70. };
  71. const requiredContent = (input: Record<string, unknown>, key: string): string | object | unknown[] => {
  72. const value = input[key];
  73. if (typeof value === 'string') {
  74. if (!value.trim()) throw new Error(`${key} 不能为空`);
  75. if (value.length > 200_000) throw new Error(`${key} 长度过长`);
  76. return value;
  77. }
  78. if (Array.isArray(value) || isRecord(value)) {
  79. if (JSON.stringify(value).length > 200_000) throw new Error(`${key} 内容过大`);
  80. return value;
  81. }
  82. throw new Error(`${key} 必须是字符串、对象或数组`);
  83. };
  84. const optionalString = (input: Record<string, unknown>, key: string): string | undefined => {
  85. const value = input[key];
  86. if (value === undefined || value === null || value === '') return undefined;
  87. if (typeof value !== 'string') throw new Error(`${key} 必须是字符串`);
  88. if (value.length > 128) throw new Error(`${key} 无效`);
  89. return value.trim();
  90. };
  91. const numberOr = (input: Record<string, unknown>, key: string, fallback: number): number => {
  92. const value = input[key];
  93. if (value === undefined) return fallback;
  94. if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${key} 必须是数字`);
  95. return value;
  96. };
  97. const run = async (operation: () => Promise<unknown>): Promise<WebMcpToolResult> => {
  98. try {
  99. return text(await operation());
  100. } catch (error) {
  101. return failed(error);
  102. }
  103. };
  104. const objectSchema = (
  105. properties: Record<string, Record<string, unknown>>,
  106. required: string[] = []
  107. ): WebMcpToolInputSchema => ({
  108. type: 'object',
  109. properties,
  110. ...(required.length ? { required } : {}),
  111. additionalProperties: false,
  112. });
  113. const validateToolInput = (tool: WebMcpTool, input: Record<string, unknown>): string | undefined => {
  114. const schema = tool.inputSchema;
  115. for (const key of schema.required || []) {
  116. if (input[key] === undefined || input[key] === null || input[key] === '') return `${key} 不能为空`;
  117. }
  118. if (schema.additionalProperties === false) {
  119. const unknownKey = Object.keys(input).find((key) => !(key in schema.properties));
  120. if (unknownKey) return `不支持的参数: ${unknownKey}`;
  121. }
  122. for (const [key, definition] of Object.entries(schema.properties)) {
  123. const value = input[key];
  124. if (value === undefined || value === null) continue;
  125. if (definition.type === 'string' && typeof value !== 'string') return `${key} 必须是字符串`;
  126. if (definition.type === 'string' && typeof value === 'string') {
  127. if (definition.minLength !== undefined && value.length < Number(definition.minLength)) return `${key} 长度过短`;
  128. if (definition.maxLength !== undefined && value.length > Number(definition.maxLength)) return `${key} 长度过长`;
  129. }
  130. if (definition.type === 'number' && (typeof value !== 'number' || !Number.isFinite(value))) return `${key} 必须是数字`;
  131. if (definition.type === 'number' && typeof value === 'number') {
  132. if (definition.minimum !== undefined && value < Number(definition.minimum)) return `${key} 不能小于 ${definition.minimum}`;
  133. if (definition.maximum !== undefined && value > Number(definition.maximum)) return `${key} 不能大于 ${definition.maximum}`;
  134. }
  135. if (definition.enum && Array.isArray(definition.enum) && !definition.enum.includes(value)) return `${key} 参数值无效`;
  136. }
  137. return undefined;
  138. };
  139. const documentIdProperty = { type: 'string', description: '文档 ID' };
  140. const blockIdProperty = { type: 'string', description: '块 ID' };
  141. const tools: WebMcpTool[] = [
  142. {
  143. name: 'open_document',
  144. title: '打开文档',
  145. description: '在当前网站编辑器中打开指定文档。只读操作。',
  146. readOnlyHint: true,
  147. inputSchema: objectSchema({ documentId: documentIdProperty }, ['documentId']),
  148. execute: (input) => run(async () => {
  149. const documentId = requiredString(input, 'documentId');
  150. useUIStore.getState().openDocumentPreview(documentId);
  151. return { documentId, message: '文档已打开' };
  152. }),
  153. },
  154. {
  155. name: 'list_documents',
  156. title: '列出文档',
  157. description: '列出当前用户的文档。只读操作。',
  158. readOnlyHint: true,
  159. inputSchema: objectSchema({
  160. sessionId: { type: 'string', description: '可选,会话 ID' },
  161. page: { type: 'number', minimum: 1 },
  162. pageSize: { type: 'number', minimum: 1, maximum: 100 },
  163. }),
  164. execute: (input) =>
  165. run(() => {
  166. const filters: DocumentListFilters = {
  167. userId: DEFAULT_USER_ID,
  168. page: numberOr(input, 'page', 1),
  169. pageSize: numberOr(input, 'pageSize', 20),
  170. sessionId: optionalString(input, 'sessionId'),
  171. sortBy: 'updated_at',
  172. sortOrder: 'desc',
  173. };
  174. return documentService.list(filters);
  175. }),
  176. },
  177. {
  178. name: 'get_document',
  179. title: '读取文档',
  180. description: '读取指定文档的元数据和全部内容块。只读操作。',
  181. readOnlyHint: true,
  182. untrustedContentHint: true,
  183. inputSchema: objectSchema({ documentId: documentIdProperty }, ['documentId']),
  184. execute: (input) => run(() => documentService.get(requiredString(input, 'documentId'), { includeBlocks: true })),
  185. },
  186. {
  187. name: 'search_document',
  188. title: '搜索文档',
  189. description: '在文档中搜索包含关键词的内容块。只读操作。',
  190. readOnlyHint: true,
  191. untrustedContentHint: true,
  192. inputSchema: objectSchema(
  193. { documentId: documentIdProperty, query: { type: 'string', description: '搜索关键词', maxLength: 2000 }, type: { type: 'string', maxLength: 64 } },
  194. ['documentId', 'query']
  195. ),
  196. execute: (input) =>
  197. run(() => blockService.searchBlocks(requiredString(input, 'documentId'), requiredString(input, 'query'), optionalString(input, 'type'))),
  198. },
  199. {
  200. name: 'get_block',
  201. title: '读取文档块',
  202. description: '读取指定文档块。只读操作。',
  203. readOnlyHint: true,
  204. untrustedContentHint: true,
  205. inputSchema: objectSchema({ documentId: documentIdProperty, blockId: blockIdProperty }, ['documentId', 'blockId']),
  206. execute: (input) => run(() => blockService.getBlock(requiredString(input, 'documentId'), requiredString(input, 'blockId'))),
  207. },
  208. {
  209. name: 'get_document_toc',
  210. title: '读取文档目录',
  211. description: '获取文档目录树。只读操作。',
  212. readOnlyHint: true,
  213. untrustedContentHint: true,
  214. inputSchema: objectSchema({ documentId: documentIdProperty }, ['documentId']),
  215. execute: (input) => run(() => blockService.getTOC(requiredString(input, 'documentId'))),
  216. },
  217. {
  218. name: 'get_document_stats',
  219. title: '读取文档统计',
  220. description: '获取文档内容块统计信息。只读操作。',
  221. readOnlyHint: true,
  222. inputSchema: objectSchema({ documentId: documentIdProperty }, ['documentId']),
  223. execute: (input) => run(() => blockService.getStats(requiredString(input, 'documentId'))),
  224. },
  225. {
  226. name: 'list_export_records',
  227. title: '列出导出记录',
  228. description: '列出当前用户的导出记录。只读操作。',
  229. readOnlyHint: true,
  230. inputSchema: objectSchema({ page: { type: 'number', minimum: 1 }, pageSize: { type: 'number', minimum: 1, maximum: 100 } }),
  231. execute: (input) =>
  232. run(() => listExportRecords({
  233. userId: DEFAULT_USER_ID,
  234. page: numberOr(input, 'page', 1),
  235. pageSize: numberOr(input, 'pageSize', 20),
  236. sortOrder: 'desc',
  237. })),
  238. },
  239. {
  240. name: 'insert_block',
  241. title: '插入内容块',
  242. description: '向文档插入内容块。需要用户确认。',
  243. requiresConfirmation: true,
  244. inputSchema: objectSchema(
  245. {
  246. documentId: documentIdProperty,
  247. type: { type: 'string', enum: ['heading', 'paragraph', 'table', 'image', 'toc'] },
  248. content: { type: 'string', description: '块内容', maxLength: 200000 },
  249. level: { type: 'number', minimum: 0, maximum: 6 },
  250. afterBlockId: { type: 'string', description: '插入到此块之后,可选' },
  251. clientBlockId: { type: 'string', description: '可选,客户端幂等块 ID' },
  252. },
  253. ['documentId', 'type', 'content']
  254. ),
  255. execute: (input) => run(async () => {
  256. const type = requiredString(input, 'type') as BlockType;
  257. const level = input.level === undefined ? 0 : numberOr(input, 'level', 0);
  258. if (type === 'heading' && (level < 1 || level > 6)) {
  259. throw new Error('heading 的 level 必须是 1-6');
  260. }
  261. if (type !== 'heading' && level !== 0) {
  262. throw new Error('非 heading 块的 level 必须是 0');
  263. }
  264. const documentId = requiredString(input, 'documentId');
  265. const response = await blockService.createBlock(documentId, {
  266. type,
  267. content: requiredContent(input, 'content') as CreateBlockRequest['content'],
  268. level,
  269. after_block_id: optionalString(input, 'afterBlockId'),
  270. client_block_id: optionalString(input, 'clientBlockId'),
  271. });
  272. const created = await blockService.getBlock(documentId, response.blockId);
  273. window.dispatchEvent(new CustomEvent(BLOCK_CREATED_EVENT, {
  274. detail: { documentId, block: created.block },
  275. }));
  276. return { ...response, block: created.block, message: 'Block created successfully' };
  277. }),
  278. },
  279. {
  280. name: 'update_block',
  281. title: '修改内容块',
  282. description: '更新文档块内容。需要用户确认。',
  283. requiresConfirmation: true,
  284. inputSchema: objectSchema({ documentId: documentIdProperty, blockId: blockIdProperty, content: { type: 'string', description: '新的块内容' } }, ['documentId', 'blockId', 'content']),
  285. execute: (input) => run(() => {
  286. const documentId = requiredString(input, 'documentId');
  287. const blockId = requiredString(input, 'blockId');
  288. const updates: UpdateBlockRequest = { content: requiredString(input, 'content') };
  289. return blockService.updateBlock(documentId, blockId, updates).then((result) => {
  290. window.dispatchEvent(new CustomEvent(BLOCK_UPDATED_EVENT, {
  291. detail: { documentId, blockId, updates },
  292. }));
  293. return result;
  294. });
  295. }),
  296. },
  297. {
  298. name: 'delete_block',
  299. title: '删除内容块',
  300. description: '删除指定文档块。需要用户确认。',
  301. requiresConfirmation: true,
  302. inputSchema: objectSchema({ documentId: documentIdProperty, blockId: blockIdProperty }, ['documentId', 'blockId']),
  303. execute: (input) => run(() => {
  304. const documentId = requiredString(input, 'documentId');
  305. const blockId = requiredString(input, 'blockId');
  306. return blockService.deleteBlock(documentId, blockId).then(() => {
  307. window.dispatchEvent(new CustomEvent(BLOCK_DELETED_EVENT, {
  308. detail: { documentId, blockId },
  309. }));
  310. return { message: 'Block deleted successfully' };
  311. });
  312. }),
  313. },
  314. {
  315. name: 'export_document',
  316. title: '导出文档',
  317. description: '将文档导出为 Word 文件。需要用户确认。',
  318. requiresConfirmation: true,
  319. inputSchema: objectSchema({ documentId: documentIdProperty }, ['documentId']),
  320. execute: (input) => run(() => exportToWord({ documentId: requiredString(input, 'documentId') })),
  321. },
  322. {
  323. name: 'download_export_record',
  324. title: '下载导出记录',
  325. description: '下载指定导出记录的文件。需要用户确认。',
  326. requiresConfirmation: true,
  327. inputSchema: objectSchema({ recordId: { type: 'string', description: '导出记录 ID' } }, ['recordId']),
  328. execute: (input) => run(async () => {
  329. const recordId = requiredString(input, 'recordId');
  330. await exportRecordService.download(recordId, DEFAULT_USER_ID);
  331. return { recordId, message: '下载已开始' };
  332. }),
  333. },
  334. ];
  335. const browserTools = (): ReadonlyArray<Omit<WebMcpTool, 'requiresConfirmation'>> =>
  336. tools.map((tool) => ({
  337. name: tool.name,
  338. title: tool.title,
  339. description: tool.description,
  340. inputSchema: tool.inputSchema,
  341. readOnlyHint: tool.readOnlyHint,
  342. untrustedContentHint: tool.untrustedContentHint,
  343. execute: (input) => {
  344. if (tool.requiresConfirmation) {
  345. const activityId = startWebMcpActivity(tool.name, input);
  346. const result = { ok: false, error: '该 WebMCP 工具需要当前页面用户确认' };
  347. finishWebMcpActivity(activityId, result);
  348. return Promise.resolve(result);
  349. }
  350. return executeWebMcpTool(tool.name, input);
  351. },
  352. }));
  353. export const getWebMcpTools = (): ReadonlyArray<WebMcpTool> => tools;
  354. export const getWebMcpTool = (name: string): WebMcpTool | undefined => tools.find((tool) => tool.name === name);
  355. export const executeWebMcpTool = async (
  356. name: string,
  357. input: unknown,
  358. options: WebMcpExecutionOptions = {}
  359. ): Promise<WebMcpToolResult> => {
  360. if (!isRecord(input)) {
  361. return { ok: false, error: 'WebMCP 工具参数必须是对象' };
  362. }
  363. const activityId = startWebMcpActivity(name, input);
  364. const tool = getWebMcpTool(name);
  365. if (!tool) {
  366. const result = { ok: false, error: `未知的 WebMCP 工具: ${name}` };
  367. finishWebMcpActivity(activityId, result);
  368. return result;
  369. }
  370. if (tool.requiresConfirmation && !options.confirmed) {
  371. const result = { ok: false, error: '该 WebMCP 工具需要当前页面用户确认' };
  372. finishWebMcpActivity(activityId, result);
  373. return result;
  374. }
  375. const validationError = validateToolInput(tool, input);
  376. if (validationError) {
  377. const result = { ok: false, error: validationError };
  378. finishWebMcpActivity(activityId, result);
  379. return result;
  380. }
  381. try {
  382. const result = await tool.execute(input);
  383. finishWebMcpActivity(activityId, result);
  384. return result;
  385. } catch (error) {
  386. const result = { ok: false, error: error instanceof Error ? error.message : '工具执行失败' };
  387. finishWebMcpActivity(activityId, result);
  388. return result;
  389. }
  390. };
  391. export const registerWebMcpTools = (): Promise<WebMcpRegistrationResult> => {
  392. if (registrationPromise) return registrationPromise;
  393. registrationPromise = (async () => {
  394. const modelContext = (navigator as WebMcpNavigator).modelContext;
  395. if (!modelContext) return { supported: false, registeredTools: [], error: '当前浏览器未提供 navigator.modelContext' };
  396. try {
  397. const definitions = browserTools();
  398. if (modelContext.provideContext) await modelContext.provideContext({ tools: definitions });
  399. else if (modelContext.registerTool) for (const tool of definitions) await modelContext.registerTool(tool);
  400. else return { supported: true, registeredTools: [], error: 'WebMCP API 不支持工具注册' };
  401. return { supported: true, registeredTools: tools.map((tool) => tool.name) };
  402. } catch (error) {
  403. console.warn('[WebMCP] 工具注册失败,编辑器将继续运行', error);
  404. return { supported: true, registeredTools: [], error: error instanceof Error ? error.message : '工具注册失败' };
  405. }
  406. })();
  407. return registrationPromise;
  408. };
  409. export default tools;