MCP-server-typescript
A production-ready Model Context Protocol server built with Node.js and TypeScript, providing tool-based execution with input validation and error handling.
README
MCP Server - Model Context Protocol Tool Server
A production-ready Model Context Protocol (MCP) server built with Node.js, TypeScript, and Express. This server provides a tool-based execution system with input validation, error handling, and a scalable architecture.
📋 Table of Contents
- What is MCP?
- Features
- Folder Structure
- Installation
- Usage
- API Endpoints
- Example Tools
- Adding New Tools
- Real-World Use Case
- Error Handling
🤔 What is MCP?
Model Context Protocol (MCP) is a pattern for enabling AI assistants and other clients to execute backend tools/functions through a standardized API. Think of it as a bridge between AI models and your backend services.
How It Works:
- Client (AI assistant, frontend app) sends a request to the MCP server
- MCP Server validates the input using schemas
- Tool executes the requested function
- Response is returned in a standardized format
[AI Assistant] → POST /mcp → [MCP Server] → [Tool Execution] → [Response]
✨ Features
- ✅ TypeScript - Full type safety
- ✅ Express - Fast and minimal web framework
- ✅ Zod Validation - Runtime input validation
- ✅ Error Handling - Comprehensive error management
- ✅ Logging - Winston logger with file and console output
- ✅ Security - Helmet for HTTP headers, CORS support
- ✅ Scalable Architecture - Easy to add new tools
- ✅ Production Ready - Proper error codes, health checks
📁 Folder Structure
mcp-server/
├── src/
│ ├── tools/ # Tool definitions
│ │ ├── sum.tool.ts # Sum tool implementation
│ │ ├── getUser.tool.ts # GetUser tool implementation
│ │ └── index.ts # Tool registry
│ ├── types/ # TypeScript type definitions
│ │ └── tool.types.ts # Core MCP types
│ ├── middleware/ # Express middleware
│ │ ├── errorHandler.ts # Global error handler
│ │ └── logger.ts # Winston logger configuration
│ ├── utils/ # Utility functions
│ │ └── validator.ts # Input validation helper
│ ├── server.ts # Express app configuration
│ └── index.ts # Server entry point
├── logs/ # Log files (auto-generated)
├── package.json
├── tsconfig.json
├── .env.example
└── README.md
🚀 Installation
1. Install Dependencies
npm install
2. Set Up Environment Variables
Create a .env file in the root directory:
PORT=3000
NODE_ENV=development
LOG_LEVEL=info
3. Build the Project
npm run build
4. Start the Server
Development mode (with auto-reload):
npm run dev
Production mode:
npm start
The server will start at http://localhost:3000
🎯 Usage
Quick Start Example
Request:
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"tool": "sum",
"input": {
"a": 10,
"b": 25
}
}'
Response:
{
"success": true,
"data": {
"result": 35,
"operation": "10 + 25 = 35"
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
🔌 API Endpoints
1. Health Check
GET /health
Response:
{
"status": "healthy",
"timestamp": "2026-04-24T10:30:00.000Z",
"uptime": 123.45
}
2. List Available Tools
GET /tools
Response:
{
"success": true,
"data": {
"count": 2,
"tools": [
{
"name": "sum",
"description": "Adds two numbers together and returns the result"
},
{
"name": "getUser",
"description": "Retrieves a user by their ID from the database"
}
]
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
3. Execute Tool (Main MCP Endpoint)
POST /mcp
Content-Type: application/json
Request Body:
{
"tool": "toolName",
"input": {
// Tool-specific input
}
}
Success Response:
{
"success": true,
"data": {
// Tool-specific output
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
Error Response:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Input validation failed",
"details": {
"errors": [
{
"path": "a",
"message": "Expected number, received string",
"code": "invalid_type"
}
]
}
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
🛠️ Example Tools
1. Sum Tool
Adds two numbers together.
Request:
{
"tool": "sum",
"input": {
"a": 15,
"b": 30
}
}
Response:
{
"success": true,
"data": {
"result": 45,
"operation": "15 + 30 = 45"
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
2. GetUser Tool
Retrieves user information by ID.
Request:
{
"tool": "getUser",
"input": {
"id": 1
}
}
Response:
{
"success": true,
"data": {
"id": 1,
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "admin",
"createdAt": "2024-01-15T10:30:00Z"
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
User Not Found:
{
"success": true,
"data": null,
"timestamp": "2026-04-24T10:30:00.000Z"
}
➕ Adding New Tools
Creating a new tool is simple! Follow these steps:
Step 1: Create Tool File
Create src/tools/myTool.tool.ts:
import { z } from "zod";
import { MCPTool } from "../types/tool.types";
// Define input schema
const myToolInputSchema = z.object({
name: z.string().min(1),
age: z.number().positive(),
});
type MyToolInput = z.infer<typeof myToolInputSchema>;
interface MyToolOutput {
message: string;
}
// Implement the tool
export const myTool: MCPTool<MyToolInput, MyToolOutput> = {
name: "myTool",
description: "Description of what my tool does",
inputSchema: myToolInputSchema,
execute: async (input: MyToolInput): Promise<MyToolOutput> => {
// Your tool logic here
return {
message: `Hello ${input.name}, you are ${input.age} years old!`,
};
},
};
Step 2: Register the Tool
Add to src/tools/index.ts:
import { myTool } from './myTool.tool';
constructor() {
this.registerTool(sumTool);
this.registerTool(getUserTool);
this.registerTool(myTool); // ← Add your tool here
}
Step 3: Test Your Tool
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"tool": "myTool",
"input": {
"name": "John",
"age": 25
}
}'
That's it! Your tool is now available in the MCP server.
🌍 Real-World Use Case
AI Assistant with Backend Integration
Scenario: You're building an AI customer support assistant that needs to access real backend systems.
User: "What's the status of order #12345?"
↓
AI Assistant: [Calls MCP server with "getOrderStatus" tool]
↓
MCP Server: [Validates input, queries database]
↓
AI Assistant: [Receives order data]
↓
Response: "Your order #12345 is currently being shipped and will arrive tomorrow."
Benefits:
- Separation of Concerns - AI logic separate from business logic
- Security - Validate and sanitize all AI requests
- Consistency - Standardized API for all AI interactions
- Auditability - Log all AI actions and tool executions
- Flexibility - Add new capabilities without modifying AI model
Example Tools for Production:
getOrderStatus- Check order informationsearchProducts- Find products in inventorycreateTicket- Create customer support ticketssendEmail- Send automated emailscheckAvailability- Check resource availabilityprocessRefund- Handle refund requests
⚠️ Error Handling
The MCP server uses standardized error codes:
| Error Code | HTTP Status | Description |
|---|---|---|
TOOL_NOT_FOUND |
404 | Requested tool doesn't exist |
VALIDATION_ERROR |
400 | Input validation failed |
EXECUTION_ERROR |
500 | Tool execution failed |
INTERNAL_ERROR |
500 | Unexpected server error |
Example Error Response:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Input validation failed",
"details": {
"errors": [
{
"path": "id",
"message": "Number must be greater than 0",
"code": "too_small"
}
]
}
},
"timestamp": "2026-04-24T10:30:00.000Z"
}
📊 Logging
Logs are stored in the logs/ directory:
combined.log- All logserror.log- Error logs only
Console output is colorized for better readability during development.
🔐 Security Features
- Helmet - Secures HTTP headers
- CORS - Configurable cross-origin requests
- Input Validation - Zod schema validation for all inputs
- Error Sanitization - Prevents sensitive data leakage
📝 License
MIT
🤝 Contributing
- Create a new tool following the patterns in
src/tools/ - Add comprehensive input validation
- Include tests for your tool
- Update this README with examples
📞 Support
For issues or questions, please open an issue on the repository.
Happy coding! 🚀
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。