Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/user-hash-spans.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hevy-mcp": patch
---

Use the OpenTelemetry `user.hash` semantic convention and propagate the user hash to every recorded span.
24 changes: 22 additions & 2 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const originalEnv = { ...process.env };
const originalArgv = [...process.argv];
const TEST_KEY_HMAC_SHA256 = "2cb0b5f95a";
const TEST_API_KEY_HMAC_SHA256 = "0eefd4f47c";
const TEST_SECRET_API_KEY_HMAC_SHA256 = "e09f100508";

const testDoubles = vi.hoisted(() => ({
span: {
Expand Down Expand Up @@ -84,8 +85,8 @@ vi.mock("./utils/telemetry.js", () => ({
},
serviceName: "hevy-mcp",
serviceVersion: "dev",
setCurrentUserId: vi.fn(),
getCurrentUserId: vi.fn(() => undefined),
setCurrentUserHash: vi.fn(),
getCurrentUserHash: vi.fn(() => undefined),
}));

vi.mock("./utils/metrics.js", () => ({
Expand Down Expand Up @@ -199,6 +200,7 @@ describe("Server entry", () => {
expect.objectContaining({
attributes: expect.objectContaining({
"mcp.server.name": "hevy-mcp",
"user.hash": TEST_KEY_HMAC_SHA256,
}),
}),
expect.any(Function),
Expand Down Expand Up @@ -491,6 +493,15 @@ describe("Server entry", () => {
expect(Sentry.setUser).toHaveBeenCalledWith({
id: TEST_API_KEY_HMAC_SHA256,
});
expect(testDoubles.startActiveSpan).toHaveBeenCalledWith(
"mcp.server.run",
expect.objectContaining({
attributes: expect.objectContaining({
"user.hash": TEST_API_KEY_HMAC_SHA256,
}),
}),
expect.any(Function),
);
expect(
JSON.stringify(vi.mocked(Sentry.setUser).mock.calls),
).not.toContain(secret);
Expand Down Expand Up @@ -656,6 +667,15 @@ describe("Server entry", () => {
"https://api.hevyapp.com",
{ maxGetRetries: 0, timeoutMs: 5_000 },
);
expect(testDoubles.startActiveSpan).toHaveBeenCalledWith(
"mcp.server.run",
expect.objectContaining({
attributes: expect.objectContaining({
"user.hash": TEST_SECRET_API_KEY_HMAC_SHA256,
}),
}),
expect.any(Function),
);
errorSpy.mockRestore();
stdoutSpy.mockRestore();
},
Expand Down
27 changes: 19 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
tracer,
serviceName,
serviceVersion,
setCurrentUserId,
setCurrentUserHash,
} from "./utils/telemetry.js";
import { serverStartups } from "./utils/metrics.js";

Expand Down Expand Up @@ -79,9 +79,9 @@ const SAFE_NETWORK_ERROR_CODES = new Set([
const SENTRY_USER_ID_CONTEXT = "hevy-mcp:sentry-user-id:v1";

function fingerprintApiKey(apiKey: string) {
// HMAC-SHA-256 gives Sentry a deterministic pseudonymous user ID without
// sending, logging, or storing the raw Hevy API key.
// Trimmed to 10 characters to keep it compact and readable in Sentry & OTel traces.
// HMAC-SHA-256 gives Sentry and OTel a deterministic pseudonymous user
// hash without sending, logging, or storing the raw Hevy API key.
// Trimmed to 10 characters to keep it compact and readable in traces.
return createHmac("sha256", apiKey)
.update(SENTRY_USER_ID_CONTEXT)
.digest("hex")
Expand Down Expand Up @@ -161,7 +161,8 @@ async function validateApiKey(apiKey: string) {
}

function buildServer(apiKey: string) {
const userId = fingerprintApiKey(apiKey);
const userHash = fingerprintApiKey(apiKey);
setCurrentUserHash(userHash);

return tracer.startActiveSpan(
"mcp.server.build",
Expand All @@ -170,13 +171,12 @@ function buildServer(apiKey: string) {
"mcp.server.name": name,
"mcp.server.version": version,
"mcp.transport": "stdio",
"user.id": userId,
"user.hash": userHash,
},
},
(span) => {
try {
Sentry.setUser({ id: userId });
setCurrentUserId(userId);
Sentry.setUser({ id: userHash });
const server = createSharedMcpServer({
apiKey,
clientOptions: createNodeHevyClientOptions(),
Expand Down Expand Up @@ -224,11 +224,22 @@ export async function runServer() {

serverStartups.add(1, { version });

// Seed the user context before config validation so startup failures for a
// supplied key retain the same trace correlation as normal tool calls.
const configuredApiKey = process.env.HEVY_API_KEY;
const initialUserHash = configuredApiKey
? fingerprintApiKey(configuredApiKey)
: undefined;
if (initialUserHash) {
setCurrentUserHash(initialUserHash);
}
Comment on lines +231 to +234

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To ensure that Sentry error events captured during startup validation failures (e.g., when validateApiKey throws an error) are also associated with the correct user context, we should seed the Sentry user ID alongside the OpenTelemetry user hash.

Suggested change
if (initialUserHash) {
setCurrentUserHash(initialUserHash);
}
if (initialUserHash) {
setCurrentUserHash(initialUserHash);
Sentry.setUser({ id: initialUserHash });
}


await tracer.startActiveSpan(
"mcp.server.run",
{
attributes: {
"mcp.transport": "stdio",
...(initialUserHash ? { "user.hash": initialUserHash } : {}),
},
},
async (span) => {
Expand Down
10 changes: 5 additions & 5 deletions src/utils/hevy-client-observability.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { HevyHttpError } from "./hevy-http-error.js";
import { createNodeHevyClientOptions } from "./hevy-client-observability.js";
import { getCurrentUserId } from "./telemetry.js";
import { getCurrentUserHash } from "./telemetry.js";

const testDoubles = vi.hoisted(() => ({
span: {
Expand All @@ -17,7 +17,7 @@ const testDoubles = vi.hoisted(() => ({
testDoubles.startSpan.mockReturnValue(testDoubles.span);

vi.mock("./telemetry.js", () => ({
getCurrentUserId: vi.fn(() => undefined),
getCurrentUserHash: vi.fn(() => undefined),
tracer: { startSpan: testDoubles.startSpan },
}));

Expand All @@ -34,11 +34,11 @@ describe("createNodeHevyClientOptions", () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.HEVY_MCP_API_TIMEOUT;
vi.mocked(getCurrentUserId).mockReturnValue(undefined);
vi.mocked(getCurrentUserHash).mockReturnValue(undefined);
});

it("records successful requests with bounded operational metadata", () => {
vi.mocked(getCurrentUserId).mockReturnValue("user-123");
vi.mocked(getCurrentUserHash).mockReturnValue("user-123");
const options = createNodeHevyClientOptions();

options.onRequestComplete?.({
Expand All @@ -53,7 +53,7 @@ describe("createNodeHevyClientOptions", () => {
"http.method": "GET",
"http.status_code": 200,
"hevy.api.endpoint": "/v1/user/info",
"user.id": "user-123",
"user.hash": "user-123",
},
});
expect(testDoubles.span.setStatus).toHaveBeenCalledWith({ code: 1 });
Expand Down
6 changes: 3 additions & 3 deletions src/utils/hevy-client-observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { debugLog } from "./debug.js";
import type { HevyClientOptions } from "./hevyClientKubb.js";
import { apiCalls, apiDuration } from "./metrics.js";
import { createSafeErrorDiagnostic } from "./safe-error-diagnostic.js";
import { getCurrentUserId, tracer } from "./telemetry.js";
import { getCurrentUserHash, tracer } from "./telemetry.js";

/** Node-only adapter; the Worker graph never imports telemetry or metrics. */
export function createNodeHevyClientOptions(): HevyClientOptions {
Expand All @@ -21,8 +21,8 @@ export function createNodeHevyClientOptions(): HevyClientOptions {
"http.method": observation.method,
"http.status_code": observation.status,
"hevy.api.endpoint": observation.endpoint,
...(getCurrentUserId()
? { "user.id": getCurrentUserId() as string }
...(getCurrentUserHash()
? { "user.hash": getCurrentUserHash() }
: {}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🐞 Bug - Double State Read: Capture the return value in a local variable before the spread:

const userHash = getCurrentUserHash();
...(userHash ? { "user.hash": userHash } : {}),
Suggested change
...(getCurrentUserHash()
? { "user.hash": getCurrentUserHash() }
: {}),
...((() => { const userHash = getCurrentUserHash(); return userHash ? { "user.hash": userHash } : {}; })()),
Is this review accurate? Use 👍 or 👎 to rate it

If you want to tell us more, use /gs feedback e.g. /gs feedback this review doesn't make sense, I disagree, and it keeps repeating over and over

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🐞 Bug - Double Hash Lookup: Capture the result in a local variable and use it in both branches:

const userHash = getCurrentUserHash();
...(userHash ? { "user.hash": userHash } : {}),
Suggested change
...(getCurrentUserHash()
? { "user.hash": getCurrentUserHash() }
: {}),
...((() => { const userHash = getCurrentUserHash(); return userHash ? { "user.hash": userHash } : {}; })()),
Is this review accurate? Use 👍 or 👎 to rate it

If you want to tell us more, use /gs feedback e.g. /gs feedback this review doesn't make sense, I disagree, and it keeps repeating over and over

},
});
Expand Down
4 changes: 2 additions & 2 deletions src/utils/stdio-observability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ vi.mock("./telemetry.js", () => ({
},
serviceName: "hevy-mcp",
serviceVersion: "dev",
setCurrentUserId: vi.fn(),
getCurrentUserId: vi.fn(() => undefined),
setCurrentUserHash: vi.fn(),
getCurrentUserHash: vi.fn(() => undefined),
}));

vi.mock("./metrics.js", () => ({
Expand Down
12 changes: 6 additions & 6 deletions src/utils/telemetry-wrapper.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { HevyHttpError } from "./hevy-http-error.js";
import { getCurrentUserId } from "./telemetry.js";
import { getCurrentUserHash } from "./telemetry.js";
import { withTelemetry } from "./telemetry-wrapper.js";

const testDoubles = vi.hoisted(() => ({
Expand All @@ -22,7 +22,7 @@ const testDoubles = vi.hoisted(() => ({

vi.mock("./telemetry.js", () => ({
tracer: { startActiveSpan: testDoubles.startActiveSpan },
getCurrentUserId: vi.fn(() => undefined),
getCurrentUserHash: vi.fn(() => undefined),
}));

vi.mock("./metrics.js", () => ({
Expand All @@ -39,7 +39,7 @@ describe("withTelemetry", () => {
beforeEach(() => {
delete process.env.HEVY_MCP_DEBUG;
vi.clearAllMocks();
vi.mocked(getCurrentUserId).mockReturnValue(undefined);
vi.mocked(getCurrentUserHash).mockReturnValue(undefined);
});

it("emits redacted debug input from the central tool wrapper", async () => {
Expand Down Expand Up @@ -258,8 +258,8 @@ describe("withTelemetry", () => {
);
});

it("preserves safe argument ordering, scalar values, truncation, and user ID", async () => {
vi.mocked(getCurrentUserId).mockReturnValue("user-123");
it("preserves safe argument ordering, scalar values, truncation, and user hash", async () => {
vi.mocked(getCurrentUserHash).mockReturnValue("user-123");
const handler = vi.fn().mockResolvedValue({ content: [] });
const longQuery = "a".repeat(120);

Expand All @@ -283,7 +283,7 @@ describe("withTelemetry", () => {
"workflow.name": "ArgsContext",
"mcp.tool.args.key_count": 6,
"mcp.tool.args.keys": "page,pageSize,query,includeCustom",
"user.id": "user-123",
"user.hash": "user-123",
"mcp.tool.args.page": 2,
"mcp.tool.args.pageSize": 10,
"mcp.tool.args.query": `${"a".repeat(100)}...`,
Expand Down
6 changes: 3 additions & 3 deletions src/utils/telemetry-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { debugLog, isDebugEnabled, redactToolArgs } from "./debug.js";
import { resolveErrorPolicy } from "./error-policy.js";
import { toolDuration, toolErrors, toolInvocations } from "./metrics.js";
import type { McpToolResponse } from "./response-formatter.js";
import { getCurrentUserId, tracer } from "./telemetry.js";
import { getCurrentUserHash, tracer } from "./telemetry.js";

/** Whitelist of safe argument keys that can be logged without exposing PII. */
const ARGUMENT_WHITELIST = new Set([
Expand Down Expand Up @@ -113,7 +113,7 @@ export function withTelemetry<TParams extends Record<string, unknown>>(

toolInvocations.add(1, { tool_name: context });

const userId = getCurrentUserId();
const userHash = getCurrentUserHash();
const safeArgs = extractSafeArgs(args);
const whitelistedKeys = Object.keys(safeArgs).map((key) =>
key.replace("mcp.tool.args.", ""),
Expand All @@ -127,7 +127,7 @@ export function withTelemetry<TParams extends Record<string, unknown>>(
"workflow.name": context,
"mcp.tool.args.key_count": argumentKeyCount,
"mcp.tool.args.keys": whitelistedKeys.join(","),
...(userId ? { "user.id": userId } : {}),
...(userHash ? { "user.hash": userHash } : {}),
...safeArgs,
},
},
Expand Down
25 changes: 25 additions & 0 deletions src/utils/telemetry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const testDoubles = vi.hoisted(() => ({
batchSpanProcessor: vi.fn(),
meterProvider: vi.fn(),
periodicExportingMetricReader: vi.fn(),
nodeTracerProviderOptions: undefined as unknown,
}));

vi.mock("@sentry/node", () => ({
Expand Down Expand Up @@ -63,6 +64,9 @@ vi.mock("@opentelemetry/sdk-trace-base", () => ({

vi.mock("@opentelemetry/sdk-trace-node", () => {
class MockNodeTracerProvider {
constructor(options: unknown) {
testDoubles.nodeTracerProviderOptions = options;
}
register = testDoubles.register;
}
return { NodeTracerProvider: MockNodeTracerProvider };
Expand Down Expand Up @@ -151,4 +155,25 @@ describe("telemetry initialization", () => {
expect(mod.serviceName).toBe("hevy-mcp");
expect(mod.serviceVersion).toBe("dev");
});
it("adds the current user hash to every started span", async () => {
vi.resetModules();
const mod = await import("./telemetry.js");
mod.setCurrentUserHash("hash-123");
expect(mod.getCurrentUserHash()).toBe("hash-123");

const providerOptions = testDoubles.nodeTracerProviderOptions as {
spanProcessors: Array<{
onStart: (span: unknown, parentContext: unknown) => void;
}>;
};
const processor = providerOptions.spanProcessors[0];
if (!processor) {
throw new Error("Expected user hash span processor");
}

const setAttribute = vi.fn();
processor.onStart({ setAttribute }, {});

expect(setAttribute).toHaveBeenCalledWith("user.hash", "hash-123");
});
});
39 changes: 30 additions & 9 deletions src/utils/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import type { SpanProcessor } from "@opentelemetry/sdk-trace";
import type {
ReadableSpan,
Span,
SpanProcessor,
} from "@opentelemetry/sdk-trace";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import {
MeterProvider,
Expand Down Expand Up @@ -73,9 +77,28 @@ const sentryClient = Sentry.init({
});

// --- OpenTelemetry tracer provider (dual export) ---
const spanProcessors: SpanProcessor[] = [new SentrySpanProcessor()];
let currentUserHash: string | undefined;

// Span processor 2: OTel Collector → Honeycomb (traces) — only if token is available
class UserHashSpanProcessor implements SpanProcessor {
onStart(span: Span): void {
if (currentUserHash) {
span.setAttribute("user.hash", currentUserHash);
}
}

onEnd(_span: ReadableSpan): void {}

async forceFlush(): Promise<void> {}

async shutdown(): Promise<void> {}
}

const spanProcessors: SpanProcessor[] = [
new UserHashSpanProcessor(),
new SentrySpanProcessor(),
];

// OTel Collector → Honeycomb traces — only if token is available
if (collectorToken) {
spanProcessors.push(
new BatchSpanProcessor(
Expand Down Expand Up @@ -144,12 +167,10 @@ export const serviceInfo: ServiceInfo = { name, version } as const;
export { name as serviceName, version as serviceVersion };

// --- User context for span attributes ---
let currentUserId: string | undefined;

export function setCurrentUserId(id: string): void {
currentUserId = id;
export function setCurrentUserHash(hash: string): void {
currentUserHash = hash;
}

export function getCurrentUserId(): string | undefined {
return currentUserId;
export function getCurrentUserHash(): string | undefined {
return currentUserHash;
}
Loading