Skip to main content
Glama
theoddden

io.github.theoddden/stamp

by theoddden

stamp-mcp

An MCP server for NTP time and clock drift. Zero dependencies, fully synchronous, raw JSON-RPC 2.0 over stdio -- no MCP library, no asyncio.

A single NTP query tells you where your clock is right now. Drift history tells you where it is going: a clock that is consistently 200ms fast and accelerating is a different problem than one that is stable at 200ms fast. get_time takes the measurement; every call appends to a local log; get_drift reads the log and reports the trend.

Install

pip install stamp-mcp

Related MCP server: chuk-mcp-time

Use with Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "stamp": {
      "command": "stamp-mcp"
    }
  }
}

Or run the module directly:

{
  "mcpServers": {
    "stamp": {
      "command": "python3",
      "args": ["-m", "stamp_mcp"]
    }
  }
}

Tools

  • get_time -- one NTP query: UTC time, this clock's offset in ms, network delay, stratum. Appends the sample to the drift log. Optional argument: server (default time.cloudflare.com).

  • get_drift -- analyzes the drift log: sample count, timespan, current/mean/stddev offset, drift rate in ms/day (least-squares fit), first-half vs. second-half rates, and a verdict: stable, drifting, or accelerating. Optional argument: server to filter samples.

The drift log

Every get_time call appends one JSON line to ~/.stamp/drift.jsonl (override with STAMP_DRIFT_LOG). The file is capped at 10,000 samples. Call get_time periodically -- a cron job, a heartbeat, or just asking Claude "check the clock" now and then -- and get_drift turns the accumulated offsets into a trend.

How it works

The whole server is stamp_mcp/server.py:

  • JSON-RPC 2.0 over stdio -- initialize, tools/list, tools/call, ping, notifications, and the standard error codes (-32700, -32601).

  • Raw NTP with real offset math -- a 48-byte NTPv3 packet over UDP 123 carrying our transmit timestamp; the response's receive (t2) and transmit (t3) timestamps are unpacked with struct.unpack("!II", ...) as 64-bit fixed point, and offset/delay follow RFC 5905: offset = ((t2-t1)+(t3-t4))/2, delay = (t4-t1)-(t3-t2).

  • Two rules that matter: stdout is the protocol channel (log to stderr only), and flush() after every write (subprocess stdout is block-buffered).

Development

client.py is a test harness that plays the role of an MCP host -- it spawns the server and performs the real handshake, printing every raw frame:

python3 client.py                          # tests server.py (stage 1)
python3 client.py server_atomic.py         # tests the standalone artifact
python3 client.py stamp_mcp/server.py      # tests the package

server.py and server_atomic.py are the from-scratch learning artifacts; stamp_mcp/ is the packaged, published server.

Publishing

The GitHub Action in .github/workflows/publish-mcp.yml runs on version tags (git tag v0.3.0 && git push origin v0.3.0) and does two things:

  1. Publishes the package to PyPI -- requires a PYPI_API_TOKEN repository secret (or configure Trusted Publishing on PyPI and remove the password line).

  2. Publishes metadata to the MCP Registry -- uses mcp-publisher with GitHub OIDC (id-token: write), no secret needed. The server name io.github.theoddden/stamp is bound to the GitHub account; the mcp-name HTML comment at the top of this README is the PyPI ownership verification marker.


Appendix: how this was built, stage by stage

Build an MCP server with no library, one concept at a time. By the end you will have written every line yourself and the official MCP SDK becomes a convenience you could discard.

Stage 1 -- raw JSON-RPC over stdio (DONE, verified)

  • server.py -- the entire protocol in ~100 lines: sys.stdin -> json -> dispatch -> sys.stdout -> flush().

  • client.py -- plays the role of Claude Desktop. Spawns the server and performs the real handshake, printing every raw frame.

Run it:

python3 client.py

Things to notice in the output:

  • initialize returns protocolVersion, capabilities, serverInfo.

  • notifications/initialized has no id and gets no response.

  • tools/list returns the manifest; inputSchema is plain JSON Schema.

  • tools/call results are {"content": [{"type": "text", ...}]}.

  • Unknown method -> JSON-RPC error -32601.

  • Unknown tool -> a normal result with isError: true (so the model can read the failure and recover).

  • Malformed JSON -> -32700.

Two rules that will bite you if ignored:

  1. stdout is the protocol channel. One stray print() corrupts the stream. Log to stderr only.

  2. flush() after every write. As a subprocess, stdout is block-buffered; without flush the host thinks the server is dead.

Stage 2 -- asyncio

Rewrite the stdin loop as an async coroutine:

  • async def main() + asyncio.run(main())

  • Read stdin without blocking the loop: loop.run_in_executor(None, sys.stdin.readline) or asyncio.StreamReader hooked to stdin via loop.connect_read_pipe.

  • await each handler.

The payoff comes in stage 4 -- for now it is the same server with a different engine.

Stage 3 -- real NTP

Replace the stub get_time with a real query.

  • First pass: pip install ntplib, then ntplib.NTPClient().request('pool.ntp.org', version=3).

  • Second pass (optional, illuminating): delete ntplib and write the UDP query yourself. NTPv3 packet = 48 bytes, first byte 0x1B (LI=0, VN=3, Mode=3), rest zeros. Send to port 123, read 48 bytes back, unpack the transmit timestamp (bytes 40-43, seconds since 1900) with struct.unpack('!I', ...). Subtract 2208988800 to get Unix time. ntplib is ~200 lines of exactly this -- read its source once.

Stage 4 -- blocking vs. the event loop

The lesson you learn by breaking it:

  1. Call ntplib directly inside your async def handler.

  2. While a slow NTP server is being queried, send a ping from the client. Watch it hang -- the single-threaded event loop is frozen.

  3. Fix it: await loop.run_in_executor(None, blocking_ntp_call). Blocking work goes to the thread pool; async work gets awaited.

Rule of thumb: ntplib, requests, file I/O = blocking. aiohttp, httpx (async mode), asyncpg = not blocking.

Connecting to Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "ntp-scratch": {
      "command": "/usr/bin/python3",
      "args": ["/Users/theowolfenden/CascadeProjects/mcp-from-scratch/server.py"]
    }
  }
}

Restart Claude Desktop, then ask it "what tools do you have?" -- get_time should appear. If it doesn't, check the logs at ~/Library/Logs/Claude/mcp*.log -- a stray print or missing flush is the usual culprit.

The wire protocol, in one glance

>>> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{...}}
<<< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05",...}}
>>> {"jsonrpc":"2.0","method":"notifications/initialized"}     (no reply)
>>> {"jsonrpc":"2.0","id":2,"method":"tools/list"}
<<< {"jsonrpc":"2.0","id":2,"result":{"tools":[...]}}
>>> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_time","arguments":{}}}
<<< {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"..."}]}}

That is the whole thing. Everything else is plumbing.

Available Tools

2 tools
get_driftAInspect

Analyze the drift log built by get_time: reports current offset, drift rate (ms/day), and whether the clock is stable, drifting, or accelerating.

ParametersJSON Schema
NameRequiredDescriptionDefault
serverNoOnly analyze samples from this NTP server

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden of behavioral disclosure. It communicates a read-only analysis operation and enumerates the computed outputs, which gives the agent an accurate model of what invoking the tool will do. It could mention behavior when no log exists or how the server filter affects results, but the core behavior is transparent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single sentence front-loads the primary purpose ('Analyze the drift log built by get_time') and then lists the specific reports produced. Every clause earns its place and there is no redundant or filler content.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple tool with one optional parameter and no output schema, the description covers the key context: what data it analyzes, what metrics it reports, and the relationship to get_time. It is not exhaustive about edge cases like empty logs or threshold definitions, but those are not required given the tool's simplicity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema already describes the only parameter, server, with 100% coverage. The tool description does not add extra meaning about parameter usage beyond the schema, so the baseline score of 3 is appropriate since the schema fully documents the parameter.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action (analyze), the resource (the drift log built by get_time), and the specific outputs (current offset, drift rate, stability status). It also distinguishes itself from its sibling get_time by framing itself as an analysis of that tool's log data.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description establishes a clear context: it operates on the drift log produced by get_time, implying get_time should be run first. It does not explicitly state when not to use it or compare it to alternatives, but for a two-tool sibling set the sequencing is strongly implied.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_timeAInspect

Query an NTP server for current UTC time and this clock's offset, and append the sample to the drift log. Call it periodically to build drift history.

ParametersJSON Schema
NameRequiredDescriptionDefault
serverNoNTP server to querytime.cloudflare.com

TDQS

A4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and it discloses an important behavioral trait: the call appends a sample to the drift log, which is a side effect beyond a simple read. It does not go into failure modes or output format, but it covers the main behavioral surprise.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences: the first states the operation and side effect, the second gives usage guidance. Every sentence earns its place, and there is no redundant wording.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with one optional parameter and no output schema, the description covers what it does, what side effect it causes, and how often to call it. It does not explicitly connect to the sibling get_drift, but the core calling context is sufficiently complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100% for the single parameter, so the schema already documents 'server' as the NTP server to query. The description adds almost no semantic value beyond the schema, making the baseline 3 appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description is specific: 'Query an NTP server for current UTC time and this clock's offset, and append the sample to the drift log.' It names a clear action, resource, and side effect, and it implicitly contrasts with the sibling get_drift by describing a data-collection operation rather than a read operation, though it never explicitly names the sibling.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The instruction 'Call it periodically to build drift history' gives clear context for when the tool should be used. However, it does not mention alternatives or explicitly say when not to use it compared to get_drift.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 2 tool updatesv0.3.0
    • First observedget_drift
    • First observedget_time

TDQS

A4.2/5.0
Disambiguation5/5

get_time is responsible for sampling a new NTP timestamp and appending it to the drift log, while get_drift is responsible for analyzing the accumulated log. Although both mention offset, their roles are clearly separated: one collects data, the other interprets it.

Naming Consistency5/5

Both tools follow a consistent get_<noun> naming pattern, making the tool surface predictable and easy to understand. There is no mixing of styles or vague verbs.

Tool Count3/5

With only two tools, the server is on the thin side, but the two tools cover the core sampling and analysis workflow of a narrow domain. The count is understandable but still feels minimal.

Completeness4/5

The server covers the essential workflow: sample time and analyze drift. Minor gaps exist, such as no way to inspect raw log entries or clear/reset the drift log, but these are not fatal for the stated purpose.

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Provides accurate time information from Network Time Protocol (NTP) servers with timezone support and security filtering. Features whitelist-based server approval, blocks unauthorized sources, and delivers structured time output with fallback mechanisms.
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    Provides high-accuracy time information by querying multiple NTP servers for consensus time, and comprehensive timezone support using IANA tzdata for conversions, DST handling, and clock drift detection independent of system time.
    7
    3
    Apache 2.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides accurate UTC time by aggregating and verifying data from multiple reliable sources like WorldClockAPI, Google, and GitHub. It enables users to retrieve time in various formats including ISO, Unix timestamps, and human-readable strings with automatic source fallback for reliability.
    1
    MIT
  • F
    license
    Not graded
    quality
    C
    maintenance
    Provides real-time time awareness to Hermes Agent by exposing date, time, and timezone tools through MCP, enabling on-demand temporal queries.
    1
    -

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/theoddden/Stamp-MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server