Skip to main content
Glama
mcp-server-base

mcp-server-base

by ahmedalbanna

MCP Server Base v3.0 — 扩展与企业级 (2026)

CI Node 20+ MCP SDK 1.12.1 TypeScript 5.7 License MIT Coverage 88% Version 3.0.0 Smithery

使用最新技术栈的现代 Model Context Protocol 服务器:

  • MCP SDK 1.12+ — McpServer 高级 API + StreamableHTTPServerTransport(新)和 StdioServerTransport

  • TypeScript 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 位于 /admin

  • v3.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 build

CI

.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)

node dist/index.js

Streamable HTTP

远程 / Docker / 云

node dist/index.js --http

Streamable HTTP 是取代 SSE(已于 2025 年 3 月弃用)的新标准。


🧰 工具(40)

工具

描述

输入

echo

回显消息

message, uppercase?

calculator

加/减/乘/除

operation, a, b

get_time

当前时间

timezone?

fetch_url

获取 URL

url, maxLength?

list_files

列出 ALLOWED_ROOT 下的文件

path?, recursive?

read_file

读取文件(1MB 限制)

path

write_file

写入文件 + 触发资源变更

path, content

search_files

在文件中搜索文本

query, path?, maxResults?

memory_set

在内存中设置 KV

key, value

memory_get

获取 KV

key

memory_delete

删除 KV

key

memory_list

列出 KV

—

memory_clear

清除全部

—

database_query

通过 alasql 执行 SQL(users、notes)

sql

database_tables

列出表行数

—

shell_execute

Shell(白名单,默认禁用)

command, timeout?

collect_user_info

引导演示(联系方式/偏好)

infoType?

generate_with_sampling

采样演示(LLM)

prompt, maxTokens?

rag_ingest

摄取文本(分块、嵌入)

text, id?, metadata?, chunk?

rag_search

混合搜索(向量+BM25)

query, topK?, threshold?, mode?

rag_list

列出文档

—

rag_clear

清除向量存储

—

brave_search

Brave API(无密钥时模拟)

query, count?

tavily_search

Tavily API(无密钥时模拟)

query, maxResults?, includeAnswer?

web_fetch

缓存的网页获取

url, useCache?, maxLength?

github_search_repos

GitHub 搜索仓库

query, perPage?

github_get_repo

GitHub 获取仓库

repo

github_get_issue

GitHub 获取问题

repo, issueNumber

create_task

创建后台任务

duration?, payload?

get_task

获取任务状态

taskId

get_task_result

获取任务结果

taskId

slack_list_channels

Slack 频道(插件)

—

slack_post_message

Slack 发布(插件)

channel, text

slack_search

Slack 搜索(插件)

query, count?

notion_search

Notion 搜索(插件)

query, page_size?

notion_get_page

Notion 页面(插件)

page_id

notion_create_page

Notion 创建(插件)

title, content?

linear_list_issues

Linear 问题(插件)

team?, limit?

linear_create_issue

Linear 创建(插件)

title, description?, team?

linear_get_issue

Linear 问题(插件)

id

📦 资源(6)

  • config://server-info — 服务器元数据(JSON,现在包含 features)

  • greeting://{name} — 动态问候模板

  • file:///{+path} — 沙盒文件(ALLOWED_ROOT),列出 + 补全,file:///notes.txt

  • memory://{key} — 内存 KV,列出 + 补全

  • db://{table}/{id} — 演示数据库行(users/notes),列出 + 补全

  • docs://{id} — RAG 块(通过 rag_ingest 摄取),列出 + 补全

💬 提示(4)

  • code-review — 参数:language、code

  • explain-concept — 参数:concept、level

  • summarize — 参数: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 :6333

RAG 演示(摄取 → 搜索 → 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-Id randomUUID、回显头、子日志关联)(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% 覆盖率

🔗 集成(第四阶段)

  • 缓存 MemoryCache TTL(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/deleteTenant

  • SSO 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,stages 10→50 虚拟用户,checks >99%,npm run bench / bench:local

  • Compose 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,npm 2.0.0

🔒 加固与可观测性(阶段 5 — v2.1)— 新增

  • OTEL 真实实现 src/observability/otel-real.ts:1 — initOtel() 动态导入 @opentelemetry/sdk-node + OTLPTraceExporter(控制台回退),OTEL_ENABLED + OTEL_EXPORTER_OTLP_ENDPOINT,SIGTERM 时优雅 shutdown

  • SLO src/observability/slo.ts:1 — checkSlo()(内存/RAG/缓存/正常运行时间,latencyMs),GET /health → {status, checks, uptime, version, otel, eventStore} + GET /ready → 非 ok 时返回 503,GET /metrics → 通过 prom-client 输出 Prometheus text/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-client Registry + collectDefaultMetrics,httpRequestsTotal/httpRequestDuration/mcpToolCallsTotal/mcpSessionsActive,GET /metrics 处理器

  • 测试 tests/v2_1.test.ts:1(13 个测试:SLO 检查,RBAC hasRole/X-Role 403/200,SLO health/metrics 200 + 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 文档

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    C
    maintenance
    A 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.
    6
    2 npm
    1
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    A 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
  • A
    license
    B
    quality
    C
    maintenance
    Enables running a Model Context Protocol server with a validated echo tool over stdio or Streamable HTTP, including strict schemas, tests, and hardened container deployment.
    1
    1
    MIT