高精度时间服务

一个基于NTP共识和IANA tzdata的高精度时间服务,提供准确的时间信息和时区转换功能,适用于需要可信时间源、时区转换或分布式系统的应用场景。

  • by IBM
  • Python
  • 本地部署
  • 3 星标
  • 更新于
在 GitHub 查看 chrishayuk/chuk-mcp-time

使用说明

chuk mcp时间

使用NTP共识和IANA tzdata的高精度时间+时区MCP服务器

一种模型上下文协议(MCP)服务器,通过查询多个NTP服务器、删除异常值和计算独立于系统时钟的共识时间来提供极其准确的时间信息。现在包括使用IANA-tzdata进行精确时区转换、夏令时处理和时区发现的全面时区支持。非常适合需要可信时间源、时区转换、检测时钟漂移或在分布式系统中工作的应用程序。

这是一个为学习和测试目的而提供的演示项目。

特性

🎯 多源共识:同时查询4-7个NTP服务器,并使用中值和异常值拒绝计算共识时间

⚡ 异步优先:基于asyncio构建,可实现并发NTP查询的最大性能

⏱️ 延迟补偿:自动调整查询持续时间的时间戳,因此返回的时间表示“现在”

🔒 类型安全:100%Pydantic模型,具有完整的类型提示和使用枚举进行验证

🌍 IANA时区支持:通过夏令时、转换和发现完成时区处理

🔍 时钟漂移检测:将系统时钟与受信任的NTP源进行比较

⏰ 时区转换:通过精确的夏令时处理在任何IANA时区之间进行转换

🗺️ 时区发现:列出并搜索600多个IANA时区以防止幻觉

📊 透明:返回所有源数据、共识方法、错误估计和查询持续时间

⚙️ 可配置的:NTP服务器和共识参数的基于环境的配置

🚀 部署示例:Docker支持、GitHub Actions CI/CD、Fly.io部署

🌐 公共端点:立即尝试 https://time.chukai.io/mcp -无需安装!

快速开始

🌐 使用公共HTTP终结点(无需安装)

立即使用我们的托管MCP服务器进行尝试:

端点: https://time.chukai.io/mcp

在Claude Desktop或任何MCP客户端中配置以连接到HTTP流式传输端点。无需安装!

📦 安装选项

使用uvx(建议当地使用)

# Run directly with uvx (auto-installs and runs)
uvx chuk-mcp-time

# For STDIO mode (Claude Desktop, mcp-cli)
uvx chuk-mcp-time

# For HTTP mode
uvx chuk-mcp-time http

使用pip

pip install chuk-mcp-time

来源

# Clone the repository
git clone <repository-url>
cd chuk-mcp-time
make dev-install

演示

通过全面的演示查看服务器的运行情况:

# Run the demo script
uv run examples/demo.py

# Or with Python
python examples/demo.py

演示显示:

  • ✅ 查询4个NTP服务器并达成共识
  • ✅ 系统时钟漂移检测(检测精度±毫秒)
  • ✅ 时区转换(来自单一共识的6个时区)
  • ✅ 5个样品的稳定性

输出示例:

📊 Results:
Consensus Time (UTC).................... 2025-11-28T10:04:59.916227+00:00
Sources Used............................ 4/4
Estimated Error......................... ±10.0 ms
Query Time.............................. 42.8 ms

🕐 Clock Comparison:
Delta................................... +2.4 ms
Status.................................. ✅ OK - System clock is accurate

看 示例/README.md 查看详细的演示文档。

与MCP客户端一起使用

选项1:公共HTTP端点(最简单)

连接到我们的托管服务器 https://time.chukai.io/mcp

Claude桌面配置:

添加到您的 claude_desktop_config.json:

{
  "mcpServers": {
    "time": {
      "url": "https://time.chukai.io/mcp"
    }
  }
}

✅ 无需安装 ✅ 始终保持最新 ✅ 高可用性

选项2:本地STDIO(最常见)

使用uvx在本地运行STDIO传输(适用于Claude Desktop、mcp-cli等):

