2025-08-27

從零開始學(xué)MCP(7) | 實戰(zhàn):用 MCP 構(gòu)建論文分析智能體

在之前的教程中,我們已經(jīng)了解了 MCP(Model Context Protocol)的基本概念和核心組件。本篇教程將通過一個實際案例,展示如何使用 MCP 構(gòu)建一個能夠分析學(xué)術(shù)論文的智能體。這個論文分析智能體將能夠讀取 PDF 論文,提取關(guān)鍵信息,并回答用戶關(guān)于論文內(nèi)容的問題。

一、項目概述

我們將構(gòu)建一個具有以下功能的論文分析智能體:

  1. 讀取和解析 PDF 論文
  2. 提取論文的基本信息(標題、作者、摘要等)
  3. 分析論文內(nèi)容并回答用戶問題
  4. 提供論文關(guān)鍵信息的總結(jié)

二、環(huán)境準備

首先,確保你已經(jīng)安裝了以下工具:

  • Node.js (版本 18 或更高)
  • npm 或 yarn
  • Claude 桌面應(yīng)用或支持 MCP 的其它客戶端

創(chuàng)建項目目錄并初始化:

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left; visibility: visible;">mkdir paper-analysis-agent cd paper-analysis-agent npm init -y </pre>

安裝所需依賴:

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">npm install @modelcontextprotocol/server-nodejs pdf-parse </pre>

三、實現(xiàn) MCP 服務(wù)器

1. 創(chuàng)建服務(wù)器入口文件

創(chuàng)建 server.js 文件:

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">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() { // 資源相關(guān)設(shè)置將在后續(xù)實現(xiàn) } 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'); } // 這里實現(xiàn)論文總結(jié)邏輯 const summary = "論文總結(jié)內(nèi)容將在這里顯示"; 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); </pre>

2. 實現(xiàn)論文分析器

創(chuàng)建 paperAnalyzer.js 文件:

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">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; // 簡單的信息提取邏輯(實際應(yīng)用中可能需要更復(fù)雜的 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); // 這里可以實現(xiàn)更復(fù)雜的內(nèi)容分析邏輯 // 目前只是簡單返回包含問題的響應(yīng) return關(guān)于論文的分析結(jié)果: 問題: ${question} 回答: 根據(jù)論文內(nèi)容,這里應(yīng)該包含針對問題的詳細分析。; } } // 創(chuàng)建單例實例 const analyzer = new PaperAnalyzer(); // 導(dǎo)出函數(shù) asyncfunction analyzePaper(pdfPath, question) { returnawait analyzer.analyzeContent(pdfPath, question); } asyncfunction extractPaperInfo(pdfPath) { returnawait analyzer.extractPaperInfo(pdfPath); } module.exports = { analyzePaper, extractPaperInfo, };` </pre>

四、配置 MCP 客戶端

創(chuàng)建 claude_desktop_config.json 文件(位于 Claude 桌面應(yīng)用的配置目錄):

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">{ "mcpServers": { "paper-analysis": { "command": "node", "args": ["/path/to/your/paper-analysis-agent/server.js"], "env": {} } } } </pre>

五、測試智能體

創(chuàng)建測試腳本 test.js

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">const { analyzePaper, extractPaperInfo } = require('./paperAnalyzer'); asyncfunction test() { try { // 測試信息提取 const info = await extractPaperInfo('./sample.pdf'); console.log('論文信息:', info); // 測試內(nèi)容分析 const analysis = await analyzePaper( './sample.pdf', '這篇論文的主要貢獻是什么?' ); console.log('分析結(jié)果:', analysis); } catch (error) { console.error('測試失敗:', error); } } test(); </pre>

六、運行和使用

  1. 啟動 MCP 服務(wù)器:

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">node server.js </pre>

  1. 在 Claude 桌面應(yīng)用中,你現(xiàn)在可以使用以下工具:
  • analyze_paper: 分析論文內(nèi)容并回答問題
  • extract_paper_info: 提取論文基本信息
  • summarize_paper: 生成論文總結(jié)

示例對話:

<pre data-tool="mdnice編輯器" style="-webkit-tap-highlight-color: transparent; margin: 10px 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px; text-align: left;">用戶: 請分析這篇論文 "/path/to/paper.pdf",并告訴我它的主要研究方法。 Claude: 我將使用論文分析工具來幫您解答這個問題。 [調(diào)用 analyze_paper 工具] </pre>

七、進階功能擴展

你可以進一步擴展這個智能體:

  1. 集成 NLP 庫:添加自然語言處理功能,如實體識別、關(guān)系提取等
  2. 添加引用分析:解析論文的參考文獻和引用關(guān)系
  3. 實現(xiàn)可視化:生成論文內(nèi)容的可視化分析報告
  4. 添加緩存機制:提高重復(fù)查詢的響應(yīng)速度
  5. 支持多種格式:擴展支持 Word、HTML 等其他文檔格式

八、總結(jié)

通過本教程,你學(xué)會了如何:

  1. 創(chuàng)建一個基于 MCP 的論文分析智能體
  2. 實現(xiàn) PDF 解析和內(nèi)容提取功能
  3. 配置 MCP 服務(wù)器與 Claude 客戶端的集成
  4. 構(gòu)建實用的論文分析工具

這個項目展示了 MCP 在實際應(yīng)用中的強大能力,通過組合不同的工具和資源,可以構(gòu)建出專門針對特定領(lǐng)域的高效智能體。

記得在實際應(yīng)用中處理錯誤情況、添加適當(dāng)?shù)娜罩居涗洠⒖紤]性能優(yōu)化和安全問題。

推薦學(xué)習(xí)

行業(yè)首個「知識圖譜+測試開發(fā)」深度整合課程【人工智能測試開發(fā)訓(xùn)練營】,贈送智能體工具。提供企業(yè)級解決方案,人工智能的管理平臺部署,實現(xiàn)智能化測試,落地大模型,實現(xiàn)從傳統(tǒng)手工轉(zhuǎn)向用AI和自動化來實現(xiàn)測試,提升效率和質(zhì)量。

image.png

推薦閱讀
2025大語言模型部署實戰(zhàn)指南:從個人筆記本到企業(yè)級服務(wù)的全棧方案 - 霍格沃茲測試開發(fā)學(xué)社 - 博客園
Playwright實戰(zhàn):寫UI自動化腳本,速度直接起飛 - 霍格沃茲測試開發(fā)學(xué)社 - 博客園
2025大模型應(yīng)用平臺選型指南:從個人助手到企業(yè)級智能體,5大平臺場景化拆解 - 霍格沃茲測試開發(fā)學(xué)社 - 博客園

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容