Skip to content

vagnervjs/mcp-server-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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 kilograms
  • heightM (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 configuration
  • info://server - Server information

Dynamic Resources

  • users://{userId}/profile - User profiles by ID
  • github://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 kilograms
  • height (string): Height in meters
  • city (string): City for weather-based activity recommendations
  • goals (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 check
  • activity (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 Screenshot 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 termination
  • GET /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 tools
  • tools/call - Execute a tool
  • resources/list - List available resources
  • resources/read - Read a resource
  • prompts/list - List available prompts
  • prompts/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

  1. 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"
      }]
    };
  }
};
  1. 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

  1. Add to src/resources/static-resources.js (for static resources) or src/resources/dynamic-resources.js (for templated resources)

  2. 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 server
  • npm run dev - Start with auto-restart (development)
  • npm test - Run all tests
  • npm run test:watch - Run tests in watch mode (auto-rerun on changes)
  • npm run test:integration - Run HTTP integration tests
  • npm run test:manual - Run manual cURL tests
  • npm run stop - Stop the running server

🀝 Contributing

  1. Add new tools in src/tools/
  2. Add new resources in src/resources/
  3. Update configuration in src/config/
  4. Follow the existing JavaScript code structure and patterns
  5. 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.

About

A scalable MCP (Model Context Protocol) server with modular tools, prompts, and resources

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published