Claude桌面配置:

{
  "mcpServers": {
    "time": {
      "command": "uvx",
      "args": ["chuk-mcp-time"]
    }
  }
}

或手动运行:

# Run with uvx
uvx chuk-mcp-time

# Or with Python
python -m chuk_mcp_time.server

选项3:本地HTTP服务器

运行自己的HTTP服务器进行测试/开发:

# Start HTTP server
uvx chuk-mcp-time http

# Or with Python
python -m chuk_mcp_time.server http

# Server runs on http://localhost:8000

Claude桌面配置:

{
  "mcpServers": {
    "time": {
      "url": "http://localhost:8000/mcp"
    }
  }
}

可用工具

1. get_time_utc

使用NTP共识以高精度获取当前UTC时间。

参数:

  • mode (可选): "fast" (默认情况下,4台服务器)或 "accurate" (7台服务器)
  • compensate_latency (可选): true (默认)调整查询持续时间的时间戳

退货:

{
  "iso8601_time": "2025-11-28T01:23:45.123456+00:00",
  "epoch_ms": 1732756425123,
  "sources_used": 4,
  "total_sources": 4,
  "consensus_method": "median_with_outlier_rejection",
  "estimated_error_ms": 12.5,
  "source_samples": [...],
  "warnings": ["Applied +150.2ms latency compensation to timestamp"],
  "system_time": "2025-11-28T01:23:49.456789+00:00",
  "system_delta_ms": 4333.333,
  "query_duration_ms": 150.2,
  "latency_compensated": true
}

延迟补偿: 默认情况下,时间戳会根据查询NTP服务器所花费的时间进行调整。这意味着返回的时间戳表示“现在”(发送响应时),而不是NTP查询开始时。这对于慢速网络或精确模式尤为重要。

2. get_time_for_timezone

以高精度获取特定时区的当前时间。

参数:

  • timezone_name:IANA时区名称(例如。, "America/New_York", "Europe/London")
  • mode (可选): "fast" 或 "accurate"
  • compensate_latency (可选): true (默认)调整查询持续时间的时间戳

退货: 同 get_time_utc 加上:

{
  "timezone": "America/New_York",
  "local_time": "2025-11-27T20:23:45.123456-05:00"
}

3. get_local_time

以高精度获取特定IANA时区的当前时间。

使用NTP共识获得准确的UTC时间,然后使用IANA-tzdata转换为请求的时区。提供独立于系统时钟的权威本地时间。

参数:

  • timezone:IANA时区标识符(例如。, "America/New_York", "Europe/London", "Asia/Tokyo")
  • mode (可选): "fast" 或 "accurate"
  • compensate_latency (可选): true (默认)调整查询持续时间的时间戳

退货:

{
  "local_datetime": "2025-11-27T20:23:45.123456-05:00",
  "timezone": "America/New_York",
  "utc_offset_seconds": -18000,
  "is_dst": false,
  "abbreviation": "EST",
  "source_utc": "2025-11-28T01:23:45.123456+00:00",
  "tzdata_version": "2024b",
  "estimated_error_ms": 12.5
}

4. convert_time

使用IANA规则将日期时间从一个时区转换为另一个时区。

独立于系统时钟执行时区转换。使用IANA-tzdata处理所有夏令时转换、历史变化和政治边界。

参数:

  • datetime_str:ISO 8601日期时间字符串(朴素,将在from_timezone中解释)
  • from_timezone:源IANA时区标识符
  • to_timezone:目标IANA时区标识符

退货:

{
  "from_timezone": "America/New_York",
  "from_datetime": "2025-06-15T14:30:00-04:00",
  "from_utc_offset_seconds": -14400,
  "to_timezone": "Europe/London",
  "to_datetime": "2025-06-15T19:30:00+01:00",
  "to_utc_offset_seconds": 3600,
  "offset_difference_seconds": 18000,
  "explanation": "Europe/London is 5.0 hours ahead of America/New_York (UTC-4.0 → UTC+1.0)"
}

5. list_timezones

