从零构建MCP服务器:为Claude Code集成英国央行数据查询工具

发布时间:2026/7/26 18:50:00
从零构建MCP服务器:为Claude Code集成英国央行数据查询工具 在 AI 开发领域让大语言模型LLM安全、可控地访问外部工具和数据源一直是个核心挑战。传统方法往往需要为每个工具编写特定的插件或适配器不仅开发成本高而且难以在不同模型间复用。Model Context ProtocolMCP正是为了解决这一问题而设计的开放标准它定义了一套统一的接口规范让 LLM 能够通过标准化的方式调用各种外部资源。Claude Code 作为 Anthropic 推出的代码助手工具原生支持 MCP 协议这意味着开发者可以为其配置各种 MCP 服务器来扩展功能。本文将详细介绍如何从零开始构建一个 MCP 服务器并将其集成到 Claude Code 中最终实现通过自然语言查询英国央行Bank of England的公开数据。1. 理解 MCP 协议的核心概念和工作原理MCP 协议的核心思想是将 LLM 与外部工具的交互标准化。它采用客户端-服务器架构其中 Claude Code 作为 MCP 客户端而各种工具服务作为 MCP 服务器。这种设计有几个关键优势工具无关性任何符合 MCP 标准的工具都可以被 Claude Code 调用无需为每个工具开发特定插件安全可控MCP 服务器运行在独立进程中通过明确的权限控制来管理资源访问跨模型兼容同一套 MCP 服务器可以支持不同的 LLM 客户端提高开发效率MCP 协议定义了几种核心资源类型Tools工具可供 LLM 调用的函数如数据查询、计算等Resources资源LLM 可以读取的静态或动态数据源Prompts提示词可复用的对话模板Data Sources数据源结构化的信息查询接口在实际项目中构建 MCP 服务器主要涉及实现这些资源的接口并通过标准化的 JSON-RPC over STDIO 与客户端通信。2. 环境准备与开发工具配置构建 MCP 服务器需要准备合适的开发环境。以下是推荐的技术栈和配置步骤2.1 Node.js 和 npm 环境配置MCP 服务器可以使用多种语言开发但 Node.js 因其丰富的生态和便捷的包管理成为首选。首先需要安装 Node.js 环境# 检查当前 Node.js 版本 node --version # 检查 npm 版本 npm --version如果系统提示“npm : 无法将npm项识别为 cmdlet、函数、脚本文件或可运行程序的名称”说明 Node.js 没有正确安装或环境变量配置有误。解决方案从 Node.js 官网下载 LTS 版本安装包安装时勾选“自动安装必要的工具”选项安装完成后重启终端验证安装是否成功对于 Windows PowerShell 执行策略导致的“无法加载文件 npm.ps1”错误可以通过以下命令解决# 以管理员身份运行 PowerShell然后执行 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser2.2 开发工具选择与配置VS Code 是开发 MCP 服务器的理想选择它提供了完善的 TypeScript 支持和调试功能安装 VS Code 并确保以下扩展已安装TypeScript 和 JavaScript Language FeaturesESLintPrettier - Code formatter配置 VS Code 的工作区设置.vscode/settings.json{ typescript.preferences.includePackageJsonAutoImports: auto, editor.formatOnSave: true, editor.codeActionsOnSave: { source.fixAll.eslint: true } }2.3 项目初始化与依赖安装创建项目目录并初始化 npm 项目# 创建项目目录 mkdir bank-of-england-mcp cd bank-of-england-mcp # 初始化 npm 项目 npm init -y # 安装 MCP SDK 和类型定义 npm install modelcontextprotocol/sdk npm install -D typescript types/node # 安装开发依赖 npm install -D eslint typescript-eslint/parser typescript-eslint/eslint-plugin初始化 TypeScript 配置tsconfig.json{ compilerOptions: { target: ES2022, module: CommonJS, outDir: ./dist, rootDir: ./src, strict: true, esModuleInterop: true, skipLibCheck: true, forceConsistentCasingInFileNames: true }, include: [src/**/*], exclude: [node_modules, dist] }3. 构建英国央行数据查询 MCP 服务器英国央行提供了丰富的公开数据 API包括利率决策、通胀数据、货币政策报告等。我们将构建一个 MCP 服务器来封装这些 API 的访问。3.1 项目结构设计首先规划清晰的项目结构bank-of-england-mcp/ ├── src/ │ ├── index.ts # 服务器入口文件 │ ├── tools/ # 工具实现 │ │ └── boeTools.ts # 英国央行专用工具 │ ├── types/ # 类型定义 │ │ └── boeTypes.ts # API 响应类型 │ └── utils/ # 工具函数 │ └── apiClient.ts # API 客户端 ├── package.json ├── tsconfig.json └── README.md3.2 实现核心 API 客户端创建 API 客户端来处理与英国央行数据接口的通信// src/utils/apiClient.ts import axios, { AxiosInstance } from axios; export interface BOEApiResponseT { data: T; status: string; } export class BOEApiClient { private client: AxiosInstance; constructor() { this.client axios.create({ baseURL: https://www.bankofengland.co.uk/boeapps/apiapi, timeout: 10000, headers: { Accept: application/json, User-Agent: MCP-Server/1.0 } }); } async getInterestRates(): Promiseany { const response await this.client.get(/v1/rates/bankrate); return response.data; } async getInflationData(): Promiseany { const response await this.client.get(/v1/data/inflation); return response.data; } async getMonetaryPolicySummary(): Promiseany { const response await this.client.get(/v1/publications/mpreport/summary); return response.data; } }3.3 实现 MCP 工具定义具体的 MCP 工具这些工具将暴露给 Claude Code 调用// src/tools/boeTools.ts import { Tool } from modelcontextprotocol/sdk; import { BOEApiClient } from ../utils/apiClient; export class BOETools { private apiClient: BOEApiClient; constructor() { this.apiClient new BOEApiClient(); } getInterestRateTool(): Tool { return { name: get_boe_interest_rate, description: 获取英国央行最新基准利率数据, inputSchema: { type: object, properties: { period: { type: string, description: 时间周期如 latest、1m、3m 等, default: latest } } } }; } getInflationTool(): Tool { return { name: get_boe_inflation, description: 获取英国通胀率数据, inputSchema: { type: object, properties: { metric: { type: string, enum: [cpi, rpi, cpih], description: 通胀指标类型 } } } }; } // 工具方法的实际实现 async executeTool(name: string, args: any): Promiseany { switch (name) { case get_boe_interest_rate: return await this.apiClient.getInterestRates(); case get_boe_inflation: return await this.apiClient.getInflationData(); default: throw new Error(Unknown tool: ${name}); } } }3.4 构建完整的 MCP 服务器将各个组件整合成完整的 MCP 服务器// src/index.ts import { Server } from modelcontextprotocol/sdk/server/index.js; import { StdioServerTransport } from modelcontextprotocol/sdk/server/stdio.js; import { BOETools } from ./tools/boeTools.js; class BOEMCPServer { private server: Server; private tools: BOETools; constructor() { this.server new Server( { name: bank-of-england-mcp, version: 1.0.0, }, { capabilities: { tools: {}, }, } ); this.tools new BOETools(); this.setupToolHandlers(); } private setupToolHandlers(): void { // 注册工具列表 this.server.setRequestHandler( tools/list, async () ({ tools: [ this.tools.getInterestRateTool(), this.tools.getInflationTool(), ], }) ); // 处理工具调用 this.server.setRequestHandler( tools/call, async (request) { if (!request.params.name || !request.params.arguments) { throw new Error(Invalid tool call request); } try { const result await this.tools.executeTool( request.params.name, request.params.arguments ); return { content: [ { type: text, text: JSON.stringify(result, null, 2), }, ], }; } catch (error) { return { content: [ { type: text, text: Error: ${error instanceof Error ? error.message : Unknown error}, }, ], isError: true, }; } } ); } async run(): Promisevoid { const transport new StdioServerTransport(); await this.server.connect(transport); console.error(Bank of England MCP server running on stdio); } } // 启动服务器 const server new BOEMCPServer(); server.run().catch(console.error);3.5 配置 package.json 脚本更新 package.json 添加构建和运行脚本{ name: bank-of-england-mcp, version: 1.0.0, type: module, scripts: { build: tsc, start: node dist/index.js, dev: tsc --watch }, bin: { bank-of-england-mcp: ./dist/index.js } }4. 在 Claude Code 中配置和使用 MCP 服务器构建完 MCP 服务器后需要将其配置到 Claude Code 中才能实际使用。4.1 安装和配置 Claude Code首先确保已安装 Claude Code 扩展在 VS Code 中打开扩展面板CtrlShiftX搜索 Claude Code 并安装重启 VS Code 使扩展生效4.2 配置 MCP 服务器在 VS Code 的设置中配置 MCP 服务器。可以通过 UI 设置或直接编辑 settings.json{ claude.code.mcpServers: { bank-of-england: { command: node, args: [/path/to/your/bank-of-england-mcp/dist/index.js], env: { NODE_ENV: production } } } }如果已将 MCP 服务器发布为 npm 包可以直接通过包名配置{ claude.code.mcpServers: { bank-of-england: { command: npx, args: [bank-of-england-mcp] } } }4.3 验证配置是否生效配置完成后重启 Claude Code 会话。在聊天窗口中输入测试命令bank-of-england 有什么可用的工具Claude 应该能够列出可用的工具列表。也可以直接询问请使用英国央行数据工具查询当前基准利率4.4 实际使用示例配置成功后就可以通过自然语言与 Claude 交互来查询英国央行数据用户请帮我分析一下英国最近的货币政策动向 Claude我将使用英国央行 MCP 工具来获取最新数据... [调用 get_boe_interest_rate 工具] [调用 get_boe_inflation 工具] 根据最新数据英国央行当前基准利率为 X.X%通胀率为 Y.Y%...5. 常见问题排查与解决方案在开发和配置 MCP 服务器过程中可能会遇到各种问题。以下是常见问题的排查指南5.1 MCP 服务器启动失败问题现象Claude Code 提示无法连接 MCP 服务器或服务器立即退出。排查步骤检查 Node.js 路径和权限# 验证 Node.js 可执行文件路径 which node # 验证脚本是否有执行权限 chmod x dist/index.js检查依赖是否完整安装# 清理并重新安装依赖 rm -rf node_modules package-lock.json npm install检查 TypeScript 编译是否正确npm run build # 查看是否有编译错误5.2 Claude Code 无法识别工具问题现象配置了 MCP 服务器但 Claude 提示没有可用工具。排查步骤验证 MCP 服务器配置格式是否正确检查服务器日志输出# 手动运行服务器查看输出 node dist/index.js确认工具注册逻辑正确// 确保工具名称和描述符合规范 this.server.setRequestHandler(tools/list, async () ({ tools: [/* 工具数组 */] }));5.3 API 请求失败或超时问题现象工具调用返回错误或超时。解决方案增加超时时间配置const client axios.create({ timeout: 30000, // 30秒超时 });添加重试机制async function withRetryT( operation: () PromiseT, maxRetries: number 3 ): PromiseT { for (let i 0; i maxRetries; i) { try { return await operation(); } catch (error) { if (i maxRetries - 1) throw error; await new Promise(resolve setTimeout(resolve, 1000 * (i 1))); } } throw new Error(Max retries exceeded); }5.4 权限和路径问题问题现象Windows 系统下出现路径或权限错误。解决方案使用绝对路径而非相对路径处理 Windows 路径分隔符问题import path from path; // 使用 path.join 处理路径 const configPath path.join(__dirname, config.json);以管理员身份运行 VS Code如果需要访问受限目录6. 生产环境最佳实践将 MCP 服务器用于生产环境时需要考虑更多因素6.1 错误处理和日志记录实现完善的错误处理和日志系统class Logger { static error(message: string, error?: Error): void { console.error(JSON.stringify({ timestamp: new Date().toISOString(), level: ERROR, message, error: error ? error.message : undefined })); } static info(message: string): void { console.error(JSON.stringify({ timestamp: new Date().toISOString(), level: INFO, message })); } }6.2 性能优化和缓存策略为 API 调用添加缓存机制减少请求次数import NodeCache from node-cache; class CachedBOEApiClient extends BOEApiClient { private cache: NodeCache; constructor() { super(); this.cache new NodeCache({ stdTTL: 300 }); // 5分钟缓存 } async getInterestRates(): Promiseany { const cacheKey interest_rates; let data this.cache.get(cacheKey); if (!data) { data await super.getInterestRates(); this.cache.set(cacheKey, data); } return data; } }6.3 安全性考虑输入验证对所有输入参数进行严格验证速率限制实现 API 调用频率限制敏感信息处理避免在日志中记录敏感数据import rateLimit from express-rate-limit; const limiter rateLimit({ windowMs: 15 * 60 * 1000, // 15分钟 max: 100 // 限制每个IP每15分钟最多100次请求 });6.4 测试策略编写完整的单元测试和集成测试// tests/boeTools.test.ts import { BOETools } from ../src/tools/boeTools; describe(BOETools, () { let tools: BOETools; beforeEach(() { tools new BOETools(); }); test(should return interest rate tool definition, () { const tool tools.getInterestRateTool(); expect(tool.name).toBe(get_boe_interest_rate); expect(tool.description).toContain(基准利率); }); });7. 扩展方向和进阶应用基础 MCP 服务器完成后可以考虑以下扩展方向7.1 添加更多数据源除了英国央行可以集成其他金融数据源美联储经济数据FRED欧洲央行统计数据国际货币基金组织IMF数据集7.2 实现数据分析工具不仅提供原始数据还可以添加分析功能趋势分析工具数据可视化生成预测模型集成7.3 支持更多 MCP 资源类型除了工具还可以实现其他 MCP 资源提示词资源预定义的金融分析对话模板数据源资源结构化的历史数据查询接口7.4 发布为 npm 包将成熟的 MCP 服务器发布到 npm registry准备 package.json 的发布配置添加详细的 README 文档配置 CI/CD 自动化发布流程添加版本管理和变更日志通过 MCP 协议构建专用工具服务器能够显著提升 Claude Code 在特定领域的实用性。这种模式不仅适用于金融数据查询还可以扩展到代码分析、文档处理、系统监控等各种场景。关键在于理解业务需求设计合理的工具接口并确保实现的稳定性和性能。在实际项目中建议先从最小可行产品开始逐步迭代完善功能。同时要密切关注 MCP 协议标准的演进及时适配新特性和最佳实践。