implement-distributed-tracing

implement-distributed-tracing is a cursor rule for Cursor from PaulJPhilp/EffectPatterns. It costs 1,466 tokens per session, scanned A, original, MIT.

A TypeScript rule for propagating trace context between services, so related requests can share trace and span identifiers.

In plain words
What is it for?
Use it in HTTP services to create, receive, and forward trace context through request headers.
Why use it?
It lets developers connect logs and work across service boundaries when diagnosing a distributed request.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/pauljphilp/effectpatterns/implement-distributed-tracing
Clone the repo
git clone --depth 1 https://github.com/PaulJPhilp/EffectPatterns

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for implement-distributed-tracing

README.md
[![agentmods](https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/implement-distributed-tracing.svg)](https://agentmods.dev/rules/pauljphilp/effectpatterns/implement-distributed-tracing)
Your own site
<a href="https://agentmods.dev/rules/pauljphilp/effectpatterns/implement-distributed-tracing"><img src="https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/implement-distributed-tracing.svg" alt="Measured on agentmods" height="20"></a>
Per session 1,466 This file is loaded in full into every session.
When invoked 1,466 The same file — it is already loaded in full.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.01466 $0.01466
Opus 5 $0.00733 $0.00733
Sonnet 5 $0.00293 $0.00293
Haiku 4.5 $0.00147 $0.00147

Measured 3d ago against content hash fada4c2f00c9, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-06, from the pricing page.

Security

Grade A, and why

implement-distributed-tracing scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

content/published/rules/cursor/implement-distributed-tracing.mdc · 237 lines

How it starts

The opening of the file, as written. The whole thing — 237 lines — stays where its author put it; the contents beside it link to each section on GitHub.

description: Propagate trace context across service boundaries to correlate requests. globs: "**/*.ts" alwaysApply: true

Implement Distributed Tracing

Rule: Propagate trace context across service boundaries to correlate requests.

Example

import { Effect, Context, Layer } from "effect"
import { HttpClient, HttpClientRequest, HttpServerRequest, HttpServerResponse } from "@effect/platform"

// ============================================
// 1. Define trace context
// ============================================

interface TraceContext {
  readonly traceId: string
  readonly spanId: string
  readonly parentSpanId?: string
  readonly sampled: boolean
}

class CurrentTrace extends Context.Tag("CurrentTrace")<
  CurrentTrace,
  TraceContext
>() {}

// W3C Trace Context header names
const TRACEPARENT_HEADER = "traceparent"
const TRACESTATE_HEADER = "tracestate"

// ============================================
// 2. Generate trace IDs
// ============================================

const generateTraceId = (): string =>
  Array.from(crypto.getRandomValues(new Uint8Array(16)))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")

const generateSpanId = (): string =>
  Array.from(crypto.getRandomValues(new Uint8Array(8)))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")

// ============================================
// 3. Parse and format trace context
// ============================================

const parseTraceparent = (header: string): TraceContext | null => {
  // Format: 00-traceId-spanId-flags
  const parts = header.split("-")
  if (parts.length !== 4) return null

  return {
    traceId: parts[1],
    spanId: generateSpanId(),  // New span for this service
    parentSpanId: parts[2],
    sampled: parts[3] === "01",
  }
}

const formatTraceparent = (ctx: TraceContext): string =>
  `00-${ctx.traceId}-${ctx.spanId}-${ctx.sampled ? "01" : "00"}`

// ============================================
// 4. Extract trace from incoming request
// ============================================

const extractTraceContext = Effect.gen(function* () {
  const request = yield* HttpServerRequest.HttpServerRequest

  const traceparent = request.headers[TRACEPARENT_HEADER]

  if (traceparent) {
    const parsed = parseTraceparent(traceparent)
    if (parsed) {
      yield* Effect.log("Extracted trace context").pipe(
        Effect.annotateLogs({
          traceId: parsed.traceId,
          parentSpanId: parsed.parentSpanId,
        })
      )
      return parsed
    }
  }

  // No incoming trace - start a new one
  const newTrace: TraceContext = {
    traceId: generateTraceId(),
    spanId: generateSpanId(),
    sampled: Math.random() < 0.1,  // 10% sampling
  }

  yield* Effect.log("Started new trace").pipe(
    Effect.annotateLogs({ traceId: newTrace.traceId })
  )

  return newTrace
})

// ============================================
// 5. Propagate trace to outgoing requests
// ============================================

const makeTracedHttpClient = Effect.gen(function* () {
  const baseClient = yield* HttpClient.HttpClient
  const trace = yield* CurrentTrace

  return {
    get: (url: string) =>
      Effect.gen(function* () {
        // Create child span for outgoing request
        const childSpan: TraceContext = {
          traceId: trace.traceId,
          spanId: generateSpanId(),
          parentSpanId: trace.spanId,
          sampled: trace.sampled,
        }

        yield* Effect.log("Making traced HTTP request").pipe(
          Effect.annotateLogs({
            traceId: childSpan.traceId,
            spanId: childSpan.spanId,
            url,
          })
        )

        const request = HttpClientRequest.get(url).pipe(
          HttpClientRequest.setHeader(
            TRACEPARENT_HEADER,
            formatTraceparent(childSpan)
          )
        )

        return yield* baseClient.execute(request)
      }),
  }
})

// ============================================
// 6. Tracing middleware for HTTP server
// ============================================

const withTracing = <A, E, R>(
  handler: Effect.Effect<A, E, R | CurrentTrace>
): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>
  Effect.gen(function* () {
    const traceContext = yield* extractTraceContext

    return yield* handler.pipe(
      Effect.provideService(CurrentTrace, traceContext),
      Effect.withLogSpan(`request-${traceContext.spanId}`),
      Effect.annotateLogs({
        "trace.id": traceContext.traceId,
        "span.id": traceContext.spanId,
        "parent.span.id": traceContext.parentSpanId ?? "none",
      })
    )
  })

// ============================================
// 7. Example: Service A calls Service B
// ============================================

// Service B handler
const serviceBHandler = withTracing(
  Effect.gen(function* () {
    const trace = yield* CurrentTrace
    yield* Effect.log("Service B processing request")

    // Simulate work
    yield* Effect.sleep("50 millis")

    return HttpServerResponse.json({
      message: "Hello from Service B",
      traceId: trace.traceId,
    })
  })
)

// Service A handler (calls Service B)
const serviceAHandler = withTracing(
  Effect.gen(function* () {
    const trace = yield* CurrentTrace
    yield* Effect.log("Service A processing request")

    // Call Service B with trace propagation
    const tracedClient = yield* makeTracedHttpClient
    const response = yield* tracedClient.get("http://service-b/api/data")

    yield* Effect.log("Service A received response from B")

    return HttpServerResponse.json({
      message: "Hello from Service A",
      traceId: trace.traceId,
    })
  })
)

// ============================================
// 8. Run and observe
// ============================================

const program = Effect.gen(function* () {
  yield* Effect.log("=== Distributed Tracing Demo ===")

  // Simulate incoming request with trace
  const incomingTrace: TraceContext = {
    traceId: generateTraceId(),
    spanId: generateSpanId(),
    sampled: true,
  }

  yield* Effect.log("Processing traced request").pipe(
    Effect.provideService(CurrentTrace, incomingTrace),
    Effect.annotateLogs({
      "trace.id": incomingTrace.traceId,
      "span.id": incomingTrace.spanId,
    })
  )
})

Effect.runPromise(program)

Read the full file on GitHub · 237 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 237 lines · 1,466 tokens per session scan A fada4c2f00c9

Subscribe to this mod's changes

implement-distributed-tracing is a cursor rule published in the GitHub repository PaulJPhilp/EffectPatterns (796 stars, last pushed 2mo ago), licensed MIT. It adds 1,466 tokens to every session, about $0.0073 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.