列出可用的IANA时区,并可选择过滤。

返回所有有效的IANA时区标识符。帮助发现正确的时区名称,并防止产生无效时区的幻觉。

参数:

  • country_code (可选):ISO 3166国家代码过滤器(例如。, "US", "GB", "FR")
  • search (可选):子字符串搜索过滤器(不区分大小写)

退货:

{
  "timezones": [
    {
      "id": "America/New_York",
      "country_code": "US",
      "comment": null,
      "example_city": "New York"
    },
    {
      "id": "Europe/London",
      "country_code": "GB",
      "comment": null,
      "example_city": "London"
    }
  ],
  "total_count": 2,
  "tzdata_version": "2024b"
}

示例搜索:

  • search: "New" → 返回名称中包含“New”的所有时区
  • search: "Tokyo" → 返回亚洲/东京
  • 没有过滤器→ 返回所有600+个IANA时区

6. get_timezone_info

获取时区的详细信息,包括即将到来的转换。

提供全面的时区元数据,包括当前偏移、夏令时状态和即将到来的转换(例如夏令时更改)。有助于规划和理解时区行为。

参数:

  • timezone:IANA时区标识符
  • mode (可选): "fast" 或 "accurate" (影响当前时间的准确性)

退货:

{
  "timezone": "America/New_York",
  "country_code": null,
  "comment": null,
  "current_offset_seconds": -18000,
  "current_is_dst": false,
  "current_abbreviation": "EST",
  "transitions": [
    {
      "from_datetime": "2026-03-08T07:00:00+00:00",
      "utc_offset_seconds": -14400,
      "is_dst": true,
      "abbreviation": "EDT"
    },
    {
      "from_datetime": "2026-11-01T06:00:00+00:00",
      "utc_offset_seconds": -18000,
      "is_dst": false,
      "abbreviation": "EST"
    }
  ],
  "tzdata_version": "2024b"
}

7. compare_system_clock

将系统时钟与受信任的NTP源进行比较,以检测漂移。

参数:

  • mode (可选): "fast" 或 "accurate"

退货:

{
  "system_time": "2025-11-28T01:23:49.456789+00:00",
  "trusted_time": "2025-11-28T01:23:45.123456+00:00",
  "delta_ms": 4333.333,
  "estimated_error_ms": 12.5,
  "status": "error"
}

状态值:

  • "ok":Δ<100ms
  • "drift":增量100-1000ms
  • "error":增量>1000ms

配置

配置可以通过环境变量或 .env 文件:

# NTP Servers (comma-separated)
TIME_SERVER_NTP_SERVERS=time.cloudflare.com,time.google.com,time.apple.com

# NTP timeout in seconds (0.5 to 10.0)
TIME_SERVER_NTP_TIMEOUT=2.0

# Maximum outlier deviation in milliseconds (100.0 to 60000.0)
TIME_SERVER_MAX_OUTLIER_DEVIATION_MS=5000.0

# Minimum number of sources required (1 to 10)
TIME_SERVER_MIN_SOURCES=3

# Maximum disagreement before warning in milliseconds (10.0 to 5000.0)
TIME_SERVER_MAX_DISAGREEMENT_MS=250.0

# Number of servers to query in fast mode (2 to 10)
TIME_SERVER_FAST_MODE_SERVER_COUNT=4

看 .env.示例 获取完整的配置模板。

运作原理

一致性算法

  1. 查询多个来源:根据模式同时查询4-7个NTP服务器
  2. RTT调整:通过添加往返时间的一半来调整时间戳
  3. 离群值去除:从中位数中迭代删除大于5秒的异常值
  4. 中位共识:计算剩余时间戳的中位数
  5. 误差估计:计算IQR(四分位数间距)作为误差估计
  6. 延迟补偿:将查询持续时间添加到时间戳中,使结果表示“现在”
  7. 系统比较:将共识与系统时钟进行比较

延迟补偿

服务器跟踪查询NTP服务器和计算共识所需的时间(通常为100-500ms)。默认情况下,此持续时间将添加到共识时间戳中,因此返回的时间表示发送响应的时间,而不是查询开始的时间。

