vagnervjs/mcp-server-example
If you are the rightful owner of mcp-server-example and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
A scalable Model Context Protocol (MCP) server implementation built with Node.js and Express.js, using the official MCP JavaScript SDK.
calculate-bmi
Calculates Body Mass Index with health category classification.
fetch-weather
Retrieves weather information for a city (mock data).
list-files
Lists project files matching a pattern.
MCP Server Example
A scalable Model Context Protocol (MCP) server implementation built with Node.js and Express.js, using the official MCP JavaScript SDK.
๐๏ธ Project Structure
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
๐ Quick Start
Prerequisites
- Node.js 18+
- npm or yarn
Installation
npm install
Running the Server
# Start the server
npm start
# Development mode with auto-restart
npm run dev
# Test the server
npm test
Testing the Server
# 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
๐ง Available Tools (Examples)
1. BMI Calculator (calculate-bmi
)
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
}
}
2. Weather Fetcher (fetch-weather
)
Retrieves weather information for a city (mock data).
Parameters:
city
(string): Name of the city
Example:
{
"name": "fetch-weather",
"arguments": {
"city": "London"
}
}
3. File Lister (list-files
)
Lists project files matching a pattern.
Parameters:
pattern
(string): File pattern (e.g., ".js", ".md")
Example:
{
"name": "list-files",
"arguments": {
"pattern": "*.js"
}
}
๐ Available Resources (Examples)
Static Resources
config://app
- Application configurationinfo://server
- Server information
Dynamic Resources
users://{userId}/profile
- User profiles by IDgithub://repos/{owner}/{repo}
- GitHub repository info
๐ฏ Available Prompts (Examples)
1. Health Assessment (health-assessment
)
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"
}
}
2. Project Analysis (project-analysis
)
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')
3. Weather Planning (weather-planning
)
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')
4. Code Review (code-review
)
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')
5. Onboarding (onboarding
)
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
๐ก Using Prompts
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"
}
}
}'
๐งช Testing
The project includes comprehensive testing with Node.js built-in test runner:
Test Structure
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
Running 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
Test Coverage
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
Manual Testing
Browser-based Testing (Recommended)
# 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
Command-line Testing
# 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
๐ก API Endpoints
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
๐ Browser Testing
For the easiest testing experience, use the official MCP Inspector:
npx @modelcontextprotocol/inspector
Then connect to http://localhost:3000/mcp
in the web interface.
MCP Protocol Methods
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
โ๏ธ Configuration
Edit src/config/server-config.js
to customize:
- Server port and host
- Session management settings
- Logging configuration
- MCP protocol settings
Environment Variables
PORT
- Server port (default: 3000)HOST
- Server host (default: localhost)LOG_LEVEL
- Logging level (default: info)NODE_ENV
- Environment (development/production)
๐ง Adding New Tools
- 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];
๐๏ธ Adding New Resources
-
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
๐ Session Management
The server includes robust session management:
- Automatic session cleanup
- Session limits (configurable)
- Graceful session termination
- Memory leak prevention
๐ ๏ธ Development Features
- 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
๐ Scripts
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
๐ค Contributing
- 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
๐ MCP Protocol
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.
MCP SDK Integration
- 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.
๐ License
MIT License - see package.json for details.