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+ — высокоуровневый API McpServer + StreamableHTTPServerTransport (новый) и StdioServerTransport

  • TypeScript 5.7 ESM + модуль NodeNext

  • Zod валидация → автоматическая JSON Schema + валидация окружения (src/config.ts:1)

  • Express 4 + helmet + CORS allowlist + rate-limit + health/ready + Admin UI

  • Два транспорта: STDIO (Claude Desktop) и Streamable HTTP (удалённый, спецификация 2025-03, stateless + stateful resumability через RedisEventStore)

  • Структурированные модули tool/resource/prompt + интеграции RAG (локальные векторы), Web (кэш), GitHub

  • OTEL трассировка/метрики (src/utils/otel.ts:1), Tasks (экспериментальные + create_task), k6 нагрузочные тесты

  • tsx watch, vitest (130 тестов, 91% покрытие), graceful shutdown, 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

Dev

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: MCP Server

🔌 Транспорты

Транспорт

Использование

Команда

STDIO

Локальные клиенты (Claude Desktop)

node dist/index.js

Streamable HTTP

Удалённый / Docker / Облако

node dist/index.js --http

Streamable HTTP — новый стандарт, заменяющий SSE (устарел в марте 2025).


H 30 (G ион (31)

Tool

Description

Input

echo

Эхо-сообщение

message, uppercase?

calculator

add/sub/mul/div

operation, a, b

get_time

Текущее время

timezone?

fetch_url

Получить URL

url, maxLength?

list_files

Список файлов в ALLOWED\_ROOT

path?, recursive?

read_file

Прочитать файл (лимит 1МБ)

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

SQL через alasql (users, notes)

sql

database_tables

Список таблиц с количеством строк

shell_execute

Shell (allowlist, отключено по умолulation)

command, timeout?

collect_user_info

Демо сборе данных (контакт/предпочтит)

infoType?

generate_with_sampling

Демо сэмпleирования (LLM)

prompt, maxTokens?

rag_ingest

Загружка текста (чанкen, эмbeддинг)

text, id?, metadata?, chunk?

rag_segarch

Векторный поиск (кosine)

query, topK?, threshold?

rag_list

Список докуменчов

rag_clear

Очистить векторное хранлище

brave_search

Brave API (мок ели нет ключа)

query, count?

Tavily_search

Tavily API (мок при отсутствии ключа)

query, maxResultвов?, includeAnswer?

web_fetch

Кэширование получения веб-стрл url,useCache?, maxLength?`

gihub_search_repos

Поیک стributed

query, perPage?

gihub_get_repо

Получить репоиторий GitHub

repо

gihub_get_issue

Получить issue GitHub

repо, issueNumber

create_task

Create background task

duation?, payлоад?

get_task

Get task status

taskId

get_task_result

Get task result

taskId

📦 Ресурсы ())

config://server-info — метаданные сервера (JSON, now includes features) greeting://{name} — dynamic greeting template file:///{+path} — sandboxed file (ALLOWED_ROOT), list + complete, file:///notes.txt ?

  • db://{table}/{id} — demo DB row (users/notes), list + complete

  • docs://{id} — R A G chunk (ingested via rag_ingest), list + complete

💬 Промпты (4)

  • code-review — args: language, code

  • explain-concept — args: concept, level

  • summarизация — args: ext, length (short/medium/long), style (pullt? No, "bullets" options), style (bullets/paragraph/tldr)

  • research — args: topic, depth (overview/deep), audience (expert/executive)

***```

client Config

Claude Desktop (claude_desktop_config.json)

{
  "mcpServers": {
    "mcp-server-base": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server/dist/index.js"]
    }
  }
}

HTTP Client

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 демо (Ingest → поиск → DOC)**

# 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 allowlist (CORS_ORIGIN=* или список через запятую) с обработкой кредenţиал через cors (srs config.ts:1) (иаббл)

  • Auth AUTH_MODE=none|apiKey|beeat в src/middleware/auth.ts:1401 без валидного X- API-Key или Authorization; Bearer (health/ready и OPTIONS исключены)

  • Rate limit express-rate-limit (default 100/15мин) на /mcp429 Too Many Requests (src/middleware/rateLimit.ts:1)

  • RequestId (X-Request-Id randomUUID, echo header, child logger correlation) (src/index.ts:1)

  • Zod environSMDparseEnv() проверяет PORT, AUTH_MODE, API_KEY кросс-полем и быстро падает при ошибке

  • Структурированный логгер JSON/текст, [REDACTED] для authorization, apiKey, token (src/utils/logger.ts:24)

  • Resumability InMemoryEventStore (src/utils/eventStore.ts:1) + stateful сессий при RESUMABILITY_ENABLED=true (воспроизведение через Last-Event-ID, GET /mcp stream, DELETE close)

  • Docker hardening non-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 тестов → 130 всего с Phase 5, 90.89% покрытие

🔗 Интеграции (Phase 4)

  • Кэш MemoryCache TTL (src/utils/cache.ts:1) — defaultCache для web/github, SimpleQueue (src/utils/queue.ts:1)

  • RAG локальный вектор (hash embedding 128-dim, cosine, chunk 500/50) в src/tools/rag.tool.ts:1 — rag_ingest(с чанками +sendResourceListChanged), rag_search(topK, threshold),rag_list, rag_clear+ ресурсdocs://{id}`

  • Web src/tools/web.tool.ts:1brave_search (mock при отсутствие BRAVE_API_KEY), tavily_search (mock), web_fetch (кэширование через defaultCache, CACHE_TTL_MS)

  • GitHub src/tools/github.tool.ts:1github_search_repos, github_get_repo, github_get_issue (cached, GITHUB_TOKEN для rate limit)

  • Стек docker-compose.yml:1 (app + redis:7 + postgres:16 + qdrant:1.4)` с healthcheck

  • Демо rag_ingest → rag_search → docs:// E2E в тестах tests/integrations.test.ts:1 (21 тест)

📈 Scale и возможности (Phase 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/removeHistogram, getMetrics/getSpans, JSON Export stug для OTEL_EXPORTER_OTEL_ENDPOINT, OTEL_ENABLED

  • RedisEventStore (src/utils/redisEventStore.ts:1) — EventStore impl with storeEvent/replayEventsAfter, in-memory fallback, eventStoreFactory.create() for horizontal scaling (EVENT_STORE_TYPE=memory|redis, REDIS_URL)

  • Admin UI (src/routes/admin.ts:1) — GET /admin (HTML dashboard), /admin/tools|resources|prompts|metrics|spans|stores|health (JSON), protected via ADMIN_TOKEN (X-Admin-Token), ADMIN_ENABLED

  • Tasks (src/tools/tasks.tool.ts:1) — experimental delay_task (if sdk tasks available) + fallback create_task/get_task/get_task_result (in-memory, oolling), SimpleQueue/MemoryCache infrastructure

  • Bench k6/load.js:1http_req_duration p(95) < 100ms, load changes 10→50 VUs, checks >99%, npm run bench (or bench:local)

  • Compose docker-compose.yml:1 contains redis/postgres/qdrant for scale

  • QA tests: tests/scale.test.ts:1, 130 total

  • Deploy ready for Fly.io/Cloud Run (stateless + RedisEventStore), GHCR via release.yml, npm 2.0.0

  • Логгер для STDERR, никогда не логирует секреты (редактирование)

  • Zod → JSON Schema via SDK (src/types.ts:1, src/tools/*.tool.ts)

  • Тfusion timeout (fetch) 10s + structured errors *Graceful shutdown (SIGINT/SIGTERM)

  • Health (GET /health) and ready (GET /ready) separate from MCP

  • Stateless peek by default (sessionIdGenerator: undefined), stateful when RESUMABILITY_ENABLED=true (src/index.ts:22)

  • Type-safe, strict TS + ESLint flat + Prettier + husky + lint-staged

  • Coverage 85% lines / 90% branches enforced in vitest.config.ts:1, 130 tests:` unit + e2e HTTP/security/capabilities/integrations/scale

🤝 Вклад

См. CONRIBUTING.mdnvm use, npm test, добавить tool/resource/prompt, ensure lint/typecheck/test tests.См.CODE_OF_CONDUCT.md`.


📚 MCP Docs

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