例子:

  • 查询从T+0ms开始
  • NTP共识在T+150ms时计算→ 时间戳=12:00:00.000
  • 延迟补偿:12:00:00.000+150ms=12:00:00.150
  • 响应在T+150ms发送,时间戳为12:00:00.150

这确保了呼叫者收到时间戳时尽可能准确。您可以通过以下方式禁用此功能 compensate_latency=false 如果你更喜欢原始的共识时间戳。

时区支持

服务器使用Python zoneinfo 使用IANA tzdata获取权威时区信息的模块:

  1. IANA tzdata来源:使用IANA官方时区数据库(由IANA维护,由全球专家策划)
  2. DST处理:使用历史和未来规则自动进行夏令时转换
  3. 政治边界:处理所有时区更改、国家边界和历史调整
  4. 过渡检测:确定即将到来的夏令时变化和偏移修改
  5. 无系统时钟依赖性:所有时区转换都使用NTP共识时间,而不是系统时钟

时区数据层次结构:

  • UTC权威机构:NTP共识(time.google.com、time.cloudflare.com等)
  • 政治时间:IANA tzdata(官方时区数据库)
  • 本地转换:Python zoneinfo 模块
  • 结果:与系统时钟无关的准确本地时间

默认NTP服务器

  • time.cloudflare.com -Cloudflare的任播NTP
  • time.google.com -谷歌的公共NTP
  • time.apple.com -苹果的NTP服务器
  • 0-3.pool.ntp.org -NTP池项目服务器

所有服务器都是第1-2层,以获得最大的准确性。

发展

设置

# Clone repository
git clone <repository-url>
cd chuk-mcp-time

# Install development dependencies
make dev-install

测试

# Run tests (skip network tests)
make test

# Run tests with coverage
make test-cov

# Run all tests including network tests
pytest -v

# Run specific test
pytest tests/test_consensus.py -v

代码质量

# Run linter
make lint

# Auto-format code
make format

# Type checking
make typecheck

# Security checks
make security

# Run all checks
make check

建筑

# Build distribution packages
uv build

# Build Docker image
make docker-build

# Run Docker container
make docker-run

部署

Fly.io

# Deploy to Fly.io
flyctl deploy

# Or use GitHub Actions (push to main branch)
git push origin main

码头工人

# Build image
docker build -t chuk-mcp-time .

# Run container
docker run -p 8000:8000 chuk-mcp-time

# With custom config
docker run -p 8000:8000 \
  -e TIME_SERVER_NTP_TIMEOUT=5.0 \
  -e TIME_SERVER_MIN_SOURCES=5 \
  chuk-mcp-time

建筑

chuk-mcp-time/
├── src/chuk_mcp_time/
│   ├── __init__.py
│   ├── config.py          # Pydantic Settings configuration
│   ├── models.py          # Pydantic models (enums, responses)
│   ├── ntp_client.py      # Async NTP client
│   ├── consensus.py       # Consensus algorithm engine
│   ├── timezone_utils.py  # IANA timezone utilities
│   └── server.py          # MCP server with 7 tools
├── tests/
│   ├── test_config.py
│   ├── test_consensus.py
│   ├── test_ntp_client.py
│   └── test_server_tools.py
├── pyproject.toml
├── Makefile
├── Dockerfile
├── fly.toml
└── README.md

用例

1.检测时钟漂移

# Use compare_system_clock to monitor clock health
response = await compare_system_clock(mode="accurate")

if response.status == "error":
    print(f"⚠️  System clock is off by {response.delta_ms:.1f}ms!")
    # Take corrective action...

2.日志的可信时间戳

# Get consensus time for reliable logging
time_info = await get_time_utc(mode="fast")

log_entry = {
    "event": "user_login",
    "timestamp": time_info.iso8601_time,
    "source_count": time_info.sources_used,
    "error_ms": time_info.estimated_error_ms
}

3.日程安排的时区转换

