mcp-server-base
MCP Server Base v3.0 — 扩展与企业级 (2026)
使用最新技术栈的现代 Model Context Protocol 服务器:
MCP SDK
1.12+—McpServer高级 API +StreamableHTTPServerTransport(新)和StdioServerTransportTypeScript 5.7 ESM +
NodeNext模块Zod 验证 → 自动 JSON Schema + 环境变量验证(
src/config.ts:1)Express 4 + helmet + CORS 白名单 + 速率限制 + 健康/就绪 + Admin UI
双传输:STDIO(Claude Desktop)和 Streamable HTTP(远程,2025-03 规范,无状态 + 通过 RedisEventStore 实现有状态可恢复)
结构化工具/资源/提示模块 + RAG 混合(BM25+向量)、Web(缓存)、GitHub 集成
Plugin SDK(
src/plugin/index.ts:1)+ 集成(slack/notion/linear)、Registry(smithery.yaml、mcpName)、Prompt Playground 位于/adminv3.0 企业版:多租户(
X-Tenant-Id、命名空间存储)、SSO OIDC、控制平面 CRUD、集群模式、Prometheus/Grafana 技术栈OTEL 追踪/指标(
src/utils/otel.ts:1)、Tasks(实验性 +create_task)、k6 负载测试tsx监视、vitest(178 个测试,88% 覆盖率)、优雅关闭、docker-compose(redis、postgres、qdrant、otel-collector、prometheus、grafana)
🚀 快速开始
npm install
npm run build
# STDIO (for Claude Desktop, Cursor, opencode, etc.)
npm start
# HTTP (Streamable HTTP - latest)
npm run start:http
# → http://localhost:3000/mcp
# → health http://localhost:3000/health开发
npm run dev # stdio watch
npm run dev:http # http watch (Streamable HTTP at http://localhost:3000/mcp)
npm test # unit + e2e (InMemory + HTTP)
npm run test:coverage # coverage 80% thresholds
npm run lint # eslint 9 flat config
npm run format:check # prettier
npm run typecheck # tsc --noEmit
npm run buildCI
.github/workflows/ci.yml 在 push/PR 到 main 时运行,使用 Node 20+22 矩阵:lint、format:check、typecheck、test:coverage、build、docker build。
Related MCP server: TokenHub MCP
🔌 传输方式
传输方式 | 用途 | 命令 |
STDIO | 本地客户端(Claude Desktop) |
|
Streamable HTTP | 远程 / Docker / 云 |
|
Streamable HTTP 是取代 SSE(已于 2025 年 3 月弃用)的新标准。
🧰 工具(40)
工具 | 描述 | 输入 |
| 回显消息 |
|
| 加/减/乘/除 |
|
| 当前时间 |
|
| 获取 URL |
|
| 列出 ALLOWED_ROOT 下的文件 |
|
| 读取文件(1MB 限制) |
|
| 写入文件 + 触发资源变更 |
|
| 在文件中搜索文本 |
|
| 在内存中设置 KV |
|
| 获取 KV |
|
| 删除 KV |
|
| 列出 KV | — |
| 清除全部 | — |
| 通过 alasql 执行 SQL(users、notes) |
|
| 列出表行数 | — |
| Shell(白名单,默认禁用) |
|
| 引导演示(联系方式/偏好) |
|
| 采样演示(LLM) |
|
| 摄取文本(分块、嵌入) |
|
| 混合搜索(向量+BM25) |
|
| 列出文档 | — |
| 清除向量存储 | — |
| Brave API(无密钥时模拟) |
|
| Tavily API(无密钥时模拟) |
|
| 缓存的网页获取 |
|
| GitHub 搜索仓库 |
|
| GitHub 获取仓库 |
|
| GitHub 获取问题 |
|
| 创建后台任务 |
|
| 获取任务状态 |
|
| 获取任务结果 |
|
| Slack 频道(插件) | — |
| Slack 发布(插件) |
|
| Slack 搜索(插件) |
|
| Notion 搜索(插件) |
|
| Notion 页面(插件) |
|
| Notion 创建(插件) |
|
| Linear 问题(插件) |
|
| Linear 创建(插件) |
|
| Linear 问题(插件) |
|
📦 资源(6)
config://server-info— 服务器元数据(JSON,现在包含features)greeting://{name}— 动态问候模板file:///{+path}— 沙盒文件(ALLOWED_ROOT),列出 + 补全,file:///notes.txtmemory://{key}— 内存 KV,列出 + 补全db://{table}/{id}— 演示数据库行(users/notes),列出 + 补全docs://{id}— RAG 块(通过rag_ingest摄取),列出 + 补全
💬 提示(4)
code-review— 参数:language、codeexplain-concept— 参数:concept、levelsummarize— 参数:text、length(短/中/长)、style(要点/段落/tldr)research— 参数:topic、depth(概述/深入)、audience(初学者/专家/高管)
⚙️ 客户端配置
Claude Desktop(claude_desktop_config.json)
{
"mcpServers": {
"mcp-server-base": {
"command": "node",
"args": ["/absolute/path/to/mcp-server/dist/index.js"]
}
}
}HTTP 客户端
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
const client = new Client({ name: 'my-client', version: '1.0.0' });
await client.connect(new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp')));
const tools = await client.listTools();Inspector
npm run inspect
# or
npx @modelcontextprotocol/inspector node dist/index.js
npx @modelcontextprotocol/inspector http://localhost:3000/mcp🐳 Docker
# Single container
docker build -t mcp-server-base .
docker run -p 3000:3000 --env TRANSPORT=http mcp-server-base
# Full stack (app + redis + postgres + qdrant) — see docker-compose.yml
docker compose up -d
docker compose logs -f app
# → http://localhost:3000/health, http://localhost:3000/mcp
# → redis :6379, postgres :5432, qdrant :6333RAG 演示(摄取 → 搜索 → docs://)
# via MCP tools (Inspector or Client)
# 1. ingest
rag_ingest { "text": "MCP is Model Context Protocol...", "id": "mcp-intro" }
# 2. search
rag_search { "query": "what is MCP?", "topK": 3 }
# 3. read resource
# docs://mcp-intro → returns ingested text📁 结构
src/
├── index.ts # entry: stdio + http (helmet/cors/rateLimit/auth/RBAC/OTEL/metrics)
├── server.ts # createMcpServer() factory (v2.1.0, instructions)
├── config.ts # zod env (AUTH, CORS, rateLimit, RAG, cache, integrations, OTEL, admin, tasks)
├── types.ts # Zod schemas
├── middleware/auth.ts # AUTH_MODE none|apiKey|bearer
├── middleware/rateLimit.ts
├── middleware/requestId.ts
├── middleware/rbac.ts # RBAC reader/writer/admin + mcpRbacMiddleware (v2.1)
├── observability/otel-real.ts # OTEL NodeSDK init (v2.1)
├── observability/slo.ts # checkSlo() for /health/ready (v2.1)
├── utils/logger.ts # stderr, JSON/text, redaction, child(requestId)
├── utils/eventStore.ts # InMemoryEventStore
├── utils/redisEventStore.ts # RedisEventStore (scale)
├── utils/cache.ts # MemoryCache (TTL) + defaultCache
├── utils/queue.ts # SimpleQueue
├── utils/metrics.ts # prom-client Registry (v2.1)
├── utils/persistence.ts # save/load backup (v2.1)
├── utils/otel.ts # stub OTEL spans/metrics
├── tools/ # 40 tools: echo, fs, memory, db, shell, rag (hybrid), web, github, elicitation, sampling, tasks
│ ├── filesystem.tool.ts, memory.tool.ts, database.tool.ts, shell.tool.ts
│ ├── rag.tool.ts, web.tool.ts, github.tool.ts, elicitation.tool.ts, sampling.tool.ts, tasks.tool.ts
├── plugin/index.ts # Plugin SDK: definePlugin/registerPlugin (v2.2)
├── integrations/ # slack/notion/linear plugins (v2.2)
├── middleware/tenant.ts # Multi-tenant X-Tenant-Id + scoped stores (v3.0)
├── routes/controlplane.ts# Tenants CRUD + key rotation (v3.0)
├── utils/cluster.ts # Cluster mode horizontal scale (v3.0)
├── resources/ # 6 resources: config, greeting, file, memory, db, docs
├── routes/admin.ts # Admin UI + metrics/spans/stores (v2.0) + /metrics Prometheus (v2.1)
└── prompts/ # 4 prompts: code-review, explain-concept, summarize, research添加新工具:创建 src/tools/my.tool.ts → 导出 registerMyTool(server) → 添加到 src/tools/index.ts。
🔐 安全(第二阶段)
Helmet 头(
x-dns-prefetch-control、x-frame-options、x-content-type-options等)通过helmet@7(src/index.ts:1)CORS 白名单(
CORS_ORIGIN=*或逗号列表)以及cors凭据处理(src/config.ts:60)认证
AUTH_MODE=none|apiKey|bearer位于src/middleware/auth.ts:1— 没有有效的X-API-Key或Authorization: Bearer时返回401(健康/就绪和 OPTIONS 除外)速率限制
express-rate-limit(默认 100/15 分钟)在/mcp上 —429 Too Many Requests(src/middleware/rateLimit.ts:1)RequestId(
X-Request-IdrandomUUID、回显头、子日志关联)(src/middleware/requestId.ts:1)Zod 环境变量验证(
src/config.ts:1)—parseEnv()验证PORT、AUTH_MODE、API_KEY跨字段,环境变量无效时快速失败结构化日志 JSON/文本,对
authorization、apiKey、token使用[REDACTED](src/utils/logger.ts:24)可恢复性
InMemoryEventStore(src/utils/eventStore.ts:1)+ 当RESUMABILITY_ENABLED=true时的有状态会话映射(通过Last-Event-ID重放、GET /mcp流、DELETE关闭)Docker 加固 非 root
appuser+HEALTHCHECK(Dockerfile:1)测试:
tests/unit/auth.test.ts、tests/unit/logger.test.ts、tests/unit/eventStore.test.ts、tests/e2e/security.test.ts(helmet/auth/rateLimit/resumability)—67 个测试 → 加上 Phase 5 共 130 个,90.89% 覆盖率
🔗 集成(第四阶段)
缓存
MemoryCacheTTL(src/utils/cache.ts:1)— 用于 web/github 的defaultCache、SimpleQueue(src/utils/queue.ts:1)RAG 本地向量(哈希嵌入 128 维、余弦、块 500/50)位于
src/tools/rag.tool.ts:1—rag_ingest(分块 +sendResourceListChanged)、rag_search(topK、阈值)、rag_list、rag_clear+docs://{id}资源Web
src/tools/web.tool.ts:1—brave_search(无BRAVE_API_KEY时模拟)、tavily_search(模拟)、web_fetch(通过defaultCache、CACHE_TTL_MS缓存)GitHub
src/tools/github.tool.ts:1—github_search_repos、github_get_repo、github_get_issue(缓存,GITHUB_TOKEN用于速率限制)技术栈
docker-compose.yml:1(app + redis:7 + postgres:16 + qdrant:v1.12.4)带健康检查演示
rag_ingest → rag_search → docs://端到端验证于tests/integrations.test.ts:1(21 个测试)
🏢 扩展与企业级(第五阶段 — v3.0)— 新增
多租户
src/middleware/tenant.ts:1—X-Tenant-Id请求头(或?tenant=),当TENANT_REQUIRED=true且缺失时tenantMiddleware返回400,租户隔离的内存getTenantMemory(tid)(独立存储),带命名空间的缓存键tenant:{id}:key,注册表createTenant/deleteTenantSSO OIDC
src/middleware/auth.ts:1—AUTH_MODE=oidc:Bearer JWT 结构校验(3 段、exp、iss与OIDC_ISSUER比对、aud与OIDC_AUDIENCE比对),声明附加到req.oidcClaims;生产环境替换为 JWKS 签名验证控制平面
src/routes/controlplane.ts:1— CRUD/admin/tenants(POST/GET/PATCH/DELETE+ 409 重复/400 无效 ID),POST /admin/tenants/:id/rotate-key,GET /admin/tenants/:id/store隔离检查;受管理员令牌保护运行时扩展
src/utils/cluster.ts:1—initCluster()派生CLUSTER_WORKERS(默认 CPU-1),工作进程退出时自动重启,CLUSTER_MODE=true;无状态 +RedisEventStore实现真正的水平扩展监控栈
docker-compose.override.yml:1— Prometheus(prometheus.yml抓取app:3000/metrics)位于 :9090 + Grafana 位于 :3001测试
tests/v3_0.test.ts:1(15 个测试:租户提取/隔离/必需-400,OIDC 令牌验证 + 签发者/受众 + HTTP 401/200,控制平面生命周期 201/409/400/404/轮换密钥/存储检查/禁用-404,集群无操作,compose 服务)— 共 178 个
🔌 生态与开发者体验(阶段 5 — v2.2)
插件 SDK
src/plugin/index.ts:1—definePlugin({name, version, register}),registerPlugin(server, plugin)(重复容忍),getRegisteredPlugins(),自动sendToolListChanged通知集成
src/integrations/—slackPlugin(列表/发布/搜索),notionPlugin(搜索/获取/创建),linearPlugin(列表/创建/获取)— 全部无需令牌即可模拟(SLACK_TOKEN,NOTION_TOKEN);在src/server.ts:1中自动注册注册表
smithery.yaml:1— Smithery 配置 + MCP 注册表名称io.github.ahmedalbanna/mcp-server-base,package.json:1中的mcpName/files字段混合 RAG
src/tools/rag.tool.ts:1—rag_search模式vector|bm25|hybrid(默认 hybrid,alpha 0.5),BM25(k1=1.5,b=0.75)归一化 + 余弦重排序;评估集tests/eval/rag-eval.json(20 个问答),p@5 ≥0.8 在tests/v2_2.test.ts:1中验证提示词游乐场
src/routes/admin.ts:1—POST /admin/prompts/:name/preview服务端渲染提示词;游乐场 UI 位于/admin仪表板测试
tests/v2_2.test.ts:1(16 个测试:插件 SDK 定义/注册/重复/工具可调用,注册表文件,混合模式,评估 p@5,游乐场预览/UI/计数)— 共 163 个
📈 规模与可运维性(阶段 5 — v2.0)
版本化 MCP
v2.0.0(package.json:1,config.MCP_SERVER_VERSION),每个次版本附带说明(src/server.ts:1)OTEL 追踪/指标(
src/utils/otel.ts:1)—createSpan/withSpan,incrementCounter/recordHistogram,getMetrics/getSpans,针对OTEL_EXPORTER_OTLP_ENDPOINT的 JSON 导出桩,OTEL_ENABLED标志RedisEventStore(
src/utils/redisEventStore.ts:1)— 实现EventStore的storeEvent/replayEventsAfter,内存回退,eventStoreFactory.create()用于水平扩展(EVENT_STORE_TYPE=memory|redis,REDIS_URL)管理 UI(
src/routes/admin.ts:1)—GET /admin(HTML 仪表板),/admin/tools|resources|prompts|metrics|spans|stores|health(JSON),通过ADMIN_TOKEN(X-Admin-Token)保护,ADMIN_ENABLED标志任务(
src/tools/tasks.tool.ts:1)— 实验性delay_task(如果 SDK 任务可用)+ 回退create_task/get_task/get_task_result(内存中,轮询),SimpleQueue/MemoryCache基础设施基准测试
k6/load.js:1—http_req_duration p(95)<100ms,stages10→50 虚拟用户,checks >99%,npm run bench/bench:localCompose
docker-compose.yml:1已包含 redis/postgres/qdrant 用于扩展测试:
tests/scale.test.ts:1(OTEL 跨度/指标,RedisEventStore 重放,缓存 TTL,队列,管理 HTML/指标/令牌/就绪,任务创建/轮询,版本,k6 脚本)— 共 130 个(加上 v2.1 后为 147 个)部署 已为 Fly.io/Cloud Run 就绪(无状态 + RedisEventStore),通过
release.yml发布 GHCR,npm2.0.0
🔒 加固与可观测性(阶段 5 — v2.1)— 新增
OTEL 真实实现
src/observability/otel-real.ts:1—initOtel()动态导入@opentelemetry/sdk-node+OTLPTraceExporter(控制台回退),OTEL_ENABLED+OTEL_EXPORTER_OTLP_ENDPOINT,SIGTERM 时优雅shutdownSLO
src/observability/slo.ts:1—checkSlo()(内存/RAG/缓存/正常运行时间,latencyMs),GET /health→{status, checks, uptime, version, otel, eventStore}+GET /ready→ 非ok时返回503,GET /metrics→ 通过prom-client输出 Prometheustext/plain格式(mcp_http_requests_total,mcp_http_request_duration_ms,mcp_sessions_active)RBAC
src/middleware/rbac.ts:1—reader < writer < admin(X-Role请求头,JWT 桩),TOOL_ROLES映射(31 个工具),mcpRbacMiddleware检查tools/call请求体 → 当reader尝试write_file/shell_execute时返回403,GET /admin→ 需要admin角色备份
src/utils/persistence.ts:1—saveBackup()/loadBackup()/scheduleSave()(500ms 防抖)写入ALLOWED_ROOT/.backup.json(动态getBackupFile()),设置REDIS_URL时记录 Redis 同步桩,启动时在src/index.ts:1调用loadBackup()指标
src/utils/metrics.ts:1—prom-clientRegistry+collectDefaultMetrics,httpRequestsTotal/httpRequestDuration/mcpToolCallsTotal/mcpSessionsActive,GET /metrics处理器测试
tests/v2_1.test.ts:1(13 个测试:SLO 检查,RBAChasRole/X-Role403/200,SLO health/metrics200 + Prometheus 文本,OTEL 跨度,通过memory_set进行备份保存/加载 +scheduleSave,initOtel禁用/启用)+tests/unit/rbac.test.ts:1(4 个测试)— 共 147 个日志器对 stderr 安全,绝不记录机密(脱敏)
Zod → 通过 SDK 生成 JSON Schema(
src/types.ts:1,src/tools/*.tool.ts)fetch 超时(10 秒)+ 结构化错误
优雅关闭(
SIGINT/SIGTERM)健康检查(
GET /health)与就绪检查(GET /ready)与 MCP 分离默认无状态(
sessionIdGenerator: undefined),当RESUMABILITY_ENABLED=true时有状态(src/index.ts:22)类型安全,严格 TS + ESLint flat + Prettier + husky + lint-staged
强制覆盖率 85% 行 / 70% 分支(
vitest.config.ts:1),178 个测试:单元 + e2e HTTP/安全/能力/集成/规模/v2.1/v2.2/v3.0
📚 文档
完整文档位于 docs/:
架构 — 图表、模块映射、请求生命周期
配置 — 每个环境变量 + 验证规则
API 参考 — 工具/资源/提示词/端点
安全 — 认证、RBAC、OIDC、租户、加固清单
插件 — 插件 SDK 指南 + 注册表分发
部署 — Docker、集群/多副本扩展、监控、k6
测试 — 测试套件映射、模式、CI
🤝 贡献
参见 CONTRIBUTING.md — nvm use,npm test,添加工具/资源/提示词,确保 lint/typecheck/test 通过。参见 CODE_OF_CONDUCT.md。
📚 MCP 文档
This server cannot be deployed
Maintenance
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
A Model Context Protocol server for Wix AI tools
Model Context Protocol server for the Apideck Unified API. Connect any MCP-compatible agent framework to 100+ accounting systems, HRIS platforms, file storage providers, and more through one integration. More information https://www.apideck.com/mcp-server
Persistent memory, hybrid search and a goal graph for AI agents, over stdio or remote HTTP.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceA robust server implementing the Model Context Protocol with SSE and STDIO transport, enabling real-time communication and extensible tooling for AI models.517 npm4MIT
- AlicenseBqualityCmaintenanceA production-packaged Model Context Protocol server for coding agents that routes large file, git, web, database, and other tasks through token-budgeted tools and workflows.62 npm1MIT
- AlicenseNot gradedqualityDmaintenanceA production-ready Model Context Protocol suite over Streamable HTTP providing a sandboxed file server with tools, resources, prompts, and both manual and AI-driven clients.MIT
- AlicenseBqualityCmaintenanceEnables running a Model Context Protocol server with a validated echo tool over stdio or Streamable HTTP, including strict schemas, tests, and hardened container deployment.11MIT