@codetelemetry/mcp 0.7.0 → 0.8.0

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.
Files changed (38) hide show
  1. package/README.md +72 -6
  2. package/dist/src/client/cli.js +177 -4
  3. package/dist/src/client/import/browser.d.ts +8 -0
  4. package/dist/src/client/import/browser.js +83 -47
  5. package/dist/src/client/import/convert.d.ts +3 -3
  6. package/dist/src/client/import/convert.js +15 -4
  7. package/dist/src/client/import/core.d.ts +23 -3
  8. package/dist/src/client/import/core.js +78 -9
  9. package/dist/src/client/import/estimate.d.ts +87 -0
  10. package/dist/src/client/import/estimate.js +187 -0
  11. package/dist/src/client/import/identity.d.ts +25 -0
  12. package/dist/src/client/import/identity.js +118 -0
  13. package/dist/src/client/import/model.d.ts +18 -0
  14. package/dist/src/client/import/model.js +127 -0
  15. package/dist/src/client/import/run.d.ts +15 -2
  16. package/dist/src/client/import/run.js +80 -2
  17. package/dist/src/client/import/sources/claudeCodeText.js +2 -2
  18. package/dist/src/client/import/sources/codexText.js +28 -2
  19. package/dist/src/client/import/sources/files.d.ts +5 -1
  20. package/dist/src/client/import/sources/files.js +23 -2
  21. package/dist/src/client/import/transport.d.ts +10 -0
  22. package/dist/src/client/import/transport.js +26 -0
  23. package/dist/src/client/index.d.ts +3 -1
  24. package/dist/src/client/index.js +3 -1
  25. package/dist/src/client/repositoryHook.js +6 -1
  26. package/dist/src/client/repositoryOrigin.d.ts +1 -0
  27. package/dist/src/client/repositoryOrigin.js +13 -0
  28. package/dist/src/client/rolloutRepository.d.ts +29 -0
  29. package/dist/src/client/rolloutRepository.js +84 -0
  30. package/dist/src/client/workspaceImport.js +4 -2
  31. package/dist/src/client/workspaces.d.ts +1 -1
  32. package/dist/src/client/workspaces.js +3 -1
  33. package/dist/src/tools.d.ts +5 -0
  34. package/dist/src/tools.js +88 -8
  35. package/dist/src/version.d.ts +1 -1
  36. package/dist/src/version.js +1 -1
  37. package/package.json +9 -1
  38. package/tool-manifest.json +48 -6
@@ -1,3 +1,4 @@
1
+ import { githubOrigin } from "./repositoryOrigin.js";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  export const REPOSITORY_HOOK_MARKER = "codetelemetry-repository-observation";
@@ -146,6 +147,7 @@ function git(cwd, args) {
146
147
  }).trim(); }
147
148
  catch { return ""; }
148
149
  }
150
+ const githubOrigin = ${githubOrigin.toString()};
149
151
  const repositoryRemoteIdentity = ${normalizeRepositoryRemote.toString()};
150
152
  const selectCodexOtelExporterLine = ${selectCodexOtelExporterLine.toString()};
151
153
  function remoteName(value) {
@@ -384,7 +386,9 @@ async function main() {
384
386
  if (!permitsAuthorization(url, destination.headers)) return;
385
387
  const cwd = path.resolve(String(input.new_cwd || input.cwd || process.cwd()));
386
388
  const root = git(cwd, ["rev-parse", "--show-toplevel"]) || cwd;
387
- const remote = repositoryRemoteIdentity(git(root, ["config", "--get", "remote.origin.url"]));
389
+ const rawRemote = git(root, ["config", "--get", "remote.origin.url"]);
390
+ const remote = repositoryRemoteIdentity(rawRemote);
391
+ const originUrl = githubOrigin(rawRemote);
388
392
  const initialCommit = git(root, ["rev-list", "--max-parents=0", "HEAD"]).split(/\s+/).filter(Boolean).sort()[0] || "";
389
393
  const commonDir = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
390
394
  const commonRoot = commonDir.endsWith(path.sep + ".git") ? path.dirname(commonDir) : root;
@@ -406,6 +410,7 @@ async function main() {
406
410
  attr("code.workspace.path", cwd),
407
411
  attr("hook.event", hookEvent),
408
412
  ];
413
+ if (originUrl) attributes.push(attr("vcs.repository.url.full", originUrl));
409
414
  if (sessionId) attributes.push(attr("session.id", sessionId));
410
415
  const body = JSON.stringify({ resourceLogs: [{
411
416
  resource: { attributes: [attr("service.name", "codetelemetry-connect")] },
@@ -0,0 +1 @@
1
+ export declare function githubOrigin(value: unknown): string | undefined;
@@ -0,0 +1,13 @@
1
+ export function githubOrigin(value) {
2
+ if (typeof value !== "string" || value.length > 200 || /\s/.test(value))
3
+ return;
4
+ const match = /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?)\/([a-z0-9._-]{1,104})\/?$/i.exec(value);
5
+ if (!match)
6
+ return;
7
+ const name = match[2].replace(/\.git$/i, "");
8
+ if (!name || name.length > 100 || name === "." || name === "..")
9
+ return;
10
+ if (/(?:cot_|gh[pousr]_|github_pat_|AKIA|ASIA|sk-|xox[baprs]-|npm_|AIza|eyJ)[a-z0-9_-]{12,}/i.test(match[1] + "/" + name))
11
+ return;
12
+ return "https://github.com/" + match[1] + "/" + name;
13
+ }
@@ -0,0 +1,29 @@
1
+ export declare function rolloutRepository(file: string): {
2
+ timeUnixNano: string;
3
+ attributes: {
4
+ "codex.parent_thread_id"?: string | undefined;
5
+ "vcs.repository.url.full"?: string | undefined;
6
+ "event.name": string;
7
+ "session.id": string;
8
+ };
9
+ } | null;
10
+ export declare function reportRolloutRepositories(files: string[], send: boolean, stateFile?: string): Promise<{
11
+ sent: number;
12
+ skipped: number;
13
+ observations: {
14
+ timeUnixNano: string;
15
+ attributes: {
16
+ "event.name": string;
17
+ "session.id": string;
18
+ "vcs.repository.url.full": string;
19
+ };
20
+ }[] | {
21
+ timeUnixNano: string;
22
+ attributes: {
23
+ "codex.parent_thread_id"?: string | undefined;
24
+ "vcs.repository.url.full"?: string | undefined;
25
+ "event.name": string;
26
+ "session.id": string;
27
+ };
28
+ }[];
29
+ }>;
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { githubOrigin } from "./repositoryOrigin.js";
4
+ import { assertKey } from "./keys.js";
5
+ import { toOtlpLogs } from "./import/otlpImport.js";
6
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
7
+ export function rolloutRepository(file) {
8
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | (fs.constants.O_NOFOLLOW || 0));
9
+ try {
10
+ if (!fs.fstatSync(fd).isFile())
11
+ throw new Error("Expected a regular rollout file.");
12
+ const bytes = Buffer.alloc(256 * 1024);
13
+ const length = fs.readSync(fd, bytes, 0, bytes.length, 0);
14
+ const end = bytes.subarray(0, length).indexOf(10);
15
+ if (end < 0 && length === bytes.length)
16
+ throw new Error("Rollout header exceeds 256 KiB.");
17
+ const header = JSON.parse(bytes.toString("utf8", 0, end < 0 ? length : end));
18
+ const meta = header.payload;
19
+ const id = meta?.id;
20
+ if (header.type !== "session_meta" || typeof id !== "string" || !uuid.test(id) ||
21
+ !path.basename(file).endsWith("-" + id + ".jsonl"))
22
+ throw new Error("Rollout header and filename must identify the same session.");
23
+ const at = Date.parse(header.timestamp);
24
+ if (!Number.isFinite(at) || at <= 0 || at > Date.now() + 300000)
25
+ throw new Error("Invalid rollout timestamp.");
26
+ const url = githubOrigin(meta.git?.repository_url);
27
+ const parent = meta.parent_thread_id;
28
+ if (!url && !(typeof parent === "string" && uuid.test(parent) && parent !== id))
29
+ return null;
30
+ return { timeUnixNano: String(BigInt(at) * 1000000n), attributes: {
31
+ "event.name": "codetelemetry.repository_observed", "session.id": id,
32
+ ...(url ? { "vcs.repository.url.full": url } : {}),
33
+ ...(typeof parent === "string" && uuid.test(parent) && parent !== id ? { "codex.parent_thread_id": parent } : {}),
34
+ } };
35
+ }
36
+ finally {
37
+ fs.closeSync(fd);
38
+ }
39
+ }
40
+ async function stateRepositories(file, ids) {
41
+ if (ids.some(id => !uuid.test(id)))
42
+ throw new Error("Select exact Codex thread UUIDs with --state.");
43
+ const { DatabaseSync } = await import("node:sqlite");
44
+ const db = new DatabaseSync(file, { readOnly: true, allowExtension: false });
45
+ try {
46
+ db.exec("PRAGMA trusted_schema=OFF; PRAGMA query_only=ON; PRAGMA busy_timeout=500; BEGIN");
47
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='threads'").get() ||
48
+ !db.prepare("SELECT count(*) FROM pragma_table_info('threads') WHERE pk>0 HAVING count(*)=1 AND max(name)='id'").get())
49
+ throw new Error("Unrecognized Codex state database.");
50
+ const read = db.prepare("SELECT updated_at, CASE WHEN length(CAST(git_origin_url AS BLOB)) <= 200 THEN git_origin_url END AS remote FROM threads WHERE id=?");
51
+ return ids.flatMap(id => {
52
+ const row = read.get(id);
53
+ const url = githubOrigin(row?.remote);
54
+ const seconds = Number(row?.updated_at);
55
+ if (!url || !Number.isSafeInteger(seconds) || seconds <= 0 || seconds > Date.now() / 1000 + 300)
56
+ return [];
57
+ return [{ timeUnixNano: String(BigInt(seconds) * 1000000000n), attributes: {
58
+ "event.name": "codetelemetry.repository_observed", "session.id": id, "vcs.repository.url.full": url,
59
+ } }];
60
+ });
61
+ }
62
+ finally {
63
+ db.close();
64
+ }
65
+ }
66
+ export async function reportRolloutRepositories(files, send, stateFile) {
67
+ if (!files.length || files.length > 100)
68
+ throw new Error("Select between 1 and 100 rollout files or thread IDs.");
69
+ const rows = stateFile ? await stateRepositories(stateFile, files) : files.map(rolloutRepository).filter(row => row !== null);
70
+ if (send && rows.length) {
71
+ const key = assertKey(process.env.CODETELEMETRY_INGEST_KEY);
72
+ const response = await fetch("https://ingest.codetelemetry.com/v1/logs", {
73
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(10000),
74
+ headers: { authorization: "Bearer " + key, "content-type": "application/json" },
75
+ body: JSON.stringify(toOtlpLogs(rows, { "service.name": "codetelemetry-connect" }, { name: "codetelemetry.rollout-repository", version: "1" })),
76
+ });
77
+ if (!response.ok)
78
+ throw new Error("Repository metadata delivery returned HTTP " + response.status);
79
+ const body = await response.text();
80
+ if (body && Number(JSON.parse(body).partialSuccess?.rejectedLogRecords || 0))
81
+ throw new Error("Collector rejected repository metadata.");
82
+ }
83
+ return { sent: send ? rows.length : 0, skipped: files.length - rows.length, observations: rows };
84
+ }
@@ -6,6 +6,7 @@ import { verifyScope } from "./connectivity.js";
6
6
  import { resolveEndpoints } from "./config.js";
7
7
  import { runImport } from "./import/run.js";
8
8
  import { sessionKeyOf } from "./import/model.js";
9
+ import { resolveImportIdentity } from "./import/identity.js";
9
10
  export async function importWorkspaceHistory(options, deps = {}) {
10
11
  const context = loadWorkspace(options.name);
11
12
  if (!context.scope.teamId || !context.clientConfig)
@@ -15,12 +16,13 @@ export async function importWorkspaceHistory(options, deps = {}) {
15
16
  const expected = context.scope;
16
17
  const previewFile = path.join(workspaceHome(), `${context.name}.import-preview.json`);
17
18
  const source = context.clientConfig.client === "claude" ? "claude-code" : "codex";
19
+ const identity = resolveImportIdentity({ source });
18
20
  if (options.preview) {
19
21
  if (options.confirm || options.selections)
20
22
  throw new Error("Preview and import confirmation are separate actions.");
21
23
  const capture = workspaceCaptureDefault(context);
22
24
  const content = { prompts: capture, toolDetails: capture };
23
- const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
25
+ const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source, identity,
24
26
  sinceMs: options.sinceMs, content: { "claude-code": content, codex: content }, previewOnly: true });
25
27
  const preview = { version: 1, workspace: context.name, keyHash: keyHash(context.ingestKey),
26
28
  project, createdAt: Date.now(), scope: expected, window: result.window, content: result.content,
@@ -50,7 +52,7 @@ export async function importWorkspaceHistory(options, deps = {}) {
50
52
  connectivityUrl: resolveEndpoints(endpoints).connectivityUrl, fetchImpl: deps.fetchImpl });
51
53
  if (verified.state !== "scope_verified")
52
54
  throw new Error(`Workspace is unavailable: ${verified.state}. No history was uploaded.`);
53
- return runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
55
+ return runImport({ ...deps, key: context.ingestKey, endpoints, project, source, identity,
54
56
  sinceMs: Date.parse(preview.window.sinceIso), untilMs: Date.parse(preview.window.untilIso),
55
57
  content: preview.content, selectedPlans, maxSessions: 100, timeLimitMs: 120_000 });
56
58
  }
@@ -1,5 +1,5 @@
1
1
  import type { KeyScope } from "./connectivity.ts";
2
- export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.7.0";
2
+ export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.8.0";
3
3
  export declare const MAX_WORKSPACE_BYTES: number;
4
4
  export declare const MAX_WORKSPACES = 64;
5
5
  export type WorkspaceBinding = {
@@ -5,7 +5,7 @@ import { createHash, randomBytes } from "node:crypto";
5
5
  import { buildOtelSection } from "./codexConfig.js";
6
6
  import { repositoryHookSource, quotedCommand, REPOSITORY_HOOK_FILE, REPOSITORY_HOOK_STATE_FILE } from "./repositoryHook.js";
7
7
  import { looksLikeKey } from "./keys.js";
8
- export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.7.0";
8
+ export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.8.0";
9
9
  export const MAX_WORKSPACE_BYTES = 64 * 1024;
10
10
  export const MAX_WORKSPACES = 64;
11
11
  const isContextFile = (name) => /^[a-z][a-z0-9_-]{0,63}\.json$/.test(name) && name !== REPOSITORY_HOOK_STATE_FILE;
@@ -230,6 +230,8 @@ function upgradeLegacyCodexObserver(codexHome) {
230
230
  const declaration = `const codexConfigPath = ${JSON.stringify(configPath)};`;
231
231
  const fingerprint = createHash("sha256").update(source.replace(declaration, 'const codexConfigPath = "";')).digest("hex");
232
232
  const recognized = new Set([
233
+ "a4265abbe2ab5f2f8919b330a60c047226b708f6a42af34738f31f75004b9db3",
234
+ "92297bee16fd6a4111339d96aa7adc3b2d0ee5d9def9337470f468758b527eae",
233
235
  "69dd5ad120636379875fc411bcaaa096defe475944d24a6e899dc9796472ab2d",
234
236
  "65eaa30f6c565b0298137986bbe4e94d0435f8fedc2574fa284e7979a5fa9ef4",
235
237
  ]);
@@ -19,6 +19,11 @@ export type ToolContext = {
19
19
  ledgerPath?: string;
20
20
  nowMs?: number;
21
21
  sleep?: (ms: number) => Promise<void>;
22
+ identityPaths?: {
23
+ claudeConfigPath?: string;
24
+ claudeSettingsPath?: string;
25
+ codexAuthPath?: string;
26
+ };
22
27
  };
23
28
  };
24
29
  export type ToolResult = {
package/dist/src/tools.js CHANGED
@@ -4,7 +4,7 @@ import { workspaceProject } from "./client/join.js";
4
4
  import fs from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
- import { resolveEndpoints, sendTestEvent, confirmLanded, verifyScope, getCostSignal, getSessionPerformance, normalizeSessionPerformanceService, findSimilarSessionErrors, searchCodingSessions, SESSION_SEARCH_REQUEST_TIMEOUT_MS, countReplyPhrases, estimateTaskSize, estimateLinearIssue, readGitHubGate, configureGitHubGate, interpretSession, readSessionEvents, compareSessions, planNextSession, graderConfigRequest, normalizePlan, PLAN_PROVIDERS, ONBOARD_CLIENTS, SESSION_FILTER_ASSISTANTS, isOnboardClient, CLIENTS, PI_EXTENSION_HINT, MAX_PLAN_TEXT, MAX_PLAN_STEPS, requestDeviceCode, pollOnce, onboard as onboardCore, looksLikeKey, scrub, runImport, resolveImportContent, } from "./client/index.js";
7
+ import { resolveEndpoints, sendTestEvent, confirmLanded, verifyScope, getCostSignal, getSessionPerformance, normalizeSessionPerformanceService, findSimilarSessionErrors, searchCodingSessions, SESSION_SEARCH_REQUEST_TIMEOUT_MS, countReplyPhrases, estimateTaskSize, estimateLinearIssue, readGitHubGate, configureGitHubGate, interpretSession, readSessionEvents, compareSessions, planNextSession, graderConfigRequest, normalizePlan, PLAN_PROVIDERS, ONBOARD_CLIENTS, SESSION_FILTER_ASSISTANTS, isOnboardClient, CLIENTS, PI_EXTENSION_HINT, MAX_PLAN_TEXT, MAX_PLAN_STEPS, requestDeviceCode, pollOnce, onboard as onboardCore, looksLikeKey, scrub, runImport, runEstimate, resolveImportContent, resolveImportIdentity, fetchPricing, priceEstimate, claudeRetentionCutoffMs, IMPORT_NEVER_RECOVERS, } from "./client/index.js";
8
8
  import { seedGraderConfig } from "./client/graderSeed.js";
9
9
  import { writeGraderArtifact } from "./client/graderArtifact.js";
10
10
  import { OnboardingSession } from "./session.js";
@@ -344,8 +344,9 @@ const IMPORT_MAX_SESSIONS = 200;
344
344
  const IMPORT_DEFAULT_SESSIONS = 50;
345
345
  const IMPORT_TIME_LIMIT_MS = 4 * 60_000;
346
346
  const IMPORT_MAX_MESSAGES = 10;
347
+ const stripPaths = (s) => s.replace(/(?:[A-Za-z]:)?[\\/][^\s:;,]+\.jsonl/g, "<session file>");
347
348
  function importSummary(r) {
348
- const stripPaths = (s) => s.replace(/(?:[A-Za-z]:)?[\\/][^\s:;,]+\.jsonl/g, "<session file>");
349
+ const unaffordable = r.billing && !r.billing.affordable;
349
350
  return {
350
351
  ok: r.ok,
351
352
  dryRun: r.dryRun,
@@ -356,6 +357,8 @@ function importSummary(r) {
356
357
  remaining: r.remaining,
357
358
  stoppedBy: r.stoppedBy,
358
359
  ...(r.topup !== undefined ? { topup: r.topup } : {}),
360
+ ...(r.billing ? { billing: r.billing } : {}),
361
+ ...(r.identity ? { identity: r.identity } : {}),
359
362
  sources: r.sources.map((s) => ({
360
363
  source: s.source,
361
364
  filesFound: s.filesFound,
@@ -365,6 +368,9 @@ function importSummary(r) {
365
368
  events: s.events,
366
369
  tokenPoints: s.metricPoints,
367
370
  tokens: s.tokens,
371
+ months: s.months.slice(-13),
372
+ firstEventMs: s.firstEventMs,
373
+ lastEventMs: s.lastEventMs,
368
374
  skipped: s.skipped,
369
375
  })),
370
376
  cleanupSessions: r.cleanup.length,
@@ -372,10 +378,14 @@ function importSummary(r) {
372
378
  warningCount: r.warnings.length,
373
379
  errors: r.errors.slice(0, IMPORT_MAX_MESSAGES).map(stripPaths),
374
380
  note: r.dryRun
375
- ? "Nothing was sent. Show the user this summary and the content setting, and ask before importing (dryRun false)."
376
- : r.remaining > 0
377
- ? "More sessions remain: call import_history again with the same arguments to continue."
378
- : "Import finished for this window. Imported sessions show in the dashboards like live ones, without latency, decisions or active time.",
381
+ ? "Nothing was sent. Show the user this summary, the content setting" + (r.billing ? ", the billing estimate" : "") +
382
+ " and the identity stamped on the rows, and ask before importing (dryRun false)." +
383
+ (unaffordable ? " The prepaid credit does not cover every session: a real import stops before the first one it cannot pay for." : "")
384
+ : r.stoppedBy === "budget"
385
+ ? "Stopped for budget: add credit or seats, then call import_history again with the same arguments; finished sessions are skipped."
386
+ : r.remaining > 0
387
+ ? "More sessions remain: call import_history again with the same arguments to continue."
388
+ : "Import finished for this window. Imported sessions show in the dashboards like live ones, without latency, decisions or active time.",
379
389
  };
380
390
  }
381
391
  const GITHUB_GATE_HOW_TO = {
@@ -414,7 +424,7 @@ const GRADER_CHECK_PROP = obj({
414
424
  enabled: { type: "boolean" },
415
425
  repositoryId: { type: "string", minLength: 1, maxLength: 512 },
416
426
  environment: { type: "string", minLength: 1, maxLength: 64, pattern: "^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$" },
417
- beforePush: { type: "boolean", description: "Require successful command evidence after the final edit and before pushing; subject to the backend's stricter required-command matcher validation." },
427
+ beforePush: { type: "boolean", description: "Require successful command evidence after the final edit and before pushing; the service accepts it only when matcherRule.include names the commands: one exactFingerprint equals/in condition, or all of source equals shell, executable equals/in and packageScript equals/in (each optionally with one repositoryRelativeWorkingDirectory equals condition). Broader matchers are refused." },
418
428
  matcherRule: GRADER_MATCHER_PROP,
419
429
  detectorRule: GRADER_MATCHER_PROP,
420
430
  applicabilityRule: GRADER_MATCHER_PROP,
@@ -910,6 +920,8 @@ export const TOOLS = [
910
920
  assistant: { type: "string", enum: ["all", ...SESSION_FILTER_ASSISTANTS], description: "Assistant filter (default all)." },
911
921
  minDurationMs: { type: "integer", minimum: 0, maximum: 31_536_000_000, description: "Inclusive minimum elapsed session span in milliseconds." },
912
922
  maxDurationMs: { type: "integer", minimum: 0, maximum: 31_536_000_000, description: "Inclusive maximum elapsed session span in milliseconds." },
923
+ start: { type: "integer", minimum: 0, maximum: 253_402_300_799, description: "Only sessions last active at or after this time, in Unix seconds." },
924
+ end: { type: "integer", minimum: 0, maximum: 253_402_300_799, description: "Only sessions last active before this time, in Unix seconds (after start)." },
913
925
  activity: {
914
926
  type: "string",
915
927
  enum: ["all", "substantive"],
@@ -1763,6 +1775,67 @@ export const TOOLS = [
1763
1775
  return { ok: true, gate: r.gate, settingsUrl: `${ep.apiBase}${GITHUB_GATE_SETTINGS_PATH}`, howTo: GITHUB_GATE_HOW_TO };
1764
1776
  },
1765
1777
  },
1778
+ {
1779
+ name: "estimate_history",
1780
+ title: "Estimate past sessions before importing them",
1781
+ description: "Use this when the user asks what importing their EXISTING local Claude Code or Codex history would cost, or how much history they have. " +
1782
+ "Needs no key and sends nothing: it reads ~/.claude/projects and ~/.codex/sessions on this machine and returns sessions and tokens per source, per UTC month and per day, the oldest and newest session, and the last-30-day pace, " +
1783
+ "priced with CodeTelemetry's public price list when it can be read. Imported tokens are billed like live usage: this month's included seat tokens first, then the per-million price from prepaid credit. " +
1784
+ "Claude Code deletes local transcripts cleanupPeriodDays (default 30) after their last activity, so an older Claude session survives only if it was captured live or its transcript is still on disk; goneForGood says from when. " +
1785
+ "Sessions already captured live are counted here but skipped by an import. To import, call import_history (dry run first).",
1786
+ inputSchema: obj({
1787
+ source: { type: "string", enum: ["claude-code", "codex", "all"], description: "Which history to read (default all)." },
1788
+ sinceDays: { type: "integer", minimum: 1, maximum: 364, description: "How many days back (default 364, the whole retained year)." },
1789
+ }),
1790
+ async handler(args, ctx) {
1791
+ const source = args.source ?? "all";
1792
+ if (source !== "all" && source !== "claude-code" && source !== "codex") {
1793
+ return { ok: false, error: "bad_input", message: "source must be claude-code, codex or all" };
1794
+ }
1795
+ const sinceDays = args.sinceDays ?? 364;
1796
+ if (typeof sinceDays !== "number" || !Number.isInteger(sinceDays) || sinceDays < 1 || sinceDays > 364) {
1797
+ return { ok: false, error: "bad_input", message: "sinceDays must be 1-364" };
1798
+ }
1799
+ const o = ctx.importOverrides ?? {};
1800
+ const now = o.nowMs ?? Date.now();
1801
+ const estimate = await runEstimate({
1802
+ source,
1803
+ sinceMs: Math.floor((now - sinceDays * 86_400_000) / 86_400_000) * 86_400_000,
1804
+ nowMs: now,
1805
+ claudeDir: o.claudeDir,
1806
+ codexDir: o.codexDir,
1807
+ claudeSettingsPath: o.identityPaths?.claudeSettingsPath ?? ctx.configPathsOverride?.claude,
1808
+ timeLimitMs: IMPORT_TIME_LIMIT_MS,
1809
+ });
1810
+ const pricing = await fetchPricing(endpointsFor(ctx).apiBase, ctx.fetchImpl);
1811
+ const cost = pricing ? priceEstimate(estimate, pricing) : null;
1812
+ const days = estimate.claudeCleanupPeriodDays;
1813
+ return {
1814
+ ok: true,
1815
+ estimate: {
1816
+ ...estimate,
1817
+ warnings: estimate.warnings.slice(0, IMPORT_MAX_MESSAGES).map(stripPaths),
1818
+ },
1819
+ pricing,
1820
+ cost,
1821
+ goneForGood: {
1822
+ ...(days !== null ? {
1823
+ claudeCleanupPeriodDays: days,
1824
+ claudeCutoffIso: new Date(claudeRetentionCutoffMs(now, days)).toISOString(),
1825
+ claude: `Claude Code deletes transcripts ${days} day(s) after their last activity, so a Claude Code session from before the cutoff survives only if CodeTelemetry captured it live or its transcript is still on disk (those are counted here).`,
1826
+ } : {}),
1827
+ codex: "Codex keeps its rollouts until they are removed.",
1828
+ neverRecovered: `An import never recovers ${IMPORT_NEVER_RECOVERS}.`,
1829
+ },
1830
+ note: "Nothing was sent and no key was used. " +
1831
+ (cost
1832
+ ? "cost.uploadCostUsd prices every estimated token before the included seat tokens (a real bill is at most this); cost.monthlyUsdOneSeat is one seat at the last-30-day pace. "
1833
+ : `Prices could not be read; see ${endpointsFor(ctx).apiBase}/estimate. `) +
1834
+ "Show the user the totals by month and the gone-for-good cutoff; to import, call import_history with dryRun true first " +
1835
+ `and sinceDays ${sinceDays} (its default is 30 days, so without it the import covers less than this estimate).`,
1836
+ };
1837
+ },
1838
+ },
1766
1839
  {
1767
1840
  name: "import_history",
1768
1841
  title: "Import past Claude Code / Codex sessions",
@@ -1772,6 +1845,8 @@ export const TOOLS = [
1772
1845
  "Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. " +
1773
1846
  "A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. " +
1774
1847
  "Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. " +
1848
+ "Imported tokens are billed like live usage (this month's included seat tokens first, then the per-million price from prepaid credit): when the server reports billing state, `billing` gives the run's estimated cost and whether the credit covers it, and a real import starts no session the credit cannot cover (stoppedBy budget). estimate_history prices the whole local history without a key. " +
1849
+ "Rows carry the signed-in account's identity as live rows do, shown masked in `identity`; identity false omits it. " +
1775
1850
  "content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
1776
1851
  inputSchema: obj({
1777
1852
  dryRun: { type: "boolean", description: "Summarize without sending anything (default true)." },
@@ -1780,6 +1855,7 @@ export const TOOLS = [
1780
1855
  content: { type: "string", enum: ["none", "live", "all"], description: "Text to include (default live: what the live exporters send)." },
1781
1856
  maxSessions: { type: "integer", minimum: 1, maximum: IMPORT_MAX_SESSIONS, description: `Sessions to send in this call (default ${IMPORT_DEFAULT_SESSIONS}).` },
1782
1857
  project: { type: "string", minLength: 1, maxLength: 1024, description: "Only sessions whose working directory is this path or under it." },
1858
+ identity: { type: "boolean", description: "Stamp the signed-in account's identity on imported rows, as live exporters do (default true; false omits it)." },
1783
1859
  }),
1784
1860
  async handler(args, ctx) {
1785
1861
  if (!ctx.session.hasKey())
@@ -1804,6 +1880,9 @@ export const TOOLS = [
1804
1880
  if (args.project !== undefined && (typeof args.project !== "string" || !args.project.trim() || args.project.length > 1024)) {
1805
1881
  return { ok: false, error: "bad_input", message: "project must be a path" };
1806
1882
  }
1883
+ if (args.identity !== undefined && typeof args.identity !== "boolean") {
1884
+ return { ok: false, error: "bad_input", message: "identity must be a boolean" };
1885
+ }
1807
1886
  const o = ctx.importOverrides ?? {};
1808
1887
  const now = o.nowMs ?? Date.now();
1809
1888
  const r = await runImport({
@@ -1812,6 +1891,7 @@ export const TOOLS = [
1812
1891
  source,
1813
1892
  sinceMs: Math.floor((now - sinceDays * 86_400_000) / 86_400_000) * 86_400_000,
1814
1893
  project: typeof args.project === "string" ? args.project.trim() : undefined,
1894
+ identity: resolveImportIdentity({ source, disabled: args.identity === false, ...(o.identityPaths ?? {}) }),
1815
1895
  content: resolveImportContent(content, {
1816
1896
  claudeSettings: ctx.configPathsOverride?.claude ?? CLIENTS.claude.resolveConfigPath({}),
1817
1897
  codexConfig: ctx.configPathsOverride?.codex ?? CLIENTS.codex.resolveConfigPath({}),
@@ -1840,7 +1920,7 @@ export async function callTool(name, args, ctx) {
1840
1920
  try {
1841
1921
  if (!["workspace_context", "bootstrap_workspace"].includes(name))
1842
1922
  await restoreWorkspace(ctx);
1843
- if (ctx.workspace && !["status", "workspace_context", "bootstrap_workspace", "seed_grader_config", "write_grader_config_artifact"].includes(name)) {
1923
+ if (ctx.workspace && !["status", "workspace_context", "bootstrap_workspace", "seed_grader_config", "write_grader_config_artifact", "estimate_history"].includes(name)) {
1844
1924
  if (["onboard", "write_local_config"].includes(name))
1845
1925
  throw new Error("Use bootstrap_workspace to configure this persistent workspace and its scoped client profile.");
1846
1926
  if (["authenticate", "auth_status", "get_ingest_key"].includes(name))
@@ -1,2 +1,2 @@
1
1
  export declare const MCP_SERVER_NAME = "codetelemetry";
2
- export declare const MCP_SERVER_VERSION = "0.7.0";
2
+ export declare const MCP_SERVER_VERSION = "0.8.0";
@@ -1,2 +1,2 @@
1
1
  export const MCP_SERVER_NAME = "codetelemetry";
2
- export const MCP_SERVER_VERSION = "0.7.0";
2
+ export const MCP_SERVER_VERSION = "0.8.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codetelemetry/mcp",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "CodeTelemetry MCP server \u2014 lets a coding agent onboard a user end to end: authenticate (device code), obtain an ingest key, write the Claude Code OTEL config, send a test event, and confirm telemetry landed \u2014 then search, read, interpret and compare the user's own coding sessions, plan the next one, and size tasks, plans and Linear issues from that history. The plaintext key never enters the model's context.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -98,6 +98,14 @@
98
98
  "types": "./dist/src/client/import/core.d.ts",
99
99
  "default": "./dist/src/client/import/core.js"
100
100
  },
101
+ "./client/import/estimate": {
102
+ "types": "./dist/src/client/import/estimate.d.ts",
103
+ "default": "./dist/src/client/import/estimate.js"
104
+ },
105
+ "./client/import/identity": {
106
+ "types": "./dist/src/client/import/identity.d.ts",
107
+ "default": "./dist/src/client/import/identity.js"
108
+ },
101
109
  "./client/import/ledger": {
102
110
  "types": "./dist/src/client/import/ledger.d.ts",
103
111
  "default": "./dist/src/client/import/ledger.js"
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "serverName": "codetelemetry",
3
- "serverVersion": "0.7.0",
4
- "registryHash": "eebf2611c67780abfae82ff19098d5b9cff943aebbc9fae45b60e37ccd836a61",
5
- "toolCount": 34,
3
+ "serverVersion": "0.8.0",
4
+ "registryHash": "fa9df3510d2a587d1fc17339fcca4436662e7954c2c7867d37523cffa759f0c4",
5
+ "toolCount": 35,
6
6
  "tools": [
7
7
  {
8
8
  "name": "discover_grader_checks",
@@ -551,6 +551,18 @@
551
551
  "maximum": 31536000000,
552
552
  "description": "Inclusive maximum elapsed session span in milliseconds."
553
553
  },
554
+ "start": {
555
+ "type": "integer",
556
+ "minimum": 0,
557
+ "maximum": 253402300799,
558
+ "description": "Only sessions last active at or after this time, in Unix seconds."
559
+ },
560
+ "end": {
561
+ "type": "integer",
562
+ "minimum": 0,
563
+ "maximum": 253402300799,
564
+ "description": "Only sessions last active before this time, in Unix seconds (after start)."
565
+ },
554
566
  "activity": {
555
567
  "type": "string",
556
568
  "enum": [
@@ -1364,7 +1376,7 @@
1364
1376
  },
1365
1377
  "beforePush": {
1366
1378
  "type": "boolean",
1367
- "description": "Require successful command evidence after the final edit and before pushing; subject to the backend's stricter required-command matcher validation."
1379
+ "description": "Require successful command evidence after the final edit and before pushing; the service accepts it only when matcherRule.include names the commands: one exactFingerprint equals/in condition, or all of source equals shell, executable equals/in and packageScript equals/in (each optionally with one repositoryRelativeWorkingDirectory equals condition). Broader matchers are refused."
1368
1380
  },
1369
1381
  "matcherRule": {
1370
1382
  "type": "object",
@@ -1639,7 +1651,7 @@
1639
1651
  },
1640
1652
  "beforePush": {
1641
1653
  "type": "boolean",
1642
- "description": "Require successful command evidence after the final edit and before pushing; subject to the backend's stricter required-command matcher validation."
1654
+ "description": "Require successful command evidence after the final edit and before pushing; the service accepts it only when matcherRule.include names the commands: one exactFingerprint equals/in condition, or all of source equals shell, executable equals/in and packageScript equals/in (each optionally with one repositoryRelativeWorkingDirectory equals condition). Broader matchers are refused."
1643
1655
  },
1644
1656
  "matcherRule": {
1645
1657
  "type": "object",
@@ -1892,10 +1904,36 @@
1892
1904
  "additionalProperties": false
1893
1905
  }
1894
1906
  },
1907
+ {
1908
+ "name": "estimate_history",
1909
+ "title": "Estimate past sessions before importing them",
1910
+ "description": "Use this when the user asks what importing their EXISTING local Claude Code or Codex history would cost, or how much history they have. Needs no key and sends nothing: it reads ~/.claude/projects and ~/.codex/sessions on this machine and returns sessions and tokens per source, per UTC month and per day, the oldest and newest session, and the last-30-day pace, priced with CodeTelemetry's public price list when it can be read. Imported tokens are billed like live usage: this month's included seat tokens first, then the per-million price from prepaid credit. Claude Code deletes local transcripts cleanupPeriodDays (default 30) after their last activity, so an older Claude session survives only if it was captured live or its transcript is still on disk; goneForGood says from when. Sessions already captured live are counted here but skipped by an import. To import, call import_history (dry run first).",
1911
+ "inputSchema": {
1912
+ "type": "object",
1913
+ "properties": {
1914
+ "source": {
1915
+ "type": "string",
1916
+ "enum": [
1917
+ "claude-code",
1918
+ "codex",
1919
+ "all"
1920
+ ],
1921
+ "description": "Which history to read (default all)."
1922
+ },
1923
+ "sinceDays": {
1924
+ "type": "integer",
1925
+ "minimum": 1,
1926
+ "maximum": 364,
1927
+ "description": "How many days back (default 364, the whole retained year)."
1928
+ }
1929
+ },
1930
+ "additionalProperties": false
1931
+ }
1932
+ },
1895
1933
  {
1896
1934
  "name": "import_history",
1897
1935
  "title": "Import past Claude Code / Codex sessions",
1898
- "description": "Use this when the user wants their EXISTING local Claude Code or Codex history (sessions from before CodeTelemetry was set up) to show in CodeTelemetry. It reads ~/.claude/projects and ~/.codex/sessions on this machine and sends them through the normal ingest under the session's key, tagged as imported. ALWAYS call it first with dryRun true (the default) and show the user the summary — sessions, tokens, what is skipped and the content setting — then ask before calling again with dryRun false. Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
1936
+ "description": "Use this when the user wants their EXISTING local Claude Code or Codex history (sessions from before CodeTelemetry was set up) to show in CodeTelemetry. It reads ~/.claude/projects and ~/.codex/sessions on this machine and sends them through the normal ingest under the session's key, tagged as imported. ALWAYS call it first with dryRun true (the default) and show the user the summary — sessions, tokens, what is skipped and the content setting — then ask before calling again with dryRun false. Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. Imported tokens are billed like live usage (this month's included seat tokens first, then the per-million price from prepaid credit): when the server reports billing state, `billing` gives the run's estimated cost and whether the credit covers it, and a real import starts no session the credit cannot cover (stoppedBy budget). estimate_history prices the whole local history without a key. Rows carry the signed-in account's identity as live rows do, shown masked in `identity`; identity false omits it. content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
1899
1937
  "inputSchema": {
1900
1938
  "type": "object",
1901
1939
  "properties": {
@@ -1938,6 +1976,10 @@
1938
1976
  "minLength": 1,
1939
1977
  "maxLength": 1024,
1940
1978
  "description": "Only sessions whose working directory is this path or under it."
1979
+ },
1980
+ "identity": {
1981
+ "type": "boolean",
1982
+ "description": "Stamp the signed-in account's identity on imported rows, as live exporters do (default true; false omits it)."
1941
1983
  }
1942
1984
  },
1943
1985
  "additionalProperties": false