# Convert meeting time between timezones
result = await convert_time(
    datetime_str="2025-12-15T14:00:00",
    from_timezone="America/New_York",
    to_timezone="Asia/Tokyo"
)

print(result.explanation)
# "Asia/Tokyo is 14.0 hours ahead of America/New_York (UTC-5.0 → UTC+9.0)"
print(f"Meeting time in Tokyo: {result.to_datetime}")
# "2025-12-16T04:00:00+09:00"

4.多区域时间协调

# Get accurate local time for different regions
ny_time = await get_local_time("America/New_York")
london_time = await get_local_time("Europe/London")
tokyo_time = await get_local_time("Asia/Tokyo")

# All from the same NTP consensus - guaranteed consistency
# Each includes DST status, offset, and abbreviation
print(f"NY: {ny_time.local_datetime} ({ny_time.abbreviation})")
print(f"London: {london_time.local_datetime} ({london_time.abbreviation})")
print(f"Tokyo: {tokyo_time.local_datetime} ({tokyo_time.abbreviation})")

5.发现有效时区

# Search for timezones to avoid hallucination
timezones = await list_timezones(search="New")

for tz in timezones.timezones:
    print(f"{tz.id} - {tz.example_city}")
# America/New_York - New York
# America/North_Dakota/New_Salem - New Salem
# ...

6.围绕夏令时过渡进行规划

# Get upcoming DST transitions
info = await get_timezone_info("America/New_York")

print(f"Current: {info.current_abbreviation} (DST: {info.current_is_dst})")
print(f"Upcoming transitions:")
for transition in info.transitions:
    print(f"  {transition.from_datetime}: {transition.abbreviation} (DST: {transition.is_dst})")

7.金融/交易应用程序

# High-accuracy mode for financial operations
time_info = await get_time_utc(mode="accurate")

if time_info.estimated_error_ms < 20:
    # Error < 20ms, safe to use for timestamp-sensitive operations
    execute_trade(timestamp=time_info.epoch_ms)
else:
    # Too much uncertainty, defer or use alternative timing
    log_warning("Time uncertainty too high", error_ms=time_info.estimated_error_ms)

为什么在系统时间内使用此功能?

系统时钟问题

  • 漂移:系统时钟随时间漂移(通常为10-50ppm)
  • 虚拟化:虚拟机可能存在严重的时间偏差
  • 容器:Docker容器继承主机时钟问题
  • 发展:开发人员计算机的时间经常不正确
  • 分布式系统:很难信任跨多个主机的时间

此解决方案提供

  • 独立验证:多个外部来源
  • 孤立点检测:自动删除不良源
  • 透明度:查看所有源数据和警告
  • 误差界限:知道时间的准确性
  • 可审计性:调试时间问题的完整数据

演出

  • 快速模式:~40-150ms(查询4台服务器)
  • 精确模式:~100-300ms(查询7台服务器)
  • 典型精度:±10-50ms(比系统时钟漂移好得多)
  • 吞吐量:受NTP查询速率限制(建议高频使用缓存)

延迟故障

  • NTP查询(并发):每台服务器20-100ms
  • 共识计算:<1ms
  • 延迟补偿:自动添加到时间戳中
  • 总往返时间:40-300ms,具体取决于模式和网络

局限性

  • 需要网络:需要互联网访问NTP服务器
  • 延迟:每次查询100-500ms(不适合微秒精度)
  • 速率限制:不要过于频繁地查询(遵守NTP池指南)
  • 准确度:典型值为±10-50ms(对于大多数应用来说已经足够好了,不是原子钟精度)

贡献

欢迎投稿!拜托:

  1. 克隆该仓库
  2. 创建要素分支
  3. 通过测试进行更改
  4. 跑 make check 确保质量
  5. 提交拉取请求

许可证

Apache许可证2.0-有关详细信息,请参阅许可证。

学分

内置:

  • chuk mcp服务器-高性能mcp服务器框架
  • 派丹蒂克 -使用Python类型提示进行数据验证
  • NTP池项目服务器