mcp-ntp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ # EditorConfig is awesome: http://EditorConfig.org
2
+
3
+ # top-most EditorConfig file
4
+ root = true
5
+
6
+ [*]
7
+ charset = utf-8
8
+ indent_style = space
9
+ indent_size = 4
10
+ end_of_line = lf
11
+ insert_final_newline = true
12
+ trim_trailing_whitespace = true
@@ -0,0 +1,79 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # Environments
30
+ .env
31
+ .venv
32
+ env/
33
+ venv/
34
+ ENV/
35
+ env.bak/
36
+ venv.bak/
37
+
38
+ # uv/uvx specific
39
+ .uv/
40
+ .uvx/
41
+ .venv.uv/
42
+
43
+ # IDEs and editors
44
+ .idea/
45
+ .vscode/
46
+ *.swp
47
+ *.swo
48
+ *~
49
+
50
+ # OS specific
51
+ .DS_Store
52
+ Thumbs.db
53
+
54
+ # Debug and local development
55
+ debug/
56
+ local/
57
+
58
+ # Credentials
59
+ .pypirc
60
+
61
+ # Pytest
62
+ .pytest_cache/
63
+ .coverage/
64
+ .coverage
65
+
66
+ # Pre-commit
67
+ .pre-commit-config.yaml.cache
68
+
69
+ # debug
70
+ playground/
71
+
72
+ # cursor
73
+ .cursor*
74
+
75
+ # Claude
76
+ .claude/
77
+ # repomix
78
+ .repomixignore
79
+ repomix.config.json
mcp_ntp-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Guo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mcp_ntp-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-ntp
3
+ Version: 0.1.0
4
+ Summary: MCP-based NTP Time Service
5
+ Author-email: Scofield Guo <guozhi5658@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Guo
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ License-File: LICENSE
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: click
30
+ Requires-Dist: fastapi
31
+ Requires-Dist: fastmcp
32
+ Requires-Dist: mcp
33
+ Requires-Dist: ntplib
34
+ Requires-Dist: python-dotenv
35
+ Requires-Dist: requests
36
+ Requires-Dist: uvicorn
37
+ Description-Content-Type: text/markdown
38
+
39
+ # MCP-NTP 时间服务
40
+
41
+ 这是一个基于MCP(Model Context Protocol)的NTP时间服务,为大模型提供准确的网络时间获取功能。
42
+
43
+ ## 功能特性
44
+
45
+ - 从NTP服务器获取准确的网络时间
46
+ - 支持stdio和sse两种传输模式
47
+ - 提供`get_current_time`工具,方便大模型获取当前时间
48
+ - 支持环境变量和请求头两种配置NTP服务器的方式
49
+ - 返回详细的时间信息和NTP协议数据
50
+
51
+ ## 安装
52
+
53
+ ```bash
54
+ # 使用 uv 安装依赖
55
+ uv sync
56
+ ```
57
+
58
+ ## 配置
59
+
60
+ ### 环境变量配置(stdio模式)
61
+
62
+ 设置`NTP_DOMAIN_URL`环境变量:
63
+
64
+ ```bash
65
+ export NTP_DOMAIN_URL="time.windows.com"
66
+ ```
67
+
68
+ ### 请求头配置(sse模式)
69
+
70
+ 在请求头中包含`ntp_url`字段:
71
+
72
+ ```
73
+ ntp_url: time.windows.com
74
+ ```
75
+
76
+ ## 使用方法
77
+
78
+ ### stdio模式
79
+
80
+ ```bash
81
+ # 设置环境变量
82
+ export NTP_DOMAIN_URL="time.windows.com"
83
+
84
+ # 启动服务
85
+ python -m app
86
+ ```
87
+
88
+ ### sse模式
89
+
90
+ ```bash
91
+ # 启动服务
92
+ python -m app --transport sse --port 18002
93
+
94
+ # 使用curl测试
95
+ curl -H "ntp_url: time.windows.com" http://localhost:18002/sse
96
+ ```
97
+
98
+ ## 工具说明
99
+
100
+ ### get_current_time
101
+
102
+ 获取当前NTP服务器时间。
103
+
104
+ **参数:**
105
+ - `ntp_server` (可选): NTP服务器地址,如果不提供则使用环境变量或请求头中的配置
106
+
107
+ **返回数据:**
108
+ ```json
109
+ {
110
+ "ntp_server": "time.windows.com",
111
+ "ntp_timestamp": 1703123456.789,
112
+ "ntp_time": "2023-12-21T10:30:56.789",
113
+ "local_system_time": "2023-12-21T10:30:56.789",
114
+ "time_offset": 0.123,
115
+ "response_delay": 0.045
116
+ }
117
+ ```
118
+
119
+ ## 调试
120
+
121
+ 可以使用提供的测试NTP服务器进行调试:
122
+
123
+ ```bash
124
+ export NTP_DOMAIN_URL="time.windows.com"
125
+ python -m app -v
126
+ ```
127
+
128
+ ## 开发
129
+
130
+ ### 项目结构
131
+
132
+ ```
133
+ mcp-ntp/
134
+ ├── app/
135
+ │ ├── __init__.py # 主入口
136
+ │ ├── server.py # MCP服务器实现
137
+ │ ├── client.py # NTP客户端
138
+ │ └── config.py # 配置管理
139
+ ├── pyproject.toml # 项目配置
140
+ └── README.md # 说明文档
141
+ ```
142
+
143
+ ### 添加新的NTP服务器
144
+
145
+ 在`client.py`中的`get_current_time`函数可以轻松扩展支持更多NTP服务器配置。
146
+
147
+ ## 许可证
148
+
149
+ MIT License
@@ -0,0 +1,111 @@
1
+ # MCP-NTP 时间服务
2
+
3
+ 这是一个基于MCP(Model Context Protocol)的NTP时间服务,为大模型提供准确的网络时间获取功能。
4
+
5
+ ## 功能特性
6
+
7
+ - 从NTP服务器获取准确的网络时间
8
+ - 支持stdio和sse两种传输模式
9
+ - 提供`get_current_time`工具,方便大模型获取当前时间
10
+ - 支持环境变量和请求头两种配置NTP服务器的方式
11
+ - 返回详细的时间信息和NTP协议数据
12
+
13
+ ## 安装
14
+
15
+ ```bash
16
+ # 使用 uv 安装依赖
17
+ uv sync
18
+ ```
19
+
20
+ ## 配置
21
+
22
+ ### 环境变量配置(stdio模式)
23
+
24
+ 设置`NTP_DOMAIN_URL`环境变量:
25
+
26
+ ```bash
27
+ export NTP_DOMAIN_URL="time.windows.com"
28
+ ```
29
+
30
+ ### 请求头配置(sse模式)
31
+
32
+ 在请求头中包含`ntp_url`字段:
33
+
34
+ ```
35
+ ntp_url: time.windows.com
36
+ ```
37
+
38
+ ## 使用方法
39
+
40
+ ### stdio模式
41
+
42
+ ```bash
43
+ # 设置环境变量
44
+ export NTP_DOMAIN_URL="time.windows.com"
45
+
46
+ # 启动服务
47
+ python -m app
48
+ ```
49
+
50
+ ### sse模式
51
+
52
+ ```bash
53
+ # 启动服务
54
+ python -m app --transport sse --port 18002
55
+
56
+ # 使用curl测试
57
+ curl -H "ntp_url: time.windows.com" http://localhost:18002/sse
58
+ ```
59
+
60
+ ## 工具说明
61
+
62
+ ### get_current_time
63
+
64
+ 获取当前NTP服务器时间。
65
+
66
+ **参数:**
67
+ - `ntp_server` (可选): NTP服务器地址,如果不提供则使用环境变量或请求头中的配置
68
+
69
+ **返回数据:**
70
+ ```json
71
+ {
72
+ "ntp_server": "time.windows.com",
73
+ "ntp_timestamp": 1703123456.789,
74
+ "ntp_time": "2023-12-21T10:30:56.789",
75
+ "local_system_time": "2023-12-21T10:30:56.789",
76
+ "time_offset": 0.123,
77
+ "response_delay": 0.045
78
+ }
79
+ ```
80
+
81
+ ## 调试
82
+
83
+ 可以使用提供的测试NTP服务器进行调试:
84
+
85
+ ```bash
86
+ export NTP_DOMAIN_URL="time.windows.com"
87
+ python -m app -v
88
+ ```
89
+
90
+ ## 开发
91
+
92
+ ### 项目结构
93
+
94
+ ```
95
+ mcp-ntp/
96
+ ├── app/
97
+ │ ├── __init__.py # 主入口
98
+ │ ├── server.py # MCP服务器实现
99
+ │ ├── client.py # NTP客户端
100
+ │ └── config.py # 配置管理
101
+ ├── pyproject.toml # 项目配置
102
+ └── README.md # 说明文档
103
+ ```
104
+
105
+ ### 添加新的NTP服务器
106
+
107
+ 在`client.py`中的`get_current_time`函数可以轻松扩展支持更多NTP服务器配置。
108
+
109
+ ## 许可证
110
+
111
+ MIT License
@@ -0,0 +1,169 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import sys
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ import click
8
+ from dotenv import load_dotenv
9
+
10
+ try:
11
+ __version__ = version("mcp-ntp")
12
+ except PackageNotFoundError:
13
+ __version__ = "0.1.0"
14
+
15
+
16
+ def setup_logging(level: int = logging.INFO) -> logging.Logger:
17
+ """设置日志配置"""
18
+ logger = logging.getLogger("mcp-ntp")
19
+ logger.setLevel(level)
20
+
21
+ if not logger.handlers:
22
+ handler = logging.StreamHandler(sys.stderr)
23
+ formatter = logging.Formatter(
24
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
25
+ )
26
+ handler.setFormatter(formatter)
27
+ logger.addHandler(handler)
28
+
29
+ return logger
30
+
31
+
32
+ @click.version_option(__version__, prog_name="mcp-ntp")
33
+ @click.command()
34
+ @click.option(
35
+ "-v",
36
+ "--verbose",
37
+ count=True,
38
+ help="增加详细程度 (可多次使用)",
39
+ )
40
+ @click.option(
41
+ "--env-file",
42
+ type=click.Path(exists=True, dir_okay=False),
43
+ help=".env 文件路径"
44
+ )
45
+ @click.option(
46
+ "--transport",
47
+ type=click.Choice(["stdio", "sse"]),
48
+ default="stdio",
49
+ help="传输方式 (stdio 或 sse)",
50
+ )
51
+ @click.option(
52
+ "--port",
53
+ default=18002,
54
+ help="SSE 传输方式的监听端口",
55
+ )
56
+ @click.option(
57
+ "--host",
58
+ default="0.0.0.0",
59
+ help="SSE 传输方式的监听地址",
60
+ )
61
+ def main(
62
+ verbose: int,
63
+ env_file: str | None,
64
+ transport: str,
65
+ port: int,
66
+ host: str,
67
+ ) -> None:
68
+ """MCP-NTP 服务器
69
+
70
+ 支持 stdio 和 sse 两种传输方式。
71
+ """
72
+ # 设置日志级别
73
+ if verbose == 1:
74
+ current_logging_level = logging.INFO
75
+ elif verbose >= 2:
76
+ current_logging_level = logging.DEBUG
77
+ else:
78
+ current_logging_level = logging.WARNING
79
+
80
+ logger = setup_logging(current_logging_level)
81
+ logger.debug(f"日志级别设置为: {logging.getLevelName(current_logging_level)}")
82
+
83
+ # 加载环境变量
84
+ if env_file:
85
+ logger.debug(f"从文件加载环境变量: {env_file}")
86
+ load_dotenv(env_file, override=True)
87
+ else:
88
+ logger.debug("尝试从默认 .env 文件加载环境变量")
89
+ load_dotenv(override=True)
90
+
91
+ def was_option_provided(ctx: click.Context, param_name: str) -> bool:
92
+ return (
93
+ ctx.get_parameter_source(param_name)
94
+ != click.core.ParameterSource.DEFAULT_MAP
95
+ and ctx.get_parameter_source(param_name)
96
+ != click.core.ParameterSource.DEFAULT
97
+ )
98
+
99
+ # 确定最终的传输方式
100
+ final_transport = os.getenv("TRANSPORT", transport).lower()
101
+ if final_transport not in ["stdio", "sse"]:
102
+ logger.warning(f"无效的传输方式 '{final_transport}',使用 'stdio'")
103
+ final_transport = "stdio"
104
+
105
+ logger.debug(f"最终传输方式: {final_transport}")
106
+
107
+ # 确定端口和主机
108
+ final_port = int(os.getenv("PORT", port))
109
+ final_host = os.getenv("HOST", host)
110
+
111
+ if final_transport == "stdio":
112
+ logger.info("使用 STDIO 传输方式启动服务器")
113
+ asyncio.run(run_stdio_server())
114
+ else:
115
+ logger.info(f"使用 SSE 传输方式启动服务器,地址: http://{final_host}:{final_port}/sse")
116
+ asyncio.run(run_sse_server(final_host, final_port))
117
+
118
+
119
+ async def run_stdio_server():
120
+ """运行 STDIO 传输模式的 MCP 服务器"""
121
+ from mcp.server.stdio import stdio_server
122
+ from .server import create_mcp_server
123
+
124
+ import os
125
+ ntp_url = os.getenv("NTP_DOMAIN_URL")
126
+ app = create_mcp_server(ntp_url=ntp_url)
127
+
128
+ async with stdio_server() as (read_stream, write_stream):
129
+ await app.run(
130
+ read_stream, write_stream, app.create_initialization_options()
131
+ )
132
+
133
+
134
+ async def run_sse_server(host: str, port: int):
135
+ """运行 SSE 传输模式的 MCP 服务器"""
136
+ from mcp.server.sse import SseServerTransport
137
+ from starlette.applications import Starlette
138
+ from starlette.requests import Request
139
+ from starlette.routing import Mount, Route
140
+ from .server import create_mcp_server
141
+ import uvicorn
142
+
143
+ sse = SseServerTransport("/messages/")
144
+
145
+ async def handle_sse(request: Request):
146
+ ntp_url = request.headers.get("ntp_url")
147
+ app = create_mcp_server(ntp_url=ntp_url)
148
+ async with sse.connect_sse(
149
+ request.scope, request.receive, request._send
150
+ ) as streams:
151
+ await app.run(
152
+ streams[0], streams[1], app.create_initialization_options()
153
+ )
154
+
155
+ starlette_app = Starlette(
156
+ debug=True,
157
+ routes=[
158
+ Route("/sse", endpoint=handle_sse),
159
+ Mount("/messages/", app=sse.handle_post_message),
160
+ ],
161
+ )
162
+
163
+ config = uvicorn.Config(starlette_app, host=host, port=port)
164
+ server = uvicorn.Server(config)
165
+ await server.serve()
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()
@@ -0,0 +1,4 @@
1
+ from . import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,46 @@
1
+ import ntplib
2
+ import time
3
+ from datetime import datetime
4
+ from .config import NTP_DOMAIN_URL
5
+
6
+ def get_current_time(ntp_server=None):
7
+ """从NTP服务器获取当前时间"""
8
+ if ntp_server is None or ntp_server.strip() == "":
9
+ ntp_server = NTP_DOMAIN_URL
10
+
11
+ # 处理空串和None的情况
12
+ if not ntp_server:
13
+ raise ValueError("NTP服务器地址未配置,请设置NTP_DOMAIN_URL环境变量或在请求头中提供ntp_url")
14
+
15
+ # 去除首尾空格
16
+ ntp_server = ntp_server.strip()
17
+
18
+ try:
19
+ # 创建NTP客户端
20
+ ntp_client = ntplib.NTPClient()
21
+
22
+ # 从NTP服务器获取时间
23
+ response = ntp_client.request(ntp_server, version=3, timeout=5)
24
+
25
+ # 获取NTP时间戳
26
+ ntp_time = response.tx_time
27
+
28
+ # 转换为本地时间
29
+ local_time = datetime.fromtimestamp(ntp_time)
30
+
31
+ # 获取本地时间作为对比
32
+ local_system_time = datetime.now()
33
+
34
+ return {
35
+ "ntp_server": ntp_server,
36
+ "ntp_timestamp": ntp_time,
37
+ "ntp_time": local_time.isoformat(),
38
+ "local_system_time": local_system_time.isoformat(),
39
+ "time_offset": ntp_time - time.time(),
40
+ "response_delay": response.delay
41
+ }
42
+
43
+ except ntplib.NTPException as e:
44
+ raise Exception(f"NTP请求失败: {str(e)}")
45
+ except Exception as e:
46
+ raise Exception(f"获取NTP时间时发生错误: {str(e)}")
@@ -0,0 +1,10 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv()
5
+
6
+ def get_env(key: str, default=None):
7
+ return os.getenv(key, default)
8
+
9
+ # NTP服务器配置
10
+ NTP_DOMAIN_URL = get_env("NTP_DOMAIN_URL", "pool.ntp.org")