Skip to content

Latest commit

 

History

History
124 lines (109 loc) · 17.3 KB

PORTING.md

File metadata and controls

124 lines (109 loc) · 17.3 KB

Porting notes

This SDK is a port of @amplitude/mcp-analytics (Amplitude-MCP-Analytics-Node) to Python, taken at upstream commit c1cbb40 (v0.4.1). The wire contract is shared: event names, [MCP] -prefixed property names, property precedence, the anonymous-drop rule, the error-type taxonomy, and the anchor-derived identity math (uuid5 over the f08626eb-3a5c-4f3a-bec2-227ab3178022 namespace) are identical, so the same anchor produces the same device_id from either SDK and dashboards can slice both without special-casing.

Both SDKs emit raw-name and family-detection provenance by default and use the same client attribution rules. Missing User Agent values are omitted. Request protocol metadata takes precedence over the successful handshake response on the same connection.

Events with no recognized family use Other and family source none. Keep the client name fixtures in sync with the Node SDK's source references.

Namespace note. Through 0.1.x both SDKs derived device ids under 6ba7b812-9dad-11d1-80b4-00c04fd430c8. That is not a private namespace: it is NameSpace_OID, one of the four namespace UUIDs reserved by RFC 9562 Appendix A (uuid.NAMESPACE_OID in the Python standard library). Hashing under a globally published constant forfeits what the namespace argument is for — anyone can reproduce, and so reverse, every derived device_id, and any other system reaching for the same reserved value collides with us. It is now a randomly minted v4 namespace owned by this SDK, changed in lockstep with the Node SDK.

The process anchor changed with it: its value was a bare pid, and since the anchor key is used verbatim as user_id as well as hashed into device_id, two unrelated stdio servers on different machines that drew the same pid resolved to the same Amplitude user. It is now <pid>-<random hex>, minted once per process.

Both are data-continuity breaks for anchor-derived identities. Explicit identities (set_identity, resolve_identity, instrument_server(user_id=...)) are unaffected.

This is a fork point, not a sync target

Like the Node repo's own vendoring policy: provenance here is for attribution and archaeology, not an obligation to track upstream. When a Node change is worth pulling over, do it as a normal PR titled by user-visible impact (see "PR titles set the version" in AGENTS.md), and name the upstream commit in the PR body: Ports Amplitude-MCP-Analytics-Node @ <sha>.

Intentional divergences

Error fingerprint and normalized-message emission is ported from Node dfa10f4 (PR #67). Python's existing normalization now uses ASCII number and word boundaries to match JavaScript, including for Unicode messages. The Python emitters share one module rather than separate event files; both use the merged-property redaction boundary for normalized messages. No new public exports are needed. As in Node, in-band rejections have no fingerprint, while raised pre-dispatch errors retain their classified one.

Area Node Python Why
Integration seam wraps server.connect(transport); patches the private Server._requestHandlers Map; chains oninitialized/onclose wraps Server.run(...) (one run = one connection); replaces entries in the public request_handlers dict for ordinary requests; stream proxies match the initialize request to its successful response; run teardown = session end the Python SDK has no connect(transport), and ServerSession consumes initialize before the server handler registry; transports exist only as message streams
Per-binding scope wraps every request handler in an AsyncLocalStorage frame one ContextVar set around the delegated run — anyio task groups copy context at start_soon, so handler tasks inherit it no per-handler machinery needed; also fixes stateless-HTTP concurrency (one shared Server, many concurrent runs)
Dispatch de-dup WeakSet keyed on the per-request extra object mutable DispatchMarker in a ContextVar; instrument_tool mutates the marker retrieved from the copied context RequestContext is an eq-comparing dataclass (unhashable); mutation survives anyio.to_thread context copies
Ambient context AsyncLocalStorage contextvars.ContextVar direct equivalent
Transport detection structural probe on the transport object (handleRequest) evidence from message metadata (HTTP request → streamable-http; session_id query param → sse; none → stdio); transport= override on instrument_server no transport object crosses the seam
[MCP] Transport values stdio | streamable-http adds sse (deprecated HTTP+SSE transport) truthful reporting; documented as a Python-only value
Error classification inputs AbortError, Node syscall codes, err.status/err.statusCode TimeoutError/CancelledError; ConnectionError family + gaierror (emitting econnrefused-style codes for cross-SDK parity); err.status/err.status_code/err.response.status_code platform idioms; the emitted taxonomy is identical
TrackingProxy exists (frozen ES module namespaces can't be patched) deleted — a plain DeliveryClient wrapper composes the same hooks in the same order Python objects are mutable
utils/resolve-module (bundler detection) exists deleted — a three-line lazy importlib import no bundler-rewrite problem in Python
setIdentity / set_identity signature one options object: setIdentity({ userId }) keyword arguments — set_identity(user_id=...) — with a positional SetIdentityInput still accepted (what an IdentityResolver returns); both in one call raises ValueError JS has no keyword arguments, so its options object is the only spelling available; Python has them, and requiring a wrapper dataclass for the common one-field call is noise
Logger resolution console-backed logger, overridable via the client always logging.getLogger("amplitude_mcp_analytics") the amplitude-analytics Config.logger is never None, so preferring it routed every SDK warning into the amplitude namespace, where a host silencing that chatty logger loses ours too; Python's logger hierarchy is already the host's configuration surface
Exit warning process.on('beforeExit') atexit closest equivalent; fires once at interpreter shutdown, not on os._exit/SIGKILL
Delivery-failure warning (HTTP ≥ 400) composes the client-level configuration.callback per-event BaseEvent(callback=...) avoids mutating a caller-owned client's config
disabled_tool rejection reason reachable (tool.disable()) unreachable — the official Python SDK has no tool disable; kept in the taxonomy for cross-SDK schema parity documented in docs/events.md
Byte sizes Buffer.byteLength(JSON.stringify(v)) UTF-8 length of compact json.dumps / model_dump_json; pydantic values nested inside a payload (a validated model argument in a FastMCP tool's kwargs) are dumped through model_dump(mode='json') rather than dropping the size approximations across SDKs; documented. JS has no equivalent of "the framework handed the handler a parsed model", so the nested case is Python-only
Parameter-capture argument source reads args[0] only when the handler also received extra. Ported from src/tracking/param-capture.ts at d5c7eaf (v0.5.1) On a tools/call frame, the first instrumented call keeps keyword names present in req.params.arguments when that set is empty or overlaps the call's kwargs; a non-overlapping claim (an instrumented helper inside an uninstrumented tool) and a nested/direct call fall back to identity with the signature default. Low-level handlers are func(name, arguments), so capture uses the first positional mapping. An injected FastMCP Context is dropped. Enum members are unwrapped to .value. String lengths are UTF-16 code units (len(s.encode("utf-16-le")) // 2). A nested pydantic model counts as obj[n] by model_fields length The identity fallback still misses Field(...) and copied []/{}, and still drops interned False and short strings. An empty outer arguments object still applies to a helper that claims first (overlap cannot distinguish that case). [MCP] Request Size still measures the filled-in kwargs and the injected Context (and, on a low-level handler, args[0], the tool name), so it does not line up with Param Count. That measurement is a follow-up. str(float) / str(int) can differ from JavaScript String() for extreme numbers. Wire strings, caps, the SHA-256 fingerprint, and exclusion semantics (never_keys replaces, tool never unions) are unchanged
Stateless correlation anchor source reads _meta.traceparent only prefers the standard HTTP traceparent header, with _meta as the fallback (a malformed header yields to _meta); the anchor value — the 32-hex trace id — is identical either way, so cross-SDK correlation is unchanged the header is the transport-level truth for the hop and what every W3C-compliant client, proxy, and tracing SDK propagates automatically, while _meta.traceparent is an in-band convention a client must opt into. Reading only _meta loses the anchor for normally-instrumented stateless HTTP callers, and a lost anchor is an anonymous floor — i.e. a dropped event by default. stdio is unaffected (no HTTP request)
traceparent validation any value with ≥4 hyphen-separated fields whose 2nd field is 32 hex — so 00-<trace-id>-0000000000000000-01-junk and an all-zero parent id both anchor the complete W3C shape: exactly 4 fields, 2-hex version (ff rejected per spec), 32-hex non-zero trace-id, 16-hex non-zero parent-id, 2-hex flags a malformed header is not a correlation key — partial validation lets unrelated requests be stitched under one identity by a caller-supplied string. A valid header parses to the same anchor value in both SDKs
flush() / shutdown() accounting order settles the unflushed counters, then flushes flushes (or tears down), then settles only if that succeeded; flush() still returns the underlying client's result and the exception still propagates Node's order permanently silences the serverless "N events were tracked but never flushed" warning whenever the flush itself fails — the one case where the events really are still queued and the warning is the point
Idempotency marker placement set on whichever object was handed to instrumentServer set and checked on both views of one server — the FastMCP wrapper and its _mcp_server either view is a legal argument and both share the single wrapped run, so a marker on one view only lets instrument_server(other_view) slip past both the no-op guard and the different-client warning: the second client installs nothing (run is already wrapped) yet looks configured
Peer dependencies @amplitude/analytics-node, @modelcontextprotocol/sdk as peers hard dep on amplitude-analytics (lazy import, still only on the api_key path); mcp duck-typed, dev-group only Python has no peer-dependency concept, so the two peers split by whether they are required: a required peer maps to a hard dep (an extra would turn "you must have this" into a construction-time failure), while the MCP SDK is supplied by every consumer by definition and pinning a range here could only fight theirs
createMcpAnalytics factory exported alongside the class not ported redundant with AmplitudeMCPAnalytics(...) — the Node alias exists for callers who prefer a function, which is not a Python idiom worth a second name on the public surface
sanitize_rationale config none rewrites/drops [MCP] Rationale, fail-closed; an empty-string replacement is emitted as "" (the property is omitted only on None / a non-string / a raise, exactly like sanitize_error_message). Built-in PII redaction then runs on whatever string remains Python-only for now (same shape as the shared sanitize_error_message); port upstream if Node grows the property's redaction hook
Privacy / PII redaction Node emit seam, refreshed against Amplitude-AI-Node src/core/privacy.ts @ 792806e and Node MCP src/core/privacy.ts @ b496e8c (compressed IPv6, JPEG /9j/ base64, formatted phones, standalone redact_pii / custom patterns / callback on track options). Client methods still ignore per-call redaction fields and use MCPAnalyticsConfig. Identity and [MCP] dimensions except rationale, error message, and feedback comment are not redacted same knobs. redact_value walks tuples and leaves datetime values as-is (no Date special case: only dicts, lists, and tuples are walked). An original base64 image is replaced before custom text rules, then checked again; Node still redacts text first. A custom-pattern failure log omits the pattern source, and an unknown replacement group (IndexError from re.sub) becomes [content redacted] instead of dropping the event. Email letters are a stdlib-re range approximation of Latin/Greek/Cyrillic. Phone and IPv6 boundaries use an ASCII word class. Custom replacements use Python re syntax (\1), not JavaScript $1. [MCP] Feedback Comment is free text here, so the built-in pass runs after sanitize_error_message tuples, the image-before-text order, and treating the feedback comment as free text are Python adaptations. Node's privacy allowlist still leaves [MCP] Feedback Comment as a dimension (only sanitizeErrorMessage runs). The script approximation and ASCII boundaries keep the wire strings aligned without a regex dependency
submit_feedback registration McpServer.registerTool with a Zod input shape from the peer zod. Ported from src/core/feedback-tool.ts at 4898c97 FastMCP.add_tool with a typed function (Annotated + Field). The published FEEDBACK_TOOL_DEFINITION stays JSON Schema, matching the Node definition. A low-level Server warns and no-ops. The server-scope identity resolver is passed into the feedback context. [MCP] Feedback Comment is sliced to 500 characters again after PII redaction Python has no registerTool / Zod peer. The wire event, property names, rating scale, anonymous-floor drop, and the "no [MCP] Tool Call Response" rule are unchanged. Authenticated stateless HTTP has no session anchor, so the feedback call uses the same identity resolver as other server-scope events. A redaction replacement can grow the comment past the input cap
License file none in the repo MIT LICENSE at the repo root added for the PyPI release; the Node repo's absence was never a deliberate policy

MCP SDK support

Supported: mcp 1.16 and up, including 2.x. The development lock stays on 1.x; CI runs the full suite against 1.16.0, 1.30.0, and 2.3.0, including real stdio and loopback Streamable HTTP tests. MCP remains a consumer-supplied dependency.

core/mcp.py owns the era split and all access to the MCP package:

  • 1.x: unwrap FastMCP._mcp_server, wrap public request_handlers, read ambient request_ctx, and wrap run() with handshake stream proxies.
  • 2.x: unwrap MCPServer._lowlevel_server, wrap run() for stdio connection scope and teardown, and append one observer to the provisional middleware list. Middleware also covers HTTP paths that bypass run(). An SDK-owned request ContextVar makes the injected request context available to tool instrumentation, including handlers without a context argument. Feedback registration uses public add_tool on either high-level server. Before each tools/call, the adapter best-effort wraps the registered tool's private fn once to mark actual callback entry, including sync callbacks in worker threads. This does not claim instrumented parameter names or emit a response event. It distinguishes a tool's raised MCPError from failures in validation or resolution before the callback; late registrations are covered. If the private tool registry/callable shape is unavailable, middleware retains its existing best-effort rejection classification without breaking calls.

Both adapters share SDK-independent tool-call and tools-list observers. Only decorated handlers emit [MCP] Tool Call Response; undecorated tools do not. Both eras classify pre-dispatch rejections through the same taxonomy. Modern 2026-07-28 requests carry client/protocol information per request and emit no session lifecycle events. Legacy 2.x HTTP requests obtain handshake information from the public session properties even with a fresh request scope.

Surface Node Python Why
v2 request interception wraps the private handler map provisional middleware plus SDK-owned request ContextVar Python 2.x HTTP bypasses Server.run; middleware is the common request seam, including initialize
Legacy v2 HTTP teardown connection lifecycle instrumentation session-initialized, but no session-ended when requests bypass run() no reliable public per-session teardown hook; do not fabricate an ended event
v2 high-level server / feedback McpServer / registerTool MCPServer._lowlevel_server / public add_tool native server APIs differ; low-level Python servers still warn and no-op for feedback registration