mcp-express-bolierplate
MCP Node.js Boilerplate
Boilerplate для создания MCP client и MCP server на Node.js + TypeScript. На стороне HTTP используется Express. Поддерживаются:
stdio— клиент запускает сервер как дочерний процесс, подходит для MCP host, работающих локальноStreamable HTTP — endpoint находится по адресу
/mcpи может быть опубликован через HTTPS с помощью Cloudflare Tunnelmock tools для CRUD users
статический resource
users://allи resource templateusers://{id}prompt
summarize-usersCLI client для discovery, вызова tools, чтения resources и запроса prompts
Исходные данные находятся в src/data/users.json и загружаются в память при запуске сервера. Изменения через CRUD не перезаписывают файл и сбрасываются при перезапуске процесса.
Requirements
Node.js 20 и выше
npm
cloudflaredтолько для случаев, когда нужен HTTPS tunnel
Related MCP server: MCP TypeScript Starter
Установка
npm installПроверка сборки и тестов:
npm run checkВажная структура
src/
├── client/
│ └── client.ts # MCP CLI client ใช้ได้ทั้ง stdio และ HTTP
├── data/
│ └── users.json # mock seed data
├── lib/
│ └── api-client.ts # shared Axios instance สำหรับ upstream APIs
├── services/
│ └── user-service.ts # business logic กลางสำหรับ MCP capabilities
└── server/
├── mcp.ts # ประกอบ server และ capability registrations
├── tools/
│ └── user-tools.ts
├── resources/
│ └── user-resources.ts
├── prompts/
│ └── user-prompts.ts
├── schemas/
│ └── user.ts # shared MCP output schema
├── repository.ts # in-memory CRUD repository
├── stdio.ts # stdio entry point
└── http.ts # Express + Streamable HTTP entry point
scripts/
└── build.mjs # compile TypeScript และ copy mock JSON ไป distFactory в mcp.ts используется совместно обоими транспортами, поэтому возможности сервера не отличаются. Tools, Resources и Prompts обращаются к общему UserService вместо прямой привязки к repository.
Вызов External API с помощью Axios
В проекте есть общий экземпляр Axios в src/lib/api-client.ts с base URL, timeout и опциональным Bearer token. Его можно импортировать и использовать в tool или service:
import { apiClient } from "../../lib/api-client.js";
const response = await apiClient.get("/users");
console.log(response.data);Настройка при запуске сервера:
API_BASE_URL=https://api.example.com \
API_TIMEOUT_MS=10000 \
API_TOKEN=your-token \
npm run server:httpПример использования в MCP tool:
server.registerTool(
"list-upstream-users",
{
description: "List users from the configured upstream API",
inputSchema: z.object({}),
},
async () => {
const { data } = await apiClient.get("/users");
return {
content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
structuredContent: { users: data },
};
},
);Если API_BASE_URL не задан, можно передавать абсолютный URL напрямую в Axios. Избегайте логирования API_TOKEN и храните токен в secret manager при production-развёртывании.
Запуск в режиме stdio
Обычно не нужно запускать stdio server отдельно, потому что клиент или MCP host запускают процесс сами.
Запуск demo client, который открывает сервер, выполняет discovery capabilities, вызывает tools, читает resources и запрашивает prompt:
npm run client:stdio -- demoЗапуск сервера напрямую для ожидания MCP host:
npm run server:stdioВажно: stdio использует stdout как канал для JSON-RPC, поэтому логи сервера должны записываться только через stderr, например console.error.
Пример конфигурации для MCP host, замените /absolute/path/to/mcp-boilerplate на реальный путь:
{
"mcpServers": {
"mock-users": {
"command": "node",
"args": [
"--import",
"tsx",
"/absolute/path/to/mcp-boilerplate/src/server/stdio.ts"
],
"cwd": "/absolute/path/to/mcp-boilerplate"
}
}
}Или соберите заранее и используйте JavaScript без зависимости от tsx во время выполнения:
npm run build
npm run start:stdioКонфигурация после сборки:
{
"mcpServers": {
"mock-users": {
"command": "node",
"args": [
"/absolute/path/to/mcp-boilerplate/dist/server/stdio.js"
],
"cwd": "/absolute/path/to/mcp-boilerplate"
}
}
}Запуск в режиме Express HTTP
Terminal 1 — запуск сервера:
npm run server:httpЗначения по умолчанию:
MCP endpoint:
http://127.0.0.1:3000/mcphealth check:
http://127.0.0.1:3000/health
Terminal 2 — запуск HTTP client:
npm run client:http -- demoПорт или host можно изменить с помощью environment variables:
HOST=127.0.0.1 PORT=4000 npm run server:http
MCP_URL=http://127.0.0.1:4000/mcp npm run client:http -- demoДля production build:
npm run build
npm run start:httpВключение HTTPS с помощью Cloudflare Tunnel
HTTPS в этом примере завершается на Cloudflare, а Express server продолжает слушать HTTP только локально.
Установка cloudflared на macOS:
brew install cloudflaredTerminal 1 — запуск MCP HTTP server:
npm run server:httpTerminal 2 — запуск Quick Tunnel:
cloudflared tunnel --url http://127.0.0.1:3000cloudflared покажет временный URL, например:
https://random-words.trycloudflare.comВнешний MCP endpoint будет таким:
https://random-words.trycloudflare.com/mcpTerminal 3 — тестирование через HTTPS tunnel:
MCP_URL=https://random-words.trycloudflare.com/mcp npm run client:http -- demoQuick Tunnel подходит только для разработки, и Cloudflare указывает, что SSE не поддерживается. Поэтому в этом boilerplate режим ответа установлен на auto: обычные команды CRUD/discovery отвечают JSON, но не следует использовать Quick Tunnel для тестирования функций, требующих стриминга, например долгосрочных подписок. Для production используйте named tunnel, собственный hostname, authentication и authorization.
При использовании custom hostname добавьте его в allowlist:
ALLOWED_HOSTS=mcp.example.com npm run server:httpНесколько hostname через запятую:
ALLOWED_HOSTS=mcp.example.com,mcp-staging.example.com npm run server:httplocalhost, 127.0.0.1, ::1 и *.trycloudflare.com уже разрешены для разработки.
Команды MCP client
Используется одинаковый формат для client:stdio и client:http — отличается только имя скрипта.
Просмотр tools:
npm run client:stdio -- list-tools
npm run client:http -- list-toolsПросмотр resources или prompts:
npm run client:stdio -- list-resources
npm run client:stdio -- list-promptsВызов CRUD tools:
npm run client:stdio -- call list-users '{}'
npm run client:stdio -- call get-user '{"id":"1"}'
npm run client:stdio -- call create-user '{"name":"Margaret Hamilton","email":"margaret@example.com","role":"developer"}'
npm run client:stdio -- call update-user '{"id":"1","role":"viewer"}'
npm run client:stdio -- call delete-user '{"id":"3"}'Чтение resources:
npm run client:stdio -- read users://all
npm run client:stdio -- read users://1Запрос prompt:
npm run client:stdio -- prompt summarize-users '{"tone":"detailed"}'Для другого HTTP URL задайте MCP_URL:
MCP_URL=https://mcp.example.com/mcp npm run client:http -- call list-users '{}'Примечание для stdio: каждая команда CLI запускает новый процесс сервера, поэтому данные всегда начинаются с исходных mock-данных. Если нужно, чтобы CRUD-операции были последовательными, используйте MCP host, который сохраняет одно соединение, или запустите HTTP server и обращайтесь через client:http.
Доступные tools, resources и prompt
Тип | Имя | Назначение |
Tool |
| Просмотр всех users |
Tool |
| Просмотр user по ID |
Tool |
| Создание user |
Tool |
| Изменение user |
Tool |
| Удаление user |
Resource |
| JSON-снимок всех users |
Resource template |
| JSON отдельного user с автодополнением ID |
Prompt |
| Создание текста для модели с резюме по users |
Environment variables
Переменная | По умолчанию | Использование |
|
| Адрес привязки Express server |
|
| Порт Express server |
|
| Endpoint HTTP client |
| пусто | Добавление custom Host/Origin, которые принимает сервер |
| не задан | Базовый URL upstream API, который вызывает Axios |
|
| Таймаут запроса Axios в миллисекундах |
| не задан | Bearer token, который Axios добавляет автоматически |
Примеры значений находятся в .env.example. Проект не загружает файл .env автоматически; экспортируйте переменные или указывайте их перед командой, как в примерах выше.
Security notes
В этом примере нет authentication и authorization — не открывайте публичный endpoint с реальными данными.
Проверка
HostиOriginразрешает только localhost, TryCloudflare и значения изALLOWED_HOSTS.Mock repository находится в памяти и намеренно не сохраняет данные.
Для production добавьте auth, rate limiting, audit logging, persistent database и конфигурацию TLS/trust-proxy, подходящую для реальной системы.
Все скрипты
npm run dev:stdio # stdio server พร้อม watch mode
npm run dev:http # Express HTTP server พร้อม watch mode
npm run server:stdio # stdio server จาก TypeScript
npm run server:http # Express HTTP server จาก TypeScript
npm run client:stdio -- demo
npm run client:http -- demo
npm run build
npm run start:stdio # รัน dist หลัง build
npm run start:http # รัน dist หลัง build
npm test
npm run checkThis server cannot be installed
Maintenance
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
- AlicenseNot gradedqualityDmaintenanceA simple MCP server that exposes a createUser tool to add users to a local JSON file via stdio transport.2471MIT
- AlicenseNot gradedqualityBmaintenanceA feature-complete MCP server template in TypeScript demonstrating tools, resources, prompts, and both stdio and HTTP transports.8MIT
- FlicenseNot gradedqualityDmaintenanceA sample MCP server that exposes tools, resources, and prompts for managing users and todos, supporting both stdio and Streamable HTTP transports.
- AlicenseNot gradedqualityDmaintenanceEnables creating MCP (Model Context Protocol) servers with zero boilerplate, full TypeScript support, and multiple transports (stdio and HTTP).101MIT
Related MCP Connectors
An MCP server that let you interact with Cycloid.io Internal Development Portal and Platform
A basic MCP server to operate on the Postman API.
A MCP server built for developers enabling Git based project management with project and personal…
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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/Pongsapat1035/mcp-express-bolierplate'
If you have feedback or need assistance with the MCP directory API, please join our Discord server