MCP Time Server

MCP Time Server

A Model Context Protocol server providing current time retrieval and timezone conversion using IANA timezones.

Category
访问服务器

README

MCP Server - Model Context Protocol

📖 Giới thiệu về MCP Server

Model Context Protocol (MCP) là một giao thức mở được phát triển bởi Anthropic để chuẩn hóa cách các AI models tương tác với các nguồn dữ liệu và công cụ bên ngoài. MCP Server là một thành phần quan trọng trong hệ sinh thái này, đóng vai trò là cầu nối giữa AI models và các dịch vụ, cơ sở dữ liệu, API khác nhau.

🔑 Khái niệm cốt lõi

  • MCP Server: Là một dịch vụ backend cung cấp các công cụ (tools), tài nguyên (resources) và prompts cho AI models
  • Giao thức chuẩn: Sử dụng JSON-RPC 2.0 để đảm bảo tương thích giữa các hệ thống
  • Kiến trúc Client-Server: AI applications (clients) giao tiếp với MCP servers thông qua WebSocket hoặc stdio

🌟 Sử dụng trong thực tế

1. Tích hợp Cơ sở dữ liệu

AI Model ↔ MCP Server ↔ Database (MySQL, PostgreSQL, MongoDB)
  • Cho phép AI truy vấn và phân tích dữ liệu trực tiếp
  • Tự động tạo reports và insights từ database

2. Kết nối API bên ngoài

AI Model ↔ MCP Server ↔ External APIs (Weather, Stock, Social Media)
  • Lấy dữ liệu real-time từ các dịch vụ web
  • Thực hiện các tác vụ automation

3. Quản lý File System

AI Model ↔ MCP Server ↔ Local/Cloud Storage
  • Đọc, ghi, và xử lý files
  • Backup và sync dữ liệu

🚀 Use Cases phổ biến

1. Business Intelligence & Analytics

  • Mô tả: Tự động phân tích dữ liệu kinh doanh
  • Ví dụ: Tạo báo cáo doanh thu hàng tháng từ database sales
# MCP Server cung cấp tool để query database
tools = [
    {
        "name": "query_sales_db",
        "description": "Query sales database",
        "parameters": {"query": "string"}
    }
]

2. Customer Support Automation

  • Mô tả: Hỗ trợ khách hàng thông qua AI chatbot
  • Ví dụ: Tra cứu thông tin đơn hàng, cập nhật trạng thái ticket
tools = [
    {
        "name": "get_order_status",
        "description": "Get customer order status",
        "parameters": {"order_id": "string"}
    }
]

3. Content Management

  • Mô tả: Quản lý và tạo nội dung tự động
  • Ví dụ: Tự động tạo blog posts, cập nhật CMS
tools = [
    {
        "name": "publish_content",
        "description": "Publish content to CMS",
        "parameters": {"title": "string", "content": "string"}
    }
]

4. DevOps & Monitoring

  • Mô tả: Giám sát hệ thống và tự động hóa deployment
  • Ví dụ: Kiểm tra server health, deploy applications
tools = [
    {
        "name": "check_server_health",
        "description": "Check server health status",
        "parameters": {"server_id": "string"}
    }
]

5. E-commerce Integration

  • Mô tả: Quản lý shop online thông qua AI
  • Ví dụ: Cập nhật inventory, xử lý orders, customer service

🛠️ Cách tạo MCP Server

Bước 1: Cài đặt môi trường

# Python
pip install mcp

# Node.js
npm install @modelcontextprotocol/sdk

# TypeScript
npm install @modelcontextprotocol/sdk typescript

Bước 2: Tạo MCP Server cơ bản (Python)

#!/usr/bin/env python3
import asyncio
import json
from mcp.server import Server
from mcp.server.models import InitializationOptions
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool

server = Server("my-mcp-server")

@server.list_tools()
async def handle_list_tools() -> list[Tool]:
    """Danh sách các tools có sẵn"""
    return [
        Tool(
            name="echo",
            description="Echo back the input",
            inputSchema={
                "type": "object",
                "properties": {
                    "message": {"type": "string"}
                },
                "required": ["message"]
            }
        )
    ]

@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[TextContent]:
    """Xử lý tool calls"""
    if name == "echo":
        message = arguments.get("message", "")
        return [TextContent(type="text", text=f"Echo: {message}")]
    else:
        raise ValueError(f"Unknown tool: {name}")

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="my-mcp-server",
                server_version="1.0.0",
                capabilities=server.get_capabilities()
            )
        )

if __name__ == "__main__":
    asyncio.run(main())

Bước 3: Tạo MCP Server với TypeScript

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

class MyMCPServer {
  private server: Server;

  constructor() {
    this.server = new Server(
      {
        name: 'my-mcp-server',
        version: '1.0.0',
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );

    this.setupHandlers();
  }

  private setupHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'calculator',
          description: 'Perform basic math operations',
          inputSchema: {
            type: 'object',
            properties: {
              operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'] },
              a: { type: 'number' },
              b: { type: 'number' },
            },
            required: ['operation', 'a', 'b'],
          },
        },
      ],
    }));

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;

      if (name === 'calculator') {
        const { operation, a, b } = args as any;
        let result: number;

        switch (operation) {
          case 'add':
            result = a + b;
            break;
          case 'subtract':
            result = a - b;
            break;
          case 'multiply':
            result = a * b;
            break;
          case 'divide':
            result = a / b;
            break;
          default:
            throw new Error(`Unknown operation: ${operation}`);
        }

        return {
          content: [{ type: 'text', text: `Result: ${result}` }],
        };
      }

      throw new Error(`Unknown tool: ${name}`);
    });
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
  }
}

const server = new MyMCPServer();
server.run().catch(console.error);

Bước 4: Cấu hình Client để sử dụng MCP Server

{
  "mcpServers": {
    "my-server": {
      "command": "python",
      "args": ["path/to/your/mcp_server.py"]
    }
  }
}

Bước 5: Test MCP Server

# Test với stdio
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | python mcp_server.py

📁 Projects trong Repository

🕐 MCP Time Server (Node.js)

Vị trí: mcp-time-node/

Một MCP Server được viết bằng Node.js cung cấp các chức năng liên quan đến thời gian:

✨ Tính năng

  • Get Current Time: Lấy thời gian hiện tại theo múi giờ được chỉ định
  • Convert Time: Chuyển đổi thời gian giữa các múi giờ khác nhau
  • IANA Timezone Support: Hỗ trợ đầy đủ các múi giờ theo chuẩn IANA

🚀 Cách sử dụng

# Chạy với Node.js trực tiếp
cd mcp-time-node
npm install
npm start

# Chạy demo
npm run demo

# Chạy với Docker
docker build -t mcp-time-server .
docker run -i --rm mcp-time-server

📋 Available Tools

  1. get_current_time

    • Lấy thời gian hiện tại
    • Parameter: timezone (IANA timezone name)
    • Ví dụ: Asia/Ho_Chi_Minh, America/New_York, Europe/London
  2. convert_time

    • Chuyển đổi thời gian giữa các múi giờ
    • Parameters:
      • time: Thời gian theo định dạng HH:MM
      • source_timezone: Múi giờ nguồn
      • target_timezone: Múi giờ đích

🐳 Docker Support

Project đã được containerized với Dockerfile optimized cho production:

  • Base image: node:18-alpine
  • Security: Non-root user
  • Size: Minimal footprint

⚙️ VS Code MCP Integration

Đã cấu hình sẵn trong .vscode/mcp.json với 2 options:

  • mcp-time-node: Chạy trực tiếp với Node.js
  • mcp-time-docker: Chạy với Docker container

💡 Ví dụ sử dụng

// Lấy thời gian hiện tại ở Việt Nam
{
  "name": "get_current_time",
  "arguments": {
    "timezone": "Asia/Ho_Chi_Minh"
  }
}

// Chuyển đổi 14:30 từ Việt Nam sang New York
{
  "name": "convert_time",
  "arguments": {
    "time": "14:30",
    "source_timezone": "Asia/Ho_Chi_Minh",
    "target_timezone": "America/New_York"
  }
}

🔮 Tương lai của MCP

1. Ecosystem mở rộng

  • Nhiều providers hơn: Database, Cloud services, IoT devices
  • Community-driven: Open source tools và extensions
  • Standardization: Trở thành chuẩn industry cho AI integrations

2. Performance improvements

  • Caching mechanisms: Tối ưu hóa response time
  • Parallel processing: Xử lý multiple requests đồng thời
  • Load balancing: Phân tải cho high-traffic applications

3. Security enhancements

  • Authentication & Authorization: OAuth2, JWT tokens
  • Data encryption: End-to-end encryption
  • Audit logging: Theo dõi và log mọi interactions

4. AI-native features

  • Context awareness: Hiểu context tốt hơn từ previous conversations
  • Learning capabilities: Tự học và cải thiện performance
  • Multi-modal support: Xử lý text, images, audio, video

5. Enterprise adoption

  • Enterprise-grade security: Compliance với GDPR, HIPAA
  • Scalability: Support hàng triệu concurrent connections
  • Monitoring & Analytics: Dashboard và metrics chi tiết

6. Integration trends

Current: AI ↔ MCP Server ↔ Single Service
Future:  AI ↔ MCP Server ↔ Multiple Services (Orchestration)
  • Service orchestration: Một MCP server quản lý multiple services
  • Workflow automation: Tự động hóa complex business processes
  • Real-time collaboration: Multiple AI agents làm việc cùng nhau

📈 Roadmap dự kiến

Timeline Milestone
2025 Q2 MCP v2.0 với improved performance
2025 Q3 Enterprise security features
2025 Q4 Multi-modal support
2026 Q1 Service orchestration platform
2026 Q2 AI agent collaboration framework

🎯 Kết luận

MCP Server đang trở thành backbone cho việc tích hợp AI vào các hệ thống thực tế. Với khả năng kết nối linh hoạt giữa AI models và external services, MCP mở ra vô số possibilities cho automation và intelligent applications.

Key takeaways:

  • ✅ Giao thức chuẩn hóa cho AI integrations
  • ✅ Dễ dàng implement và maintain
  • ✅ Ecosystem đang phát triển mạnh mẽ
  • ✅ Tương lai rất promising với enterprise adoption

Bắt đầu với MCP Server ngay hôm nay để tận dụng sức mạnh của AI trong ứng dụng của bạn!

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选