A scalable Model Context Protocol (MCP) server implementation built with Node.js and Express.js, using the official MCP JavaScript SDK.
mcp-server-example/
βββ src/
β βββ config/
β β βββ server-config.js # Server configuration
β βββ server/
β β βββ http-server.js # Express.js HTTP server setup
β β βββ http-utils.js # HTTP utilities and error handling
β β βββ server.js # MCP server and session management
β βββ prompts/
β β βββ health-assessment.js # Health assessment prompt
β β βββ project-analysis.js # Project analysis prompt
β β βββ weather-planning.js # Weather planning prompt
β β βββ code-review.js # Code review prompt
β β βββ onboarding.js # Onboarding prompt
β β βββ index.js # Prompt exports and registration
β βββ resources/
β β βββ static-resources.js # Static resources (config, info)
β β βββ dynamic-resources.js # Dynamic resources with templates
β β βββ index.js # Resource exports and registration
β βββ tools/
β β βββ calculate-bmi.js # BMI calculator tool
β β βββ fetch-weather.js # Weather fetcher tool
β β βββ list-files.js # File listing tool
β β βββ index.js # Tool exports and registration
β βββ index.js # Main entry point
βββ tests/ # Test suite (JavaScript, run directly)
β βββ tools.test.js # Tool functionality tests
β βββ resources.test.js # Resource functionality tests
β βββ prompts.test.js # Prompt functionality tests
β βββ server.test.js # Server architecture tests
β βββ http-integration-test.js # HTTP integration tests
βββ examples/ # Testing examples and scripts
β βββ curl/ # cURL testing scripts
β β βββ common.sh # Shared utilities
β β βββ tools.sh # Tools testing
β β βββ resources.sh # Resources testing
β β βββ prompts.sh # Prompts testing
β β βββ all.sh # Complete test suite
β βββ README.md # Examples documentation
βββ package.json
βββ README.md
- Node.js 18+
- npm or yarn
npm install
# Start the server
npm start
# Development mode with auto-restart
npm run dev
# Test the server
npm test
# Easiest way: Use MCP Inspector (web interface)
npx @modelcontextprotocol/inspector
# Then connect to: http://localhost:3000/mcp
# Alternative: Command-line testing
npm run test:manual
Calculates Body Mass Index with health category classification.
Parameters:
weightKg
(number): Weight in kilogramsheightM
(number): Height in meters
Example:
{
"name": "calculate-bmi",
"arguments": {
"weightKg": 70,
"heightM": 1.75
}
}
Retrieves weather information for a city (mock data).
Parameters:
city
(string): Name of the city
Example:
{
"name": "fetch-weather",
"arguments": {
"city": "London"
}
}
Lists project files matching a pattern.
Parameters:
pattern
(string): File pattern (e.g., ".js", ".md")
Example:
{
"name": "list-files",
"arguments": {
"pattern": "*.js"
}
}
config://app
- Application configurationinfo://server
- Server information
users://{userId}/profile
- User profiles by IDgithub://repos/{owner}/{repo}
- GitHub repository info
Comprehensive health assessment with BMI calculation and activity recommendations.
Parameters:
weight
(string): Weight in kilogramsheight
(string): Height in meterscity
(string): City for weather-based activity recommendationsgoals
(string, optional): Health or fitness goals
Example:
{
"name": "health-assessment",
"arguments": {
"weight": "70",
"height": "1.75",
"city": "London",
"goals": "lose weight and improve fitness"
}
}
Comprehensive project analysis and codebase exploration guide.
Parameters:
focus
(enum): Analysis focus - 'overview', 'structure', 'config', or 'all'fileTypes
(string, optional): Specific file types to analyze (e.g., 'js,json,md')
Weather-based activity and travel planning assistant.
Parameters:
cities
(string): Comma-separated list of cities to checkactivity
(enum): Activity type - 'travel', 'outdoor', 'fitness', or 'general'duration
(string, optional): Planning duration (e.g., 'weekend', 'week')
Systematic code review and quality assessment guide.
Parameters:
scope
(enum): Review scope - 'full', 'changes', or 'specific'focus
(enum): Review focus - 'quality', 'security', 'performance', 'maintainability', or 'all'filePattern
(string, optional): Specific file pattern to review (e.g., '.js', '.json')
Comprehensive onboarding guide for new team members and users.
Parameters:
role
(enum): Role - 'developer', 'user', 'admin', or 'reviewer'experience
(enum): Experience level - 'beginner', 'intermediate', or 'expert'focus
(string, optional): Specific areas of interest or responsibility
The server provides 5 comprehensive prompts that generate contextual guidance for various use cases. Each prompt accepts parameters and returns detailed, actionable instructions tailored to your specific needs.
Available Prompts:
- health-assessment: BMI calculation with weather-based activity recommendations
- project-analysis: Codebase exploration and analysis guidance
- weather-planning: Multi-city weather planning for activities
- code-review: Systematic code review and quality assessment
- onboarding: Role-based onboarding for team members
Usage Example:
# Get health assessment prompt
curl -X POST http://localhost:3000/mcp \
-H "mcp-session-id: YOUR_SESSION_ID" \
-d '{
"method": "prompts/get",
"params": {
"name": "health-assessment",
"arguments": {
"weight": "70",
"height": "1.75",
"city": "London"
}
}
}'
The project includes comprehensive testing with Node.js built-in test runner:
tests/
βββ tools.test.js # Tool functionality tests (7 tests)
βββ resources.test.js # Resource functionality tests (3 tests)
βββ prompts.test.js # Prompt functionality tests (10 tests)
βββ server.test.js # Server architecture tests (6 tests)
βββ http-integration-test.js # HTTP endpoint integration tests
# Run all tests
npm test
# Run tests in watch mode (auto-rerun on file changes)
npm run test:watch
# Run HTTP integration tests specifically
npm run test:integration
# Manual testing with cURL
npm run test:manual
The comprehensive test suite covers:
- β Tool Functionality: BMI calculations, weather fetching, file listing
- β Resource Management: Static resources (config, info) and dynamic resources (user profiles, repositories)
- β Prompt System: Health assessment, project analysis, weather planning, code review, onboarding
- β Session Management: Creation, limits, cleanup, and error handling
- β Server Architecture: MCP server creation, HTTP server setup, configuration
- β Integration Components: Tool, resource, and prompt registration systems
- β Error Handling: Edge cases, invalid inputs, malformed requests
Test Results: 26 tests across 4 test suites with 100% pass rate
# Start the MCP server
npm start
# In another terminal, launch MCP Inspector
npx @modelcontextprotocol/inspector
# Then open your browser to the URL shown (usually http://localhost:5173)
# Connect to: http://localhost:3000/mcp
MCP Inspector interface showing tools, resources, and prompts with interactive testing capabilities
The MCP Inspector provides a user-friendly web interface to:
- β Interactive Testing: Click-based tool execution and resource access
- β Real-time Results: See responses formatted and highlighted
- β Schema Validation: Built-in parameter validation and help
- β Session Management: Automatic session handling
- β Protocol Debugging: View raw MCP protocol messages
# Health check
curl http://localhost:3000/health
# Individual functionality testing
./examples/curl/tools.sh # Test tools only
./examples/curl/resources.sh # Test resources only
./examples/curl/prompts.sh # Test prompts only
# Complete test suite
./examples/curl/all.sh # Test everything
POST /mcp
- Main MCP protocol endpoint (tools, resources, prompts)GET /mcp
- Server-to-client notifications (SSE)DELETE /mcp
- Session terminationGET /health
- Health check and server status
For the easiest testing experience, use the official MCP Inspector:
npx @modelcontextprotocol/inspector
Then connect to http://localhost:3000/mcp
in the web interface.
tools/list
- List available toolstools/call
- Execute a toolresources/list
- List available resourcesresources/read
- Read a resourceprompts/list
- List available promptsprompts/get
- Get a prompt with arguments
Edit src/config/server-config.js
to customize:
- Server port and host
- Session management settings
- Logging configuration
- MCP protocol settings
PORT
- Server port (default: 3000)HOST
- Server host (default: localhost)LOG_LEVEL
- Logging level (default: info)NODE_ENV
- Environment (development/production)
- Create a new file in
src/tools/
:
// src/tools/my-new-tool.js
import { z } from "zod";
export const myNewTool = {
name: "my-new-tool",
config: {
title: "My New Tool",
description: "Description of what the tool does",
inputSchema: {
param1: z.string().describe("Description of param1"),
param2: z.number().optional().describe("Optional param2")
}
},
handler: async ({ param1, param2 }) => {
// Arguments are passed directly via destructuring
// Tool logic here
return {
content: [{
type: "text",
text: "Tool output"
}]
};
}
};
- Export it in
src/tools/index.js
:
export { myNewTool } from './my-new-tool.js';
// Add to registerAllTools function
const tools = [calculateBmiTool, fetchWeatherTool, listFilesTool, myNewTool];
-
Add to
src/resources/static-resources.js
(for static resources) orsrc/resources/dynamic-resources.js
(for templated resources) -
Resources are automatically registered via
src/resources/index.js
The server includes robust session management:
- Automatic session cleanup
- Session limits (configurable)
- Graceful session termination
- Memory leak prevention
- JavaScript ES Modules: Modern JavaScript with ES module syntax
- Hot Reload: Use
npm run dev
for auto-restart on file changes - Error Handling: Comprehensive error handling with proper HTTP status codes
- Logging: Configurable request logging and server events
- Health Monitoring: Built-in health check endpoint
- Graceful Shutdown: Proper cleanup on server termination
- Direct Test Execution: Tests run directly from JavaScript source using Node.js built-in test runner
npm start
- Start the servernpm run dev
- Start with auto-restart (development)npm test
- Run all testsnpm run test:watch
- Run tests in watch mode (auto-rerun on changes)npm run test:integration
- Run HTTP integration testsnpm run test:manual
- Run manual cURL testsnpm run stop
- Stop the running server
- Add new tools in
src/tools/
- Add new resources in
src/resources/
- Update configuration in
src/config/
- Follow the existing JavaScript code structure and patterns
- Test your changes with the provided test scripts
This server implements the Model Context Protocol (MCP) version 2024-11-05 using the official JavaScript SDK. For more information about MCP, visit the official documentation.
- Uses official
@modelcontextprotocol/sdk
package - Proper tool handler signatures with context objects
- JSON schema validation for tool inputs
- Resource templates with completion support
- Session management with transport handling
Note: Examples and patterns in this implementation are adapted from the official MCP TypeScript SDK repository.
MIT License - see package.json for details.