add_document
Add a single document to the MCP Knowledge Base Server to index and process its content for querying. Supports formats like PDF, DOCX, TXT, and HTML.
Instructions
添加单个文档到知识库
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file_path | Yes | 文档文件路径 |
Input Schema (JSON Schema)
{
"properties": {
"file_path": {
"description": "文档文件路径",
"type": "string"
}
},
"required": [
"file_path"
],
"type": "object"
}
Implementation Reference
- src/knowledge-base.ts:25-35 (handler)Core handler logic for the add_document tool: processes the document using DocumentProcessor, stores it in memory map, saves index to disk, returns success boolean.async addDocument(filePath: string): Promise<boolean> { const result = await this.processor.processDocument(filePath); if (result.success && result.document) { this.documents.set(result.document.id, result.document); await this.saveIndex(); return true; } return false; }
- src/mcp-server.ts:160-173 (handler)MCP server tool dispatch handler for 'add_document': extracts file_path from arguments, calls knowledgeBase.addDocument, formats and returns response content.case 'add_document': { const { file_path } = args as { file_path: string }; const success = await this.knowledgeBase.addDocument(file_path); return { content: [ { type: 'text', text: success ? `文档 "${file_path}" 已成功添加到知识库` : `添加文档 "${file_path}" 失败` } ] }; }
- src/mcp-server.ts:46-58 (registration)Registration of the 'add_document' tool in the ListToolsRequestSchema handler, defining name, description, and inputSchema.{ name: 'add_document', description: '添加单个文档到知识库', inputSchema: { type: 'object', properties: { file_path: { type: 'string', description: '文档文件路径' } }, required: ['file_path'] }
- src/document-processor.ts:11-46 (helper)Supporting utility that processes a document file: checks format, extracts text content based on type (PDF/DOCX/TXT/HTML), generates ID/title/metadata, returns Document or error.async processDocument(filePath: string): Promise<DocumentProcessingResult> { try { const ext = path.extname(filePath).toLowerCase(); if (!this.supportedFormats.includes(ext)) { return { success: false, error: `不支持的文件格式: ${ext}` }; } const content = await this.extractContent(filePath, ext); const title = this.extractTitle(filePath, content); const document: Document = { id: this.generateDocumentId(filePath), title, content, filePath, fileType: ext.slice(1) as Document['fileType'], metadata: await this.extractMetadata(filePath), createdAt: new Date(), updatedAt: new Date() }; return { success: true, document }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : '未知错误' }; } }