在之前的教程中,我們已經介紹了 MCP(Model Context Protocol)的基本概念及其核心組件。在本篇教程中,我們將通過一個實際案例,演示如何運用 MCP 構建一個能夠分析學術論文的智能體。這個智能體將具備讀取 PDF 文件、提取關鍵信息的功能,并能回答用戶有關論文內容的問題。
一、項目概述
我們將構建一個具有以下功能的論文分析智能體:
讀取和解析 PDF 論文
提取論文的基本信息(標題、作者、摘要等)
分析論文內容并回答用戶問題
提供論文關鍵信息的總結
二、環境準備
首先,確保你已經安裝了以下工具:
Node.js (版本 18 或更高)
npm 或 yarn
Claude 桌面應用或支持 MCP 的其它客戶端
創建項目目錄并初始化:
mkdir paper-analysis-agent
cd?paper-analysis-agent
npm init -y
安裝所需依賴:
npm install @modelcontextprotocol/server-nodejs pdf-parse
三、實現 MCP 服務器
1. 創建服務器入口文件
創建?server.js
?文件:
const?{ Server } =?require('@modelcontextprotocol/server-nodejs');
const?{ analyzePaper, extractPaperInfo } =?require('./paperAnalyzer');class?PaperAnalysisServer?{
constructor() {this.server =?new?Server({name:?'paper-analysis-server',version:?'1.0.0',},{capabilities: {resources: {},tools: {},},});this.setupResources();this.setupTools();this.setupErrorHandling();}setupResources() {// 資源相關設置將在后續實現}setupTools() {this.server.setRequestHandler('tools/call',?async?(request) => {const?{ name,?arguments: args } = request.params;try?{switch?(name) {case'analyze_paper':returnawaitthis.analyzePaper(args);case'extract_paper_info':returnawaitthis.extractPaperInfo(args);case'summarize_paper':returnawaitthis.summarizePaper(args);default:thrownewError(`Unknown tool:?${name}`);}}?catch?(error) {return?{content: [{type:?'text',text:?`Error:?${error.message}`,},],isError:?true,};}});}setupErrorHandling() {this.server.onerror =?(error) =>?{console.error('Server error:', error);};}async?analyzePaper(args) {const?{ pdfPath, question } = args;if?(!pdfPath) {thrownewError('PDF path is required');}const?analysis =?await?analyzePaper(pdfPath, question);return?{content: [{type:?'text',text: analysis,},],};}async?extractPaperInfo(args) {const?{ pdfPath } = args;if?(!pdfPath) {thrownewError('PDF path is required');}const?info =?await?extractPaperInfo(pdfPath);return?{content: [{type:?'text',text:?JSON.stringify(info,?null,?2),},],};}async?summarizePaper(args) {const?{ pdfPath } = args;if?(!pdfPath) {thrownewError('PDF path is required');}// 這里實現論文總結邏輯const?summary =?"論文總結內容將在這里顯示";return?{content: [{type:?'text',text: summary,},],};}async?run() {awaitthis.server.connect();console.log('Paper Analysis MCP Server is running...');}
}const?server =?new?PaperAnalysisServer();
server.run().catch(console.error);
2. 實現論文分析器
創建?paperAnalyzer.js
?文件:
const?fs =?require('fs');
const?pdf =?require('pdf-parse');class?PaperAnalyzer?{
constructor() {this.cache =?newMap();}async?parsePDF(pdfPath) {if?(this.cache.has(pdfPath)) {returnthis.cache.get(pdfPath);}try?{const?dataBuffer = fs.readFileSync(pdfPath);const?data =?await?pdf(dataBuffer);const?result = {text: data.text,info: data.info,metadata: data.metadata,};this.cache.set(pdfPath, result);return?result;}?catch?(error) {thrownewError(`Failed to parse PDF:?${error.message}`);}}async?extractPaperInfo(pdfPath) {const?paperData =?awaitthis.parsePDF(pdfPath);const?text = paperData.text;// 簡單的信息提取邏輯(實際應用中可能需要更復雜的 NLP 處理)const?titleMatch = text.match(/^(.+)\n\n(?:Abstract|ABSTRACT)/m);const?abstractMatch = text.match(/(?:Abstract|ABSTRACT)[\s\S]*?(\n\n|$)/i);const?authorMatch = text.match(/(?:Authors?|By)[:\s]+(.+?)(?=\n\n)/i);return?{title: titleMatch ? titleMatch[1].trim() :?'Unknown',authors: authorMatch ? authorMatch[1].trim() :?'Unknown',abstract: abstractMatch ? abstractMatch[0].replace(/(Abstract|ABSTRACT)/i,?'').trim() :?'Unknown',pageCount: paperData.info.Pages ||?'Unknown',};}async?analyzeContent(pdfPath, question) {const?paperData =?awaitthis.parsePDF(pdfPath);// 這里可以實現更復雜的內容分析邏輯// 目前只是簡單返回包含問題的響應return`關于論文的分析結果:
問題:?${question}
回答: 根據論文內容,這里應該包含針對問題的詳細分析。`;}
}// 創建單例實例
const?analyzer =?new?PaperAnalyzer();// 導出函數
asyncfunction?analyzePaper(pdfPath, question)?{
returnawait?analyzer.analyzeContent(pdfPath, question);
}asyncfunction?extractPaperInfo(pdfPath)?{
returnawait?analyzer.extractPaperInfo(pdfPath);
}module.exports = {analyzePaper,extractPaperInfo,
};
四、配置 MCP 客戶端
創建?claude_desktop_config.json
?文件(位于 Claude 桌面應用的配置目錄):
{"mcpServers": {"paper-analysis": {"command":?"node","args": ["/path/to/your/paper-analysis-agent/server.js"],"env": {}}}
}
五、測試智能體
創建測試腳本?test.js
:
const?{ analyzePaper, extractPaperInfo } =?require('./paperAnalyzer');asyncfunction?test()?{
try?{// 測試信息提取const?info =?await?extractPaperInfo('./sample.pdf');console.log('論文信息:', info);// 測試內容分析const?analysis =?await?analyzePaper('./sample.pdf','這篇論文的主要貢獻是什么?');console.log('分析結果:', analysis);}?catch?(error) {console.error('測試失敗:', error);}
}test();
六、運行和使用
啟動 MCP 服務器:
node server.js
在 Claude 桌面應用中,你現在可以使用以下工具:
analyze_paper
: 分析論文內容并回答問題extract_paper_info
: 提取論文基本信息summarize_paper
: 生成論文總結
示例對話:
用戶: 請分析這篇論文?"/path/to/paper.pdf",并告訴我它的主要研究方法。Claude: 我將使用論文分析工具來幫您解答這個問題。[調用 analyze_paper 工具]
七、進階功能擴展
你可以進一步擴展這個智能體:
集成 NLP 庫:添加自然語言處理功能,如實體識別、關系提取等
添加引用分析:解析論文的參考文獻和引用關系
實現可視化:生成論文內容的可視化分析報告
添加緩存機制:提高重復查詢的響應速度
支持多種格式:擴展支持 Word、HTML 等其他文檔格式
八、總結
通過本教程,你學會了如何:
創建一個基于 MCP 的論文分析智能體
實現 PDF 解析和內容提取功能
配置 MCP 服務器與 Claude 客戶端的集成
構建實用的論文分析工具
這個項目展示了 MCP 在實際應用中的強大能力,通過組合不同的工具和資源,可以構建出專門針對特定領域的高效智能體。
記得在實際應用中處理錯誤情況、添加適當的日志記錄,并考慮性能優化和安全問題。