Skip to main content
Glama
ahmedalbanna

mcp-server-base

by ahmedalbanna

MCP Server Base v2.0 — 扩展与可运维性(2026)

CI Node 20+ MCP SDK 1.12.1 TypeScript 5.7 License MIT Coverage 91% Version 2.0.0

使用最新技术栈构建的现代 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(本地向量)Web(缓存)GitHub 集成

  • OTEL 追踪/指标(src/utils/otel.ts:1)、Tasks(实验性 + create_task)、k6 负载测试

  • tsx watch 模式、vitest(130 个测试,91% 覆盖率)、优雅停机、docker-compose(redis、postgres、qdrant)


🚀 快速开始

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.ymlpush/PRmain 时运行,采用 Node 20+22 版本矩阵:lint、format:check、typecheck、test:coverage、build、docker build。


Related MCP server: MCP Server

🔌 传输

传输

使用方式

命令

STDIO

本地客户端(Claude Desktop)

node dist/index.js

Streamable HTTP

远程 / Docker / 云

node dist/index.js --http

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


🧰 工具(31)

工具

描述

输入

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

清空所有 KV

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

向量搜索(余弦相似度)

query, topK?, threshold?

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 获取 issue

repo, issueNumber

create_task

创建后台任务

duration?, payload?

get_task

获取任务状态

taskId

get_task_result

获取任务结果

taskId

📦 资源(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(short/medium/long), style(bullets/paragraph/tldr)

  • research — 参数:topic, depth(overview/deep), audience(beginner/expert/executive)


⚙️ 客户端配置

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/resumability)
├── server.ts             # createMcpServer() factory
├── config.ts             # zod env (AUTH, CORS, rateLimit, RAG, cache, integrations)
├── types.ts              # Zod schemas
├── middleware/auth.ts    # AUTH_MODE none|apiKey|bearer
├── middleware/rateLimit.ts
├── middleware/requestId.ts
├── utils/logger.ts       # stderr, JSON/text, redaction, child(requestId)
├── utils/eventStore.ts   # InMemoryEventStore for Last-Event-ID
├── utils/cache.ts        # MemoryCache (TTL) + defaultCache
├── utils/queue.ts        # SimpleQueue
├── tools/                # 31 tools: echo, fs, memory, db, shell, rag, 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
├── resources/            # 6 resources: config, greeting, file, memory, db, docs
├── routes/admin.ts       # Admin UI + metrics + spans
└── prompts/              # 4 prompts: code-review, explain-concept, summarize, research

新增工具:创建 src/tools/my.tool.ts → 导出 registerMyTool(server) → 添加到 src/tools/index.ts


🔐 安全(阶段 2)

  • 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-KeyAuthorization: Bearer 时返回 401(健康检查/就绪和 OPTIONS 请求除外)

  • 限流express-rate-limit(默认 100 次/15 分钟)应用于 /mcp — 返回 429 Too Many Requestssrc/middleware/rateLimit.ts:1

  • 请求 IDX-Request-Id 使用 randomUUID,回显请求头,子 logger 关联)(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

  • 可恢复性InMemoryEventStoresrc/utils/eventStore.ts:1)+ 当 RESUMABILITY_ENABLED=true 时的有状态会话映射(通过 Last-Event-ID 重放、GET /mcp 流、DELETE 关闭)

  • Docker 加固: 非 root appuser + HEALTHCHECKDockerfile:1

  • 测试: tests/unit/auth.test.tstests/unit/logger.test.tstests/unit/eventStore.test.tstests/e2e/security.test.ts(helmet/认证/限流/可恢复性)— 67 tests → 130 total with Phase 5, 90.89% coverage

🔗 集成(阶段 4)

  • 缓存MemoryCache TTL(src/utils/cache.ts:1)— defaultCache 用于 web/github,SimpleQueuesrc/utils/queue.ts:1

  • RAG: 本地向量(哈希嵌入 128 维、余弦、分块 500/50),位于 src/tools/rag.tool.ts:1rag_ingest(分块 + sendResourceListChanged)、rag_search(topK、threshold)、rag_listrag_clear + docs://{id} 资源

  • Websrc/tools/web.tool.ts:1brave_search(无 BRAVE_API_KEY 时模拟)、tavily_search(模拟)、web_fetch(通过 defaultCacheCACHE_TTL_MS 缓存)

  • GitHubsrc/tools/github.tool.ts:1github_search_repos, github_get_repo, github_get_issue(缓存,并使用 GITHUB_TOKEN 提高 API 速率限制)

  • 技术栈docker-compose.yml:1(app + redis:7 + postgres:16 + qdrant:v1.12.4),带健康检查

  • 演示rag_ingest → rag_search → docs:// 端到端验证见 tests/integrations.test.ts:1(21 个测试)

📈 扩展与可运维性(阶段 5 — v2.0)

  • 版本化 MCPv2.0.0package.json:1config.MCP_SERVER_VERSION),包含每个次要版本的说明(src/server.ts:1

  • OTEL 追踪/指标(src/utils/otel.ts:1)— createSpan/withSpanincrementCounter/recordHistogramgetMetrics/getSpans,为 OTEL_EXPORTER_OTLP_ENDPOINT 提供 JSON 导出 stub,OTEL_ENABLED 标志

  • RedisEventStoresrc/utils/redisEventStore.ts:1)— 实现了 storeEvent/replayEventsAfterEventStore 实现,内存回退,支持通过 eventStoreFactory.create() 进行水平扩展(EVENT_STORE_TYPE=memory|redisREDIS_URL

  • Admin UIsrc/routes/admin.ts:1)— GET /admin(HTML 仪表盘)、/admin/tools|resources|prompts|metrics|spans|stores|health(JSON),通过 ADMIN_TOKENX-Admin-Token)保护,ADMIN_ENABLED 标志

  • Taskssrc/tools/tasks.tool.ts:1)— 实验性 delay_task(如果 SDK 支持任务)+ 回退实现 create_task/get_task/get_task_result(内存、轮询),使用 SimpleQueue/MemoryCache 基础设施

  • 基准测试k6/load.js:1http_req_duration p(95)<100msstages 10→50 VUs、checks >99%npm run bench / bench:local

  • Composedocker-compose.yml:1 已包含 redis/postgres/qdrant,便于扩展

  • 测试: tests/scale.test.ts:1(OTEL spans/指标、RedisEventStore 重放、缓存 TTL、队列、Admin HTML/指标/令牌/就绪、任务创建/轮询、版本、k6 脚本)— 共 130 个测试

  • 部署: 已为 Fly.io/Cloud Run 就绪(无状态 + RedisEventStore),通过 release.yml 发布到 GHCR,npm 2.0.0

  • Logger 安全写入 stderr,绝不记录机密信息(脱敏)

  • 通过 SDK 将 Zod 转换为 JSON Schema(src/types.ts:1src/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),130 个测试:单元测试 + 端到端 HTTP/安全/能力/集成/扩展

🤝 贡献

参见 CONTRIBUTING.md — 运行 nvm use, npm test,添加工具/资源/提示词,确保 lint/typecheck/test 通过。另见 CODE_OF_CONDUCT.md


📚 MCP 文档

A
license - permissive license
Not graded
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

View all related MCP servers

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

  • Personal assistant MCP server with search, execute, packages, jobs, secrets, and integrations.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ahmedalbanna/mcp-server-base'

If you have feedback or need assistance with the MCP directory API, please join our Discord server