@codetelemetry/mcp 0.3.7 → 0.3.8

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.
package/README.md CHANGED
@@ -31,7 +31,7 @@ deterministic (see [Releases & discovery](#releases--discovery)):
31
31
  ```json
32
32
  {
33
33
  "mcpServers": {
34
- "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.3.7", "codetelemetry-mcp"] }
34
+ "codetelemetry": { "command": "npx", "args": ["-y", "--package=@codetelemetry/mcp@0.3.8", "codetelemetry-mcp"] }
35
35
  }
36
36
  }
37
37
  ```
@@ -42,10 +42,10 @@ Then just ask the agent: **"Connect me to CodeTelemetry."**
42
42
 
43
43
  | Tool | What it does |
44
44
  | --- | --- |
45
- | `authenticate` | Start device-code auth; returns a URL + short code for the human to approve. |
45
+ | `authenticate` | Start device-code auth; returns a URL + short code for the human to approve. Optional `organizationId` connects one of the user's organizations; optional `workspaceUrl` picks a CodeTelemetry server (codetelemetry.com hosts only). |
46
46
  | `auth_status` | Poll the approval; on success captures the key into the session (masked-only to the model). |
47
47
  | `get_ingest_key` | Record a pasted key (fast path) or report the authenticated one — masked + hash only. |
48
- | `write_local_config` | Merge the OTEL config + key into a recognized Claude Code or Codex config path (preserves + backs up). |
48
+ | `write_local_config` | Merge the OTEL config + key into Claude Code's or Codex's config (the default, or an explicit `path` to a `settings.json`/`settings.local.json` in a `.claude` directory or a `config.toml` in a `.codex` directory); preserves + backs up. |
49
49
  | `send_test_event` | Fire one OTLP probe log with a unique id. |
50
50
  | `verify_telemetry` | Poll the connectivity check until the probe lands. |
51
51
  | `onboard` | One-shot: key → config → test → verify, returns a checklist. |
@@ -59,21 +59,49 @@ Then just ask the agent: **"Connect me to CodeTelemetry."**
59
59
  | `get_session_performance` | Measure a session timeline's fresh/cache latency, rows, bytes, and query phases without returning content. |
60
60
  | `find_similar_session_errors` | Find other personal-scope sessions with matching normalized failure signatures and report query performance. |
61
61
  | `estimate_task_size` | T-shirt size a proposed task (free-form text or a Linear-shaped issue) from the caller's own history. |
62
+ | `estimate_plan` | T-shirt size a Claude Code / Codex **plan** (plain text or ordered steps) from the caller's own history. |
62
63
  | `estimate_linear_issue` | T-shirt size an **existing Linear issue** by URL or identifier, resolved through the workspace the user already connected. |
63
64
 
64
65
  Typical agent flow: `authenticate` → (human approves) → `auth_status` →
65
66
  `onboard`. Or, if the user pastes a key: `onboard { key }`.
66
67
 
68
+ ## Organizations
69
+
70
+ Without an `organizationId`, the key goes wherever the user picks while approving:
71
+ their personal workspace or one of their organizations. To connect an
72
+ organization on purpose, pass its id, shown in parentheses next to each
73
+ organization on the approval page:
74
+
75
+ ```jsonc
76
+ // tool: authenticate
77
+ { "organizationId": "<organization id>" }
78
+ ```
79
+
80
+ The approval link then pre-selects that organization, the sign-in runs on the
81
+ scope-fenced route, and `auth_status` keeps the key only when CodeTelemetry
82
+ attests that it belongs to that organization. Otherwise it answers `wrong_scope`
83
+ (or `scope_unverified` when the organization could not be confirmed) and discards
84
+ the key. `onboard` and `verify_telemetry` repeat the check against
85
+ the connectivity endpoint. `workspaceUrl` is unrelated: it picks the CodeTelemetry
86
+ server, not an organization.
87
+
67
88
  ## Data and local changes
68
89
 
69
90
  The default setup writes only the OpenTelemetry exporter endpoint and ingest
70
- credential to the selected client's recognized config file. The MCP tool cannot
71
- choose an arbitrary URL or filesystem path: authentication uses
72
- `https://codetelemetry.com` and telemetry uses CodeTelemetry's production ingest
73
- endpoint, while configuration is limited to Claude Code's user/current-project
74
- `settings.json` or Codex's active `config.toml`. Existing config is preserved,
75
- backed up before a change, and the resulting file is made owner-readable only
76
- where the platform supports it.
91
+ credential to the selected client's config file: Claude Code's user or
92
+ current-project `settings.json`, or Codex's active `config.toml`. An explicit
93
+ `path` may name another config file of the same client, and nothing else: a
94
+ `settings.json` or `settings.local.json` inside a `.claude` directory (or
95
+ `$CLAUDE_CONFIG_DIR`), or a `config.toml` inside a `.codex` directory (or
96
+ `$CODEX_HOME`). A leading `~` is the home directory; links, network paths and
97
+ anything but a regular file are refused, and a path the host pins outranks the
98
+ model's. Authentication uses `https://codetelemetry.com` unless `authenticate` is
99
+ given a `workspaceUrl`, which must be an https URL on codetelemetry.com or one of
100
+ its subdomains and cannot override a server the MCP configuration pins. Moving to
101
+ another server drops any key from the old one, and telemetry goes to the ingest
102
+ endpoint the new server issues with its key. Existing config is preserved, backed
103
+ up before a change, and the resulting file is made owner-readable only where the
104
+ platform supports it.
77
105
 
78
106
  Two higher-sensitivity features are off by default and require separate boolean
79
107
  opt-ins:
@@ -93,6 +121,54 @@ on prompt/body telemetry, and `enrich` does not install repository hooks. A late
93
121
  run with `repositoryObservation` omitted or false removes only CodeTelemetry's
94
122
  managed hook entries and helper/state files; unrelated user hooks are preserved.
95
123
 
124
+ ## Estimating a plan
125
+
126
+ `estimate_plan` predicts the **coding-assistant token effort** of a plan from the
127
+ user's own similar past sessions — not elapsed time or human engineering hours.
128
+ The client must submit the plan content **explicitly** (the server never reads the
129
+ agent's hidden state), and the whole plan is sized as **one** unit: submitted step
130
+ boundaries are preserved in `source` for provenance but are never summed as
131
+ independent estimates. It is read-only — it never edits the plan, creates issues,
132
+ or starts work. Weak or contradictory history yields a **low-confidence** result
133
+ carrying a small calibration task rather than a falsely precise number.
134
+
135
+ **Claude Code** — after Claude drafts a plan, ask it to size that plan. Claude
136
+ passes its own plan text/steps explicitly:
137
+
138
+ ```jsonc
139
+ // tool: estimate_plan
140
+ {
141
+ "title": "Add a rate limiter to the ingest API",
142
+ "steps": [
143
+ { "title": "Token bucket", "detail": "per-tenant bucket in the ingest middleware" },
144
+ { "title": "Config", "detail": "expose the limit + window as env vars" },
145
+ "Add unit and integration tests for the limiter"
146
+ ],
147
+ "repo": "elo",
148
+ "provider": "claude",
149
+ "model": "claude-opus-4-8"
150
+ }
151
+ ```
152
+
153
+ **Codex** — the same tool from a Codex session. Pass the plan as plain text (or
154
+ steps) and set `provider: "codex"`:
155
+
156
+ ```jsonc
157
+ // tool: estimate_plan
158
+ {
159
+ "title": "Backfill Linear estimates",
160
+ "planText": "1. Read settled sessions for the window\n2. Size each by actual token usage\n3. Write the estimate + provenance back to Linear behind a confirm gate",
161
+ "repo": "elo",
162
+ "provider": "codex"
163
+ }
164
+ ```
165
+
166
+ The result carries the shared sizing schema (`estimate`: size, predicted token
167
+ range, confidence with reasons, comparable-work evidence, optional calibration
168
+ task), plus normalized `source` metadata (title, format, preserved step
169
+ boundaries, repo/project/provider/model) and a `note` restating that the number is
170
+ token effort, not time.
171
+
96
172
  ## Estimating a Linear issue
97
173
 
98
174
  `estimate_linear_issue` sizes an issue that **already exists** in Linear, so you
@@ -212,7 +288,7 @@ npm run smoke -- --tarball out.tgz --require-auth # exactly these by
212
288
  and read `server`:
213
289
 
214
290
  ```jsonc
215
- "server": { "name": "codetelemetry", "version": "0.3.7", "registryHash": "cc2fcdcc…", "toolCount": 18 }
291
+ "server": { "name": "codetelemetry", "version": "0.3.8", "registryHash": "36d8f5e3…", "toolCount": 19 }
216
292
  ```
217
293
 
218
294
  **When a long-running client sees a new tool.** `tools/list` is requested once, at
@@ -252,3 +328,7 @@ npm run test:protocol # drives the tools through a real MCP client/server pair
252
328
  npm run test:packaged # packs, launches the artifact, runs the release smoke
253
329
  npm run typecheck
254
330
  ```
331
+
332
+ `npm test`, `test:protocol` and `test:e2e` load `test/support/isolateHome.ts`, which
333
+ points `HOME`, `USERPROFILE` and `CODEX_HOME` at a throwaway directory, so a test can
334
+ never rewrite your own `~/.claude/settings.json` or Codex config.
@@ -1,4 +1,10 @@
1
- const TERMINAL_ERRORS = new Set(["expired_token", "invalid_grant", "access_denied"]);
1
+ const TERMINAL_ERRORS = new Set(["expired_token", "invalid_grant", "access_denied", "wrong_scope"]);
2
+ function tokenError(body, fallback) {
3
+ return body.state === "wrong_scope" ? "wrong_scope" : String(body.error ?? fallback);
4
+ }
5
+ function issuedIngestEndpoint(body, endpoints) {
6
+ return typeof body.ingest_endpoint === "string" && body.ingest_endpoint ? body.ingest_endpoint : endpoints.ingestEndpoint;
7
+ }
2
8
  export async function requestDeviceCode(endpoints, fetchImpl = fetch, timeoutMs = 10_000, expected) {
3
9
  const scopeFenced = !!expected && Object.keys(expected).length > 0;
4
10
  const codeUrl = scopeFenced ? endpoints.deviceScopedCodeUrl : endpoints.deviceCodeUrl;
@@ -90,11 +96,11 @@ export async function pollOnce(endpoints, deviceCode, fetchImpl = fetch, timeout
90
96
  return {
91
97
  status: "authorized",
92
98
  apiKey: String(j.api_key),
93
- ingestEndpoint: String(j.ingest_endpoint),
99
+ ingestEndpoint: issuedIngestEndpoint(j, endpoints),
94
100
  ...(scope ? { scope } : {}),
95
101
  };
96
102
  }
97
- const error = String(j.error ?? "authorization_pending");
103
+ const error = tokenError(j, "authorization_pending");
98
104
  return TERMINAL_ERRORS.has(error) ? { status: "error", error } : { status: "pending" };
99
105
  }
100
106
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -119,11 +125,11 @@ export async function pollForKey(endpoints, deviceCode, opts = {}) {
119
125
  const scope = keyScope(j.scope);
120
126
  return {
121
127
  apiKey: String(j.api_key),
122
- ingestEndpoint: String(j.ingest_endpoint),
128
+ ingestEndpoint: issuedIngestEndpoint(j, endpoints),
123
129
  ...(scope ? { scope } : {}),
124
130
  };
125
131
  }
126
- const error = String(j.error ?? (res.status >= 500 ? "server_error" : "authorization_pending"));
132
+ const error = tokenError(j, res.status >= 500 ? "server_error" : "authorization_pending");
127
133
  if (TERMINAL_ERRORS.has(error)) {
128
134
  throw new Error(`device authorization ${error}`);
129
135
  }
@@ -0,0 +1,53 @@
1
+ export declare const MAX_PLAN_TEXT = 4000;
2
+ export declare const MAX_PLAN_TITLE = 300;
3
+ export declare const MAX_PLAN_STEP_TITLE = 300;
4
+ export declare const MAX_PLAN_STEP_DETAIL = 4000;
5
+ export declare const MAX_PLAN_STEPS = 50;
6
+ export declare const MAX_PLAN_REPO = 200;
7
+ export declare const MAX_PLAN_PROJECT = 200;
8
+ export declare const MAX_PLAN_MODEL = 120;
9
+ export declare const PLAN_PROVIDERS: readonly ["claude", "codex"];
10
+ export type PlanProvider = (typeof PLAN_PROVIDERS)[number];
11
+ export type PlanStepInput = string | {
12
+ title?: string;
13
+ detail?: string;
14
+ };
15
+ export type PlanInput = {
16
+ planText?: string;
17
+ steps?: PlanStepInput[];
18
+ title?: string;
19
+ repo?: string;
20
+ project?: string;
21
+ provider?: PlanProvider;
22
+ model?: string;
23
+ };
24
+ export type PlanSourceStep = {
25
+ index: number;
26
+ title: string | null;
27
+ chars: number;
28
+ };
29
+ export type PlanSource = {
30
+ kind: "plan";
31
+ title: string | null;
32
+ format: "text" | "steps" | "text+steps";
33
+ stepCount: number;
34
+ steps: PlanSourceStep[];
35
+ repo: string | null;
36
+ project: string | null;
37
+ provider: PlanProvider | null;
38
+ model: string | null;
39
+ contentChars: number;
40
+ };
41
+ export type NormalizedPlan = {
42
+ taskText: string;
43
+ repo?: string;
44
+ source: PlanSource;
45
+ };
46
+ export type NormalizePlanResult = {
47
+ ok: true;
48
+ plan: NormalizedPlan;
49
+ } | {
50
+ ok: false;
51
+ message: string;
52
+ };
53
+ export declare function normalizePlan(raw: Record<string, unknown>): NormalizePlanResult;
@@ -0,0 +1,112 @@
1
+ export const MAX_PLAN_TEXT = 4_000;
2
+ export const MAX_PLAN_TITLE = 300;
3
+ export const MAX_PLAN_STEP_TITLE = 300;
4
+ export const MAX_PLAN_STEP_DETAIL = 4_000;
5
+ export const MAX_PLAN_STEPS = 50;
6
+ export const MAX_PLAN_REPO = 200;
7
+ export const MAX_PLAN_PROJECT = 200;
8
+ export const MAX_PLAN_MODEL = 120;
9
+ export const PLAN_PROVIDERS = ["claude", "codex"];
10
+ const bad = (message) => ({ ok: false, message });
11
+ function boundedString(value, max) {
12
+ if (value === undefined)
13
+ return undefined;
14
+ if (typeof value !== "string" || value.length > max)
15
+ return null;
16
+ return value.trim();
17
+ }
18
+ export function normalizePlan(raw) {
19
+ const planText = boundedString(raw.planText, MAX_PLAN_TEXT);
20
+ if (planText === null) {
21
+ return bad(`planText must be a string of at most ${MAX_PLAN_TEXT} characters`);
22
+ }
23
+ const title = boundedString(raw.title, MAX_PLAN_TITLE);
24
+ if (title === null)
25
+ return bad(`title must be a string of at most ${MAX_PLAN_TITLE} characters`);
26
+ const repo = boundedString(raw.repo, MAX_PLAN_REPO);
27
+ if (repo === null)
28
+ return bad(`repo must be a string of at most ${MAX_PLAN_REPO} characters`);
29
+ const project = boundedString(raw.project, MAX_PLAN_PROJECT);
30
+ if (project === null)
31
+ return bad(`project must be a string of at most ${MAX_PLAN_PROJECT} characters`);
32
+ const model = boundedString(raw.model, MAX_PLAN_MODEL);
33
+ if (model === null)
34
+ return bad(`model must be a string of at most ${MAX_PLAN_MODEL} characters`);
35
+ let provider;
36
+ if (raw.provider !== undefined) {
37
+ if (typeof raw.provider !== "string" || !PLAN_PROVIDERS.includes(raw.provider)) {
38
+ return bad(`provider must be one of ${PLAN_PROVIDERS.join(", ")}`);
39
+ }
40
+ provider = raw.provider;
41
+ }
42
+ const stepLines = [];
43
+ const sourceSteps = [];
44
+ if (raw.steps !== undefined) {
45
+ if (!Array.isArray(raw.steps))
46
+ return bad("steps must be an array");
47
+ if (raw.steps.length > MAX_PLAN_STEPS)
48
+ return bad(`steps must contain at most ${MAX_PLAN_STEPS} items`);
49
+ for (let i = 0; i < raw.steps.length; i++) {
50
+ const step = raw.steps[i];
51
+ let stepTitle;
52
+ let stepDetail;
53
+ if (typeof step === "string") {
54
+ stepDetail = step.trim();
55
+ }
56
+ else if (step !== null && typeof step === "object" && !Array.isArray(step)) {
57
+ const obj = step;
58
+ const t = boundedString(obj.title, MAX_PLAN_STEP_TITLE);
59
+ const d = boundedString(obj.detail, MAX_PLAN_STEP_DETAIL);
60
+ if (t === null)
61
+ return bad(`steps[${i}].title must be a string of at most ${MAX_PLAN_STEP_TITLE} characters`);
62
+ if (d === null)
63
+ return bad(`steps[${i}].detail must be a string of at most ${MAX_PLAN_STEP_DETAIL} characters`);
64
+ stepTitle = t || undefined;
65
+ stepDetail = d || undefined;
66
+ }
67
+ else {
68
+ return bad(`steps[${i}] must be a string or an object with title/detail`);
69
+ }
70
+ if (!stepTitle && !stepDetail) {
71
+ return bad(`steps[${i}] must have a non-empty title or detail`);
72
+ }
73
+ const label = stepTitle && stepDetail ? `${stepTitle}: ${stepDetail}` : stepTitle ?? stepDetail;
74
+ stepLines.push(`${i + 1}. ${label}`);
75
+ sourceSteps.push({
76
+ index: i + 1,
77
+ title: stepTitle ?? null,
78
+ chars: (stepTitle?.length ?? 0) + (stepDetail?.length ?? 0),
79
+ });
80
+ }
81
+ }
82
+ const hasText = !!planText;
83
+ const hasSteps = sourceSteps.length > 0;
84
+ if (!hasText && !hasSteps) {
85
+ return bad("Provide planText or at least one step to estimate.");
86
+ }
87
+ const parts = [];
88
+ if (title)
89
+ parts.push(title);
90
+ if (planText)
91
+ parts.push(planText);
92
+ if (hasSteps)
93
+ parts.push(`Plan steps:\n${stepLines.join("\n")}`);
94
+ const taskText = parts.join("\n\n");
95
+ if (taskText.length > MAX_PLAN_TEXT) {
96
+ return bad(`Assembled plan is ${taskText.length} characters; keep title, plan text, and steps under ${MAX_PLAN_TEXT} together.`);
97
+ }
98
+ const format = hasText && hasSteps ? "text+steps" : hasSteps ? "steps" : "text";
99
+ const source = {
100
+ kind: "plan",
101
+ title: title || null,
102
+ format,
103
+ stepCount: sourceSteps.length,
104
+ steps: sourceSteps,
105
+ repo: repo || null,
106
+ project: project || null,
107
+ provider: provider ?? null,
108
+ model: model || null,
109
+ contentChars: taskText.length,
110
+ };
111
+ return { ok: true, plan: { taskText, ...(repo ? { repo } : {}), source } };
112
+ }
@@ -1,3 +1,4 @@
1
+ import type { ExpectedKeyScope, KeyScope } from "./client/connectivity.ts";
1
2
  export type KeySource = "device-flow" | "pasted";
2
3
  export declare class OnboardingSession {
3
4
  #private;
@@ -8,7 +9,13 @@ export declare class OnboardingSession {
8
9
  deviceCode: string | null;
9
10
  userCode: string | null;
10
11
  lastProbeId: string | null;
12
+ pendingScope: ExpectedKeyScope | null;
13
+ deviceScopeFenced: boolean;
14
+ keyScope: KeyScope | null;
15
+ keyExpectedScope: ExpectedKeyScope | null;
16
+ serverChosenByModel: boolean;
11
17
  setKey(plaintext: string, source: KeySource, ingestEndpoint?: string): void;
18
+ forgetKey(): void;
12
19
  hasKey(): boolean;
13
20
  useKey(): string;
14
21
  view(): {
@@ -8,6 +8,11 @@ export class OnboardingSession {
8
8
  deviceCode = null;
9
9
  userCode = null;
10
10
  lastProbeId = null;
11
+ pendingScope = null;
12
+ deviceScopeFenced = false;
13
+ keyScope = null;
14
+ keyExpectedScope = null;
15
+ serverChosenByModel = false;
11
16
  setKey(plaintext, source, ingestEndpoint) {
12
17
  if (!looksLikeKey(plaintext))
13
18
  throw new Error("not a valid CodeTelemetry ingest key (expected cot_…)");
@@ -16,6 +21,23 @@ export class OnboardingSession {
16
21
  this.source = source;
17
22
  if (ingestEndpoint)
18
23
  this.ingestEndpoint = ingestEndpoint;
24
+ this.keyScope = null;
25
+ this.keyExpectedScope = null;
26
+ if (source === "pasted") {
27
+ this.pendingScope = null;
28
+ this.deviceCode = null;
29
+ this.userCode = null;
30
+ this.deviceScopeFenced = false;
31
+ }
32
+ }
33
+ forgetKey() {
34
+ this.#key = null;
35
+ this.keyHash = null;
36
+ this.source = null;
37
+ this.keyScope = null;
38
+ this.keyExpectedScope = null;
39
+ this.ingestEndpoint = null;
40
+ this.lastProbeId = null;
19
41
  }
20
42
  hasKey() {
21
43
  return this.#key !== null;
@@ -40,5 +62,10 @@ export class OnboardingSession {
40
62
  this.deviceCode = null;
41
63
  this.userCode = null;
42
64
  this.lastProbeId = null;
65
+ this.pendingScope = null;
66
+ this.deviceScopeFenced = false;
67
+ this.keyScope = null;
68
+ this.keyExpectedScope = null;
69
+ this.serverChosenByModel = false;
43
70
  }
44
71
  }
@@ -1,4 +1,6 @@
1
+ import path from "node:path";
1
2
  import { type FetchLike } from "./client/otlp.ts";
3
+ import { type OnboardClient } from "./client/onboard.ts";
2
4
  import { OnboardingSession } from "./session.ts";
3
5
  export type ToolContext = {
4
6
  session: OnboardingSession;
@@ -22,6 +24,14 @@ export type ToolDef = {
22
24
  inputSchema: Record<string, unknown>;
23
25
  handler: (args: Record<string, unknown>, ctx: ToolContext) => Promise<ToolResult>;
24
26
  };
27
+ type RequestedPath = {
28
+ ok: true;
29
+ path: string | undefined;
30
+ } | {
31
+ ok: false;
32
+ message: string;
33
+ };
34
+ export declare function requestedConfigPath(client: OnboardClient, args: Record<string, unknown>, pathImpl?: path.PlatformPath): RequestedPath;
25
35
  export declare const ISSUE_SIZING_ERRORS: ReadonlySet<string>;
26
36
  export declare const INTERPRET_SESSION_STATES: ReadonlySet<string>;
27
37
  export declare const COMPARE_SESSION_STATES: ReadonlySet<string>;
@@ -30,3 +40,4 @@ export declare const READ_SESSION_EVENTS_STATES: ReadonlySet<string>;
30
40
  export declare const TOOLS: ToolDef[];
31
41
  export declare const TOOLS_BY_NAME: Record<string, ToolDef>;
32
42
  export declare function callTool(name: string, args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
43
+ export {};
package/dist/src/tools.js CHANGED
@@ -1,9 +1,13 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
1
4
  import { resolveEndpoints, resolveSettingsPath, } from "./client/config.js";
2
5
  import { writeSettings, readSettingsSummary, } from "./client/settings.js";
3
6
  import { resolveCodexConfigPath, writeCodexConfig, readCodexSummary, } from "./client/codexConfig.js";
4
7
  import { sendTestEvent, } from "./client/otlp.js";
5
- import { confirmLanded, } from "./client/connectivity.js";
8
+ import { confirmLanded, verifyScope, } from "./client/connectivity.js";
6
9
  import { getCostSignal, getSessionPerformance, findSimilarSessionErrors, searchCodingSessions, SESSION_SEARCH_REQUEST_TIMEOUT_MS, estimateTaskSize, estimateLinearIssue, interpretSession, readSessionEvents, compareSessions, planNextSession, } from "./client/agent.js";
10
+ import { normalizePlan, PLAN_PROVIDERS, MAX_PLAN_TEXT, MAX_PLAN_STEPS, } from "./client/plan.js";
7
11
  import { requestDeviceCode, pollOnce, } from "./client/deviceClient.js";
8
12
  import { onboard as onboardCore, } from "./client/onboard.js";
9
13
  import { looksLikeKey, scrub, } from "./client/keys.js";
@@ -47,15 +51,126 @@ const REPOSITORY_OBSERVATION_PROP = {
47
51
  type: "boolean",
48
52
  description: "Install repository-observation hooks (default false). The hooks send the absolute repository root and working-directory paths, repository name, a hashed repository id, session id, and hook event to CodeTelemetry when a session starts/resumes or its workspace changes.",
49
53
  };
50
- function configPathFor(client, args, ctx) {
54
+ const CLAUDE_CONFIG_FILES = new Set(["settings.json", "settings.local.json"]);
55
+ const CODEX_CONFIG_FILES = new Set(["config.toml"]);
56
+ const MAX_CONFIG_PATH = 1024;
57
+ const MAX_CONFIG_BYTES = 1024 * 1024;
58
+ const PATH_PROP = {
59
+ type: "string",
60
+ minLength: 1,
61
+ maxLength: MAX_CONFIG_PATH,
62
+ description: "Explicit config file, overriding scope and the Codex default: a settings.json or settings.local.json inside a .claude directory (or $CLAUDE_CONFIG_DIR), or with client \"codex\" a config.toml inside a .codex directory (or $CODEX_HOME). A leading ~ is the home directory. Links, network paths and anything but a regular file are refused.",
63
+ };
64
+ export function requestedConfigPath(client, args, pathImpl = path) {
65
+ if (args.path === undefined)
66
+ return { ok: true, path: undefined };
67
+ if (typeof args.path !== "string" || !args.path.trim() || args.path.length > MAX_CONFIG_PATH) {
68
+ return { ok: false, message: `path must be a non-empty string of at most ${MAX_CONFIG_PATH} characters.` };
69
+ }
70
+ const raw = args.path.trim();
71
+ const resolved = pathImpl.resolve(raw === "~" || raw.startsWith("~/") ? pathImpl.join(os.homedir(), raw.slice(1)) : raw);
72
+ if (resolved.startsWith("\\\\")) {
73
+ return { ok: false, message: "path must be a local file, not a network or device path." };
74
+ }
75
+ const dir = pathImpl.dirname(resolved);
76
+ const codex = client === "codex";
77
+ const configDir = codex ? process.env.CODEX_HOME : process.env.CLAUDE_CONFIG_DIR;
78
+ const inClientDir = pathImpl.basename(dir) === (codex ? ".codex" : ".claude")
79
+ || (!!configDir && pathImpl.resolve(configDir) === dir);
80
+ if (!(codex ? CODEX_CONFIG_FILES : CLAUDE_CONFIG_FILES).has(pathImpl.basename(resolved)) || !inClientDir) {
81
+ return {
82
+ ok: false,
83
+ message: codex
84
+ ? "path must name a config.toml inside a .codex directory (or $CODEX_HOME)."
85
+ : "path must name a settings.json or settings.local.json inside a .claude directory (or $CLAUDE_CONFIG_DIR).",
86
+ };
87
+ }
88
+ let stat;
89
+ try {
90
+ stat = fs.lstatSync(resolved);
91
+ }
92
+ catch {
93
+ stat = undefined;
94
+ }
95
+ if (stat && !stat.isFile()) {
96
+ return { ok: false, message: "path must be a regular file, not a link, directory or device." };
97
+ }
98
+ if (stat && stat.size > MAX_CONFIG_BYTES) {
99
+ return { ok: false, message: `path must be a config file of at most ${MAX_CONFIG_BYTES} bytes.` };
100
+ }
101
+ return { ok: true, path: resolved };
102
+ }
103
+ function configPathFor(client, args, ctx, requested) {
51
104
  if (client === "codex") {
52
- return resolveCodexConfigPath({ path: ctx.configPathsOverride?.codex });
105
+ return resolveCodexConfigPath({ path: ctx.configPathsOverride?.codex ?? requested });
53
106
  }
54
107
  return resolveSettingsPath({
55
108
  scope: args.scope === "project" ? "project" : "user",
56
- path: ctx.configPathsOverride?.claude,
109
+ path: ctx.configPathsOverride?.claude ?? requested,
57
110
  });
58
111
  }
112
+ const MAX_WORKSPACE_URL = 2048;
113
+ const MAX_ORGANIZATION_ID = 256;
114
+ function recognizedWorkspaceOrigin(value) {
115
+ let url;
116
+ try {
117
+ url = new URL(value.trim());
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ if (url.protocol !== "https:" || url.username || url.password)
123
+ return null;
124
+ const host = url.hostname.toLowerCase();
125
+ if (host !== "codetelemetry.com" && !host.endsWith(".codetelemetry.com"))
126
+ return null;
127
+ return url.origin;
128
+ }
129
+ function originOf(value) {
130
+ try {
131
+ return new URL(value).origin;
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ }
137
+ function scopeMatches(expected, attested) {
138
+ return (expected.tenantId === undefined || expected.tenantId === attested.tenantId)
139
+ && (expected.teamId === undefined || expected.teamId === attested.teamId)
140
+ && (expected.billingAccountId === undefined || expected.billingAccountId === attested.billingAccountId);
141
+ }
142
+ async function scopeCheck(ctx, key, expected, attested) {
143
+ if (attested)
144
+ return scopeMatches(expected, attested) ? "match" : "mismatch";
145
+ try {
146
+ const checked = await verifyScope({
147
+ key,
148
+ connectivityUrl: endpointsFor(ctx).connectivityUrl,
149
+ fetchImpl: ctx.fetchImpl,
150
+ expected,
151
+ });
152
+ if (checked.state === "scope_verified" || checked.state === "budget_exhausted")
153
+ return "match";
154
+ return checked.state === "wrong_scope" ? "mismatch" : "unverified";
155
+ }
156
+ catch {
157
+ return "unverified";
158
+ }
159
+ }
160
+ function endAuthorization(ctx) {
161
+ ctx.session.deviceCode = null;
162
+ ctx.session.userCode = null;
163
+ ctx.session.deviceScopeFenced = false;
164
+ ctx.session.pendingScope = null;
165
+ }
166
+ function wrongScope(expected) {
167
+ return {
168
+ ok: false,
169
+ status: "wrong_scope",
170
+ error: "wrong_scope",
171
+ message: `The approved key is not for organization ${expected.teamId}, so it was not kept. Call authenticate again and approve it for that organization.`,
172
+ };
173
+ }
59
174
  const MAX_ISSUE_REFERENCE = 512;
60
175
  export const ISSUE_SIZING_ERRORS = new Set([
61
176
  "no_connected_workspace",
@@ -227,19 +342,72 @@ export const TOOLS = [
227
342
  {
228
343
  name: "authenticate",
229
344
  title: "Authenticate (device code)",
230
- description: "Begin device-code authentication. Returns a verification URL and a short user code; show them to the human and ask them to approve in a browser, then call auth_status. No password or browser automation is needed.",
231
- inputSchema: obj(),
232
- async handler(_args, ctx) {
233
- const code = await requestDeviceCode(endpointsFor(ctx), ctx.fetchImpl);
345
+ description: "Begin device-code authentication. Returns a verification URL and a short user code; show them to the human and ask them to approve in a browser, then call auth_status. No password or browser automation is needed. Pass organizationId to connect one of the user's organizations instead of their personal workspace.",
346
+ inputSchema: obj({
347
+ organizationId: {
348
+ type: "string",
349
+ minLength: 1,
350
+ maxLength: MAX_ORGANIZATION_ID,
351
+ description: "Optional organization id. The approval page pre-selects that organization, and auth_status keeps only a key issued to it. Omit it for the personal workspace, or to let the user choose while approving.",
352
+ },
353
+ workspaceUrl: {
354
+ type: "string",
355
+ minLength: 1,
356
+ maxLength: MAX_WORKSPACE_URL,
357
+ description: "Optional CodeTelemetry server to sign in to (default https://codetelemetry.com). Only https URLs on codetelemetry.com or its subdomains are accepted. It picks the server, not an organization.",
358
+ },
359
+ }),
360
+ async handler(args, ctx) {
361
+ let organizationId;
362
+ if (args.organizationId !== undefined) {
363
+ const value = typeof args.organizationId === "string" ? args.organizationId.trim() : "";
364
+ if (!value || value.length > MAX_ORGANIZATION_ID) {
365
+ return { ok: false, error: "bad_input", message: `organizationId must be a non-empty string of at most ${MAX_ORGANIZATION_ID} characters.` };
366
+ }
367
+ organizationId = value;
368
+ }
369
+ let origin = null;
370
+ if (args.workspaceUrl !== undefined) {
371
+ origin = typeof args.workspaceUrl === "string" && args.workspaceUrl.length <= MAX_WORKSPACE_URL
372
+ ? recognizedWorkspaceOrigin(args.workspaceUrl)
373
+ : null;
374
+ if (!origin) {
375
+ return { ok: false, error: "bad_input", message: "workspaceUrl must be an https URL on codetelemetry.com or one of its subdomains." };
376
+ }
377
+ const pinned = ctx.endpointsOverride?.apiBase || process.env.CODETELEMETRY_API_BASE;
378
+ if (pinned && originOf(pinned) !== origin) {
379
+ return { ok: false, error: "bad_input", message: "This MCP server's configuration pins the CodeTelemetry server, so workspaceUrl cannot change it." };
380
+ }
381
+ }
382
+ const current = endpointsFor(ctx);
383
+ const switching = origin !== null && origin !== originOf(current.apiBase);
384
+ const endpoints = switching
385
+ ? resolveEndpoints({ apiBase: origin, ingestEndpoint: ctx.endpointsOverride?.ingestEndpoint })
386
+ : current;
387
+ const expected = organizationId ? { teamId: organizationId } : undefined;
388
+ const code = await requestDeviceCode(endpoints, ctx.fetchImpl, undefined, expected);
389
+ if (origin !== null) {
390
+ if (switching)
391
+ ctx.session.forgetKey();
392
+ ctx.session.apiBase = origin;
393
+ ctx.session.serverChosenByModel = true;
394
+ }
234
395
  ctx.session.deviceCode = code.deviceCode;
235
396
  ctx.session.userCode = code.userCode;
397
+ ctx.session.deviceScopeFenced = code.scopeFenced;
398
+ ctx.session.pendingScope = expected ?? null;
399
+ const verificationUriComplete = `${code.verificationUri}?code=${encodeURIComponent(code.userCode)}` +
400
+ (organizationId ? `&teamId=${encodeURIComponent(organizationId)}` : "") +
401
+ (code.scopeFenced ? "&scope=v1" : "");
236
402
  return {
237
403
  ok: true,
238
404
  action: "authorize",
239
405
  verificationUri: code.verificationUri,
406
+ verificationUriComplete,
240
407
  userCode: code.userCode,
241
408
  expiresInSec: code.expiresIn,
242
- message: `Ask the user to open ${code.verificationUri} and approve code ${code.userCode}, then call auth_status.`,
409
+ ...(organizationId ? { organizationId } : {}),
410
+ message: `Ask the user to open ${verificationUriComplete} and approve code ${code.userCode}${organizationId ? ` for organization ${organizationId}` : ""}, then call auth_status.`,
243
411
  };
244
412
  },
245
413
  },
@@ -249,17 +417,63 @@ export const TOOLS = [
249
417
  description: "Poll the pending device authorization once. Returns 'pending' until the user approves, then 'authorized' (the ingest key is captured into the session — its plaintext is never returned).",
250
418
  inputSchema: obj(),
251
419
  async handler(_args, ctx) {
252
- if (!ctx.session.deviceCode)
420
+ const pending = {
421
+ deviceCode: ctx.session.deviceCode,
422
+ scopeFenced: ctx.session.deviceScopeFenced,
423
+ expected: ctx.session.pendingScope,
424
+ };
425
+ if (!pending.deviceCode)
253
426
  return { ok: false, status: "no_pending_auth", message: "Call authenticate first." };
254
- const r = await pollOnce(endpointsFor(ctx), ctx.session.deviceCode, ctx.fetchImpl);
255
- if (r.status === "authorized") {
256
- ctx.session.setKey(r.apiKey, "device-flow", r.ingestEndpoint);
257
- ctx.session.deviceCode = null;
258
- return { ok: true, status: "authorized", key: { masked: ctx.session.view().masked, keyHash: ctx.session.keyHash } };
259
- }
427
+ const superseded = () => ctx.session.deviceCode !== pending.deviceCode;
428
+ const SUPERSEDED = { ok: false, status: "superseded", message: "A newer authorization or key replaced this one; nothing was kept." };
429
+ const r = await pollOnce(endpointsFor(ctx), pending.deviceCode, ctx.fetchImpl, undefined, {
430
+ scopeFenced: pending.scopeFenced,
431
+ });
432
+ if (superseded())
433
+ return SUPERSEDED;
260
434
  if (r.status === "pending")
261
435
  return { ok: true, status: "pending", message: "Not approved yet — ask the user to finish, then call auth_status again." };
262
- return { ok: false, status: "error", error: r.error };
436
+ if (r.status === "error") {
437
+ endAuthorization(ctx);
438
+ return r.error === "wrong_scope" && pending.expected
439
+ ? wrongScope(pending.expected)
440
+ : { ok: false, status: "error", error: r.error };
441
+ }
442
+ if (ctx.session.serverChosenByModel && recognizedWorkspaceOrigin(r.ingestEndpoint) === null) {
443
+ endAuthorization(ctx);
444
+ return {
445
+ ok: false,
446
+ status: "error",
447
+ error: "untrusted_ingest_endpoint",
448
+ message: "The server issued an ingest endpoint outside codetelemetry.com, so the key was not kept.",
449
+ };
450
+ }
451
+ if (pending.expected) {
452
+ const check = await scopeCheck(ctx, r.apiKey, pending.expected, r.scope);
453
+ if (superseded())
454
+ return SUPERSEDED;
455
+ if (check !== "match") {
456
+ endAuthorization(ctx);
457
+ return check === "mismatch"
458
+ ? wrongScope(pending.expected)
459
+ : {
460
+ ok: false,
461
+ status: "scope_unverified",
462
+ error: "scope_unverified",
463
+ message: "CodeTelemetry could not confirm the key's organization, so it was not kept. Call authenticate again.",
464
+ };
465
+ }
466
+ }
467
+ ctx.session.setKey(r.apiKey, "device-flow", r.ingestEndpoint);
468
+ ctx.session.keyScope = r.scope ?? null;
469
+ ctx.session.keyExpectedScope = pending.expected;
470
+ endAuthorization(ctx);
471
+ return {
472
+ ok: true,
473
+ status: "authorized",
474
+ key: { masked: ctx.session.view().masked, keyHash: ctx.session.keyHash },
475
+ ...(r.scope ? { organizationId: r.scope.teamId } : {}),
476
+ };
263
477
  },
264
478
  },
265
479
  {
@@ -282,10 +496,11 @@ export const TOOLS = [
282
496
  {
283
497
  name: "write_local_config",
284
498
  title: "Write local OTEL config (Claude Code or Codex)",
285
- description: "Write the OpenTelemetry exporter config (and the ingest key) into a recognized local client config — Claude Code's user or current-project settings.json, or Codex's active ~/.codex/config.toml (`client: \"codex\"`). Preserves existing settings and backs up the file first. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns the path and the KEYS written (never values).",
499
+ description: "Write the OpenTelemetry exporter config (and the ingest key) into a local client config — Claude Code's user or current-project settings.json, Codex's active ~/.codex/config.toml (`client: \"codex\"`), or an explicit `path` to another settings.json, settings.local.json or config.toml. Preserves existing settings and backs up the file first. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns the path and the KEYS written (never values).",
286
500
  inputSchema: obj({
287
501
  client: CLIENT_PROP,
288
502
  scope: { type: "string", enum: ["user", "project"], description: "Claude only: user → ~/.claude/settings.json (default); project → ./.claude/settings.json." },
503
+ path: PATH_PROP,
289
504
  enrich: ENRICH_PROP,
290
505
  repositoryObservation: REPOSITORY_OBSERVATION_PROP,
291
506
  }),
@@ -297,18 +512,21 @@ export const TOOLS = [
297
512
  return { ok: false, error: "bad_input", message: `${invalidOptIn} must be a boolean.` };
298
513
  }
299
514
  const client = pickClient(args);
515
+ const requested = requestedConfigPath(client, args);
516
+ if (!requested.ok)
517
+ return { ok: false, error: "bad_input", message: requested.message };
300
518
  const r = client === "codex"
301
519
  ? writeCodexConfig({
302
520
  key: ctx.session.useKey(),
303
521
  ingestEndpoint: endpointsFor(ctx).ingestEndpoint,
304
- configPath: configPathFor(client, args, ctx),
522
+ configPath: configPathFor(client, args, ctx, requested.path),
305
523
  enrich: args.enrich === true,
306
524
  repositoryObservation: args.repositoryObservation === true,
307
525
  })
308
526
  : writeSettings({
309
527
  key: ctx.session.useKey(),
310
528
  ingestEndpoint: endpointsFor(ctx).ingestEndpoint,
311
- settingsPath: configPathFor(client, args, ctx),
529
+ settingsPath: configPathFor(client, args, ctx, requested.path),
312
530
  enrich: args.enrich === true,
313
531
  repositoryObservation: args.repositoryObservation === true,
314
532
  });
@@ -344,18 +562,20 @@ export const TOOLS = [
344
562
  probeId: ctx.session.lastProbeId,
345
563
  timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : undefined,
346
564
  fetchImpl: ctx.fetchImpl,
565
+ ...(ctx.session.keyExpectedScope ? { expected: ctx.session.keyExpectedScope } : {}),
347
566
  });
348
- return { ok: r.landed, landed: r.landed, elapsedMs: r.elapsedMs, polls: r.polls };
567
+ return { ok: r.landed, landed: r.landed, state: r.state, elapsedMs: r.elapsedMs, polls: r.polls };
349
568
  },
350
569
  },
351
570
  {
352
571
  name: "onboard",
353
572
  title: "Onboard (one shot)",
354
- description: "Do the whole onboarding in one call: use the session key (or a `key` you pass), write a recognized local client config, send a test event, and confirm it landed. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns a step-by-step checklist. Run authenticate + auth_status first if you don't already have a key.",
573
+ description: "Do the whole onboarding in one call: use the session key (or a `key` you pass), write a local client config (the recognized default, or an explicit settings.json, settings.local.json or config.toml `path`), send a test event, and confirm it landed. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns a step-by-step checklist. Run authenticate + auth_status first if you don't already have a key.",
355
574
  inputSchema: obj({
356
575
  key: { type: "string", description: "A cot_… ingest key (optional if already authenticated)." },
357
576
  client: CLIENT_PROP,
358
577
  scope: { type: "string", enum: ["user", "project"], description: "Claude only: which settings.json to write (default user)." },
578
+ path: PATH_PROP,
359
579
  enrich: ENRICH_PROP,
360
580
  repositoryObservation: REPOSITORY_OBSERVATION_PROP,
361
581
  timeoutMs: { type: "number", description: "Verify timeout (default 30000)." },
@@ -365,6 +585,10 @@ export const TOOLS = [
365
585
  if (invalidOptIn) {
366
586
  return { ok: false, error: "bad_input", message: `${invalidOptIn} must be a boolean.` };
367
587
  }
588
+ const client = pickClient(args);
589
+ const requested = requestedConfigPath(client, args);
590
+ if (!requested.ok)
591
+ return { ok: false, error: "bad_input", message: requested.message };
368
592
  if (typeof args.key === "string" && args.key) {
369
593
  if (!looksLikeKey(args.key))
370
594
  return { ok: false, error: "bad_key", message: "That doesn't look like a cot_… ingest key." };
@@ -374,20 +598,21 @@ export const TOOLS = [
374
598
  return NO_KEY;
375
599
  const result = await onboardCore({
376
600
  key: ctx.session.useKey(),
377
- client: pickClient(args),
601
+ client,
378
602
  endpoints: {
379
603
  apiBase: ctx.session.apiBase ?? ctx.endpointsOverride?.apiBase,
380
604
  ingestEndpoint: ctx.session.ingestEndpoint ?? ctx.endpointsOverride?.ingestEndpoint,
381
605
  },
382
606
  settings: {
383
607
  scope: args.scope === "project" ? "project" : "user",
384
- path: pickClient(args) === "codex"
608
+ path: (client === "codex"
385
609
  ? ctx.configPathsOverride?.codex
386
- : ctx.configPathsOverride?.claude,
610
+ : ctx.configPathsOverride?.claude) ?? requested.path,
387
611
  enrich: args.enrich === true,
388
612
  repositoryObservation: args.repositoryObservation === true,
389
613
  },
390
614
  verifyTimeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : undefined,
615
+ ...(ctx.session.keyExpectedScope ? { expectedScope: ctx.session.keyExpectedScope } : {}),
391
616
  fetchImpl: ctx.fetchImpl,
392
617
  });
393
618
  if (result.test?.probeId)
@@ -405,14 +630,18 @@ export const TOOLS = [
405
630
  {
406
631
  name: "status",
407
632
  title: "Onboarding status",
408
- description: "Read-only diagnostics for a recognized client config: whether a key is held (masked), whether Claude Code's user/current-project settings.json or Codex's active ~/.codex/config.toml has the OTEL config, the resolved endpoints, any pending authorization, and `server` — the MCP build and tool-inventory hash. No secrets.",
633
+ description: "Read-only diagnostics for a client config (the recognized default, or an explicit settings.json, settings.local.json or config.toml `path`): whether a key is held (masked), whether that config has the OTEL settings, the organization requested and attested, the resolved endpoints, any pending authorization, and `server` — the MCP build and tool-inventory hash. No secrets.",
409
634
  inputSchema: obj({
410
635
  client: CLIENT_PROP,
411
636
  scope: { type: "string", enum: ["user", "project"], description: "Claude only: which settings.json to inspect (default user)." },
637
+ path: PATH_PROP,
412
638
  }),
413
639
  async handler(args, ctx) {
414
640
  const client = pickClient(args);
415
- const settingsPath = configPathFor(client, args, ctx);
641
+ const requested = requestedConfigPath(client, args);
642
+ if (!requested.ok)
643
+ return { ok: false, error: "bad_input", message: requested.message };
644
+ const settingsPath = configPathFor(client, args, ctx, requested.path);
416
645
  const summary = client === "codex" ? readCodexSummary(settingsPath) : readSettingsSummary(settingsPath);
417
646
  const ep = endpointsFor(ctx);
418
647
  return {
@@ -420,6 +649,10 @@ export const TOOLS = [
420
649
  server: registryIdentity(TOOLS),
421
650
  auth: ctx.session.view(),
422
651
  pendingAuth: !!ctx.session.deviceCode,
652
+ organization: {
653
+ requested: (ctx.session.pendingScope ?? ctx.session.keyExpectedScope)?.teamId ?? null,
654
+ key: ctx.session.keyScope ? (ctx.session.keyScope.teamId ?? "personal") : null,
655
+ },
423
656
  lastProbeId: ctx.session.lastProbeId,
424
657
  settings: { path: settingsPath, ...summary },
425
658
  endpoints: { apiBase: ep.apiBase, ingestEndpoint: ep.ingestEndpoint },
@@ -873,6 +1106,91 @@ export const TOOLS = [
873
1106
  return { ok: true, estimate: r.estimate, performance: r.performance };
874
1107
  },
875
1108
  },
1109
+ {
1110
+ name: "estimate_plan",
1111
+ title: "T-shirt size a Claude Code / Codex plan",
1112
+ description: "Estimate the effort of a plan a coding assistant proposed — t-shirt size, predicted token range, and confidence — from YOUR similar past coding sessions. Submit the plan content explicitly as `planText` and/or ordered `steps`; the server cannot read the agent's hidden state, so whatever you don't pass isn't sized. The plan is sized as ONE unit: submitted step boundaries are preserved in `source` for provenance, but the estimate is never the sum of independently sized steps. " +
1113
+ "The number predicts CODING-ASSISTANT TOKEN EFFORT, not elapsed time or human engineering hours. When the matched history is weak or contradictory the result is low confidence and carries a small calibration task instead of a falsely precise number. Read-only: it never edits the plan, creates issues, or starts work.",
1114
+ inputSchema: obj({
1115
+ planText: { type: "string", minLength: 1, maxLength: MAX_PLAN_TEXT, description: "The plan as plain text. Combined with `steps` when both are given." },
1116
+ steps: {
1117
+ type: "array",
1118
+ maxItems: MAX_PLAN_STEPS,
1119
+ description: "Ordered plan steps. Each item is a string (the step's detail) or an object { title?, detail? }. Order is preserved in the result's source metadata.",
1120
+ items: {
1121
+ oneOf: [
1122
+ { type: "string", minLength: 1, maxLength: 4000 },
1123
+ {
1124
+ type: "object",
1125
+ properties: {
1126
+ title: { type: "string", maxLength: 300 },
1127
+ detail: { type: "string", maxLength: 4000 },
1128
+ },
1129
+ additionalProperties: false,
1130
+ },
1131
+ ],
1132
+ },
1133
+ },
1134
+ title: { type: "string", maxLength: 300, description: "Optional plan title, used as the leading line of the sized text." },
1135
+ repo: { type: "string", maxLength: 200, description: "Repo the work will land in, when known. Selects that repo's calibrated ladder if one exists." },
1136
+ project: { type: "string", maxLength: 200, description: "Optional project/product grouping. Recorded as context; does not change the estimate." },
1137
+ provider: { type: "string", enum: [...PLAN_PROVIDERS], description: "Which coding assistant produced the plan (claude or codex). Recorded as context; does not change the estimate." },
1138
+ model: { type: "string", maxLength: 120, description: "Model id the caller knows produced the plan. Recorded as context; does not change the estimate." },
1139
+ lookbackDays: { type: "integer", minimum: 1, maximum: 365, description: "History window to size against (default 90 days)." },
1140
+ limit: { type: "integer", minimum: 1, maximum: 5000, description: "Maximum historical sessions to load (default 1000)." },
1141
+ }),
1142
+ async handler(args, ctx) {
1143
+ if (!ctx.session.hasKey())
1144
+ return NO_KEY;
1145
+ for (const [name, max] of [["lookbackDays", 365], ["limit", 5_000]]) {
1146
+ const value = args[name];
1147
+ if (value !== undefined &&
1148
+ (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max)) {
1149
+ return { ok: false, error: "bad_input", message: `${name} must be an integer from 1 to ${max}` };
1150
+ }
1151
+ }
1152
+ const normalized = normalizePlan(args);
1153
+ if (!normalized.ok) {
1154
+ return { ok: false, error: "bad_input", message: normalized.message };
1155
+ }
1156
+ const { taskText, repo, source } = normalized.plan;
1157
+ const r = await estimateTaskSize({
1158
+ key: ctx.session.useKey(),
1159
+ url: endpointsFor(ctx).agentTaskSizeUrl,
1160
+ taskText,
1161
+ repo,
1162
+ lookbackDays: typeof args.lookbackDays === "number" ? args.lookbackDays : undefined,
1163
+ limit: typeof args.limit === "number" ? args.limit : undefined,
1164
+ fetchImpl: ctx.fetchImpl,
1165
+ timeoutMs: 60_000,
1166
+ });
1167
+ if (!r.ok) {
1168
+ if (r.error === "read_timeout") {
1169
+ return {
1170
+ ok: false,
1171
+ error: "read_timeout",
1172
+ message: r.message ?? "Plan sizing read timed out; retry with fewer lookbackDays.",
1173
+ };
1174
+ }
1175
+ return {
1176
+ ok: false,
1177
+ error: "read_failed",
1178
+ message: r.httpStatus === 401
1179
+ ? "ingest key invalid or revoked"
1180
+ : r.httpStatus === 429
1181
+ ? "task sizing read rate limit exceeded"
1182
+ : r.message ?? r.error ?? `plan sizing read returned HTTP ${r.httpStatus}`,
1183
+ };
1184
+ }
1185
+ return {
1186
+ ok: true,
1187
+ estimate: r.estimate,
1188
+ source,
1189
+ note: "Predicts coding-assistant token effort from your own history — not elapsed time or human engineering hours. The whole plan is sized as one unit; step boundaries in `source` are provenance, not independently summed estimates.",
1190
+ performance: r.performance,
1191
+ };
1192
+ },
1193
+ },
876
1194
  {
877
1195
  name: "estimate_linear_issue",
878
1196
  title: "T-shirt size an existing Linear issue",
@@ -1,2 +1,2 @@
1
1
  export declare const MCP_SERVER_NAME = "codetelemetry";
2
- export declare const MCP_SERVER_VERSION = "0.3.7";
2
+ export declare const MCP_SERVER_VERSION = "0.3.8";
@@ -1,2 +1,2 @@
1
1
  export const MCP_SERVER_NAME = "codetelemetry";
2
- export const MCP_SERVER_VERSION = "0.3.7";
2
+ export const MCP_SERVER_VERSION = "0.3.8";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codetelemetry/mcp",
3
- "version": "0.3.7",
4
- "description": "CodeTelemetry MCP server — 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 — then search, read, interpret and compare the user's own coding sessions, plan the next one, and size tasks and Linear issues from that history. The plaintext key never enters the model's context.",
3
+ "version": "0.3.8",
4
+ "description": "CodeTelemetry MCP server — 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 — 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",
7
7
  "homepage": "https://codetelemetry.com/docs/onboarding/mcp-server",
@@ -30,9 +30,9 @@
30
30
  },
31
31
  "scripts": {
32
32
  "build": "node scripts/cleanDist.ts && tsc -p tsconfig.build.json",
33
- "test": "node --test test/tools.test.ts test/cost.test.ts test/performance.test.ts test/taskSize.test.ts test/estimateLinearIssue.test.ts test/manifest.test.ts test/clientEdgeCases.test.ts",
34
- "test:protocol": "node --test test/protocol.smoke.ts",
35
- "test:e2e": "node test/e2e.smoke.ts",
33
+ "test": "node --import ./test/support/isolateHome.ts --test test/tools.test.ts test/cost.test.ts test/performance.test.ts test/taskSize.test.ts test/estimatePlan.test.ts test/estimateLinearIssue.test.ts test/manifest.test.ts test/clientEdgeCases.test.ts",
34
+ "test:protocol": "node --import ./test/support/isolateHome.ts --test test/protocol.smoke.ts",
35
+ "test:e2e": "node --import ./test/support/isolateHome.ts test/e2e.smoke.ts",
36
36
  "test:packaged": "node --test test/packaged.smoke.ts",
37
37
  "manifest:write": "node scripts/writeManifest.ts",
38
38
  "verify:registry": "node scripts/verifyRegistry.ts",
@@ -1,16 +1,29 @@
1
1
  {
2
2
  "serverName": "codetelemetry",
3
- "serverVersion": "0.3.7",
4
- "registryHash": "cc2fcdcc98cc915f0d8c18fd63148563db133b9b3c3dc1d271032ed24f570b84",
5
- "toolCount": 18,
3
+ "serverVersion": "0.3.8",
4
+ "registryHash": "36d8f5e325b27ecde3006546f4270ac689e66761bfdabe82e5cae2018c58b18e",
5
+ "toolCount": 19,
6
6
  "tools": [
7
7
  {
8
8
  "name": "authenticate",
9
9
  "title": "Authenticate (device code)",
10
- "description": "Begin device-code authentication. Returns a verification URL and a short user code; show them to the human and ask them to approve in a browser, then call auth_status. No password or browser automation is needed.",
10
+ "description": "Begin device-code authentication. Returns a verification URL and a short user code; show them to the human and ask them to approve in a browser, then call auth_status. No password or browser automation is needed. Pass organizationId to connect one of the user's organizations instead of their personal workspace.",
11
11
  "inputSchema": {
12
12
  "type": "object",
13
- "properties": {},
13
+ "properties": {
14
+ "organizationId": {
15
+ "type": "string",
16
+ "minLength": 1,
17
+ "maxLength": 256,
18
+ "description": "Optional organization id. The approval page pre-selects that organization, and auth_status keeps only a key issued to it. Omit it for the personal workspace, or to let the user choose while approving."
19
+ },
20
+ "workspaceUrl": {
21
+ "type": "string",
22
+ "minLength": 1,
23
+ "maxLength": 2048,
24
+ "description": "Optional CodeTelemetry server to sign in to (default https://codetelemetry.com). Only https URLs on codetelemetry.com or its subdomains are accepted. It picks the server, not an organization."
25
+ }
26
+ },
14
27
  "additionalProperties": false
15
28
  }
16
29
  },
@@ -42,7 +55,7 @@
42
55
  {
43
56
  "name": "write_local_config",
44
57
  "title": "Write local OTEL config (Claude Code or Codex)",
45
- "description": "Write the OpenTelemetry exporter config (and the ingest key) into a recognized local client config — Claude Code's user or current-project settings.json, or Codex's active ~/.codex/config.toml (`client: \"codex\"`). Preserves existing settings and backs up the file first. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns the path and the KEYS written (never values).",
58
+ "description": "Write the OpenTelemetry exporter config (and the ingest key) into a local client config — Claude Code's user or current-project settings.json, Codex's active ~/.codex/config.toml (`client: \"codex\"`), or an explicit `path` to another settings.json, settings.local.json or config.toml. Preserves existing settings and backs up the file first. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns the path and the KEYS written (never values).",
46
59
  "inputSchema": {
47
60
  "type": "object",
48
61
  "properties": {
@@ -62,6 +75,12 @@
62
75
  ],
63
76
  "description": "Claude only: user → ~/.claude/settings.json (default); project → ./.claude/settings.json."
64
77
  },
78
+ "path": {
79
+ "type": "string",
80
+ "minLength": 1,
81
+ "maxLength": 1024,
82
+ "description": "Explicit config file, overriding scope and the Codex default: a settings.json or settings.local.json inside a .claude directory (or $CLAUDE_CONFIG_DIR), or with client \"codex\" a config.toml inside a .codex directory (or $CODEX_HOME). A leading ~ is the home directory. Links, network paths and anything but a regular file are refused."
83
+ },
65
84
  "enrich": {
66
85
  "type": "boolean",
67
86
  "description": "Opt in to content telemetry (default false). Claude Code uploads prompt text, tool details/content, and raw API request/response bodies; Codex uploads prompt text. These can contain source code, commands, file contents, secrets, or other sensitive data."
@@ -102,7 +121,7 @@
102
121
  {
103
122
  "name": "onboard",
104
123
  "title": "Onboard (one shot)",
105
- "description": "Do the whole onboarding in one call: use the session key (or a `key` you pass), write a recognized local client config, send a test event, and confirm it landed. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns a step-by-step checklist. Run authenticate + auth_status first if you don't already have a key.",
124
+ "description": "Do the whole onboarding in one call: use the session key (or a `key` you pass), write a local client config (the recognized default, or an explicit settings.json, settings.local.json or config.toml `path`), send a test event, and confirm it landed. Content telemetry and repository-path observation are separate, explicit opt-ins. Returns a step-by-step checklist. Run authenticate + auth_status first if you don't already have a key.",
106
125
  "inputSchema": {
107
126
  "type": "object",
108
127
  "properties": {
@@ -126,6 +145,12 @@
126
145
  ],
127
146
  "description": "Claude only: which settings.json to write (default user)."
128
147
  },
148
+ "path": {
149
+ "type": "string",
150
+ "minLength": 1,
151
+ "maxLength": 1024,
152
+ "description": "Explicit config file, overriding scope and the Codex default: a settings.json or settings.local.json inside a .claude directory (or $CLAUDE_CONFIG_DIR), or with client \"codex\" a config.toml inside a .codex directory (or $CODEX_HOME). A leading ~ is the home directory. Links, network paths and anything but a regular file are refused."
153
+ },
129
154
  "enrich": {
130
155
  "type": "boolean",
131
156
  "description": "Opt in to content telemetry (default false). Claude Code uploads prompt text, tool details/content, and raw API request/response bodies; Codex uploads prompt text. These can contain source code, commands, file contents, secrets, or other sensitive data."
@@ -145,7 +170,7 @@
145
170
  {
146
171
  "name": "status",
147
172
  "title": "Onboarding status",
148
- "description": "Read-only diagnostics for a recognized client config: whether a key is held (masked), whether Claude Code's user/current-project settings.json or Codex's active ~/.codex/config.toml has the OTEL config, the resolved endpoints, any pending authorization, and `server` — the MCP build and tool-inventory hash. No secrets.",
173
+ "description": "Read-only diagnostics for a client config (the recognized default, or an explicit settings.json, settings.local.json or config.toml `path`): whether a key is held (masked), whether that config has the OTEL settings, the organization requested and attested, the resolved endpoints, any pending authorization, and `server` — the MCP build and tool-inventory hash. No secrets.",
149
174
  "inputSchema": {
150
175
  "type": "object",
151
176
  "properties": {
@@ -164,6 +189,12 @@
164
189
  "project"
165
190
  ],
166
191
  "description": "Claude only: which settings.json to inspect (default user)."
192
+ },
193
+ "path": {
194
+ "type": "string",
195
+ "minLength": 1,
196
+ "maxLength": 1024,
197
+ "description": "Explicit config file, overriding scope and the Codex default: a settings.json or settings.local.json inside a .claude directory (or $CLAUDE_CONFIG_DIR), or with client \"codex\" a config.toml inside a .codex directory (or $CODEX_HOME). A leading ~ is the home directory. Links, network paths and anything but a regular file are refused."
167
198
  }
168
199
  },
169
200
  "additionalProperties": false
@@ -695,6 +726,91 @@
695
726
  "additionalProperties": false
696
727
  }
697
728
  },
729
+ {
730
+ "name": "estimate_plan",
731
+ "title": "T-shirt size a Claude Code / Codex plan",
732
+ "description": "Estimate the effort of a plan a coding assistant proposed — t-shirt size, predicted token range, and confidence — from YOUR similar past coding sessions. Submit the plan content explicitly as `planText` and/or ordered `steps`; the server cannot read the agent's hidden state, so whatever you don't pass isn't sized. The plan is sized as ONE unit: submitted step boundaries are preserved in `source` for provenance, but the estimate is never the sum of independently sized steps. The number predicts CODING-ASSISTANT TOKEN EFFORT, not elapsed time or human engineering hours. When the matched history is weak or contradictory the result is low confidence and carries a small calibration task instead of a falsely precise number. Read-only: it never edits the plan, creates issues, or starts work.",
733
+ "inputSchema": {
734
+ "type": "object",
735
+ "properties": {
736
+ "planText": {
737
+ "type": "string",
738
+ "minLength": 1,
739
+ "maxLength": 4000,
740
+ "description": "The plan as plain text. Combined with `steps` when both are given."
741
+ },
742
+ "steps": {
743
+ "type": "array",
744
+ "maxItems": 50,
745
+ "description": "Ordered plan steps. Each item is a string (the step's detail) or an object { title?, detail? }. Order is preserved in the result's source metadata.",
746
+ "items": {
747
+ "oneOf": [
748
+ {
749
+ "type": "string",
750
+ "minLength": 1,
751
+ "maxLength": 4000
752
+ },
753
+ {
754
+ "type": "object",
755
+ "properties": {
756
+ "title": {
757
+ "type": "string",
758
+ "maxLength": 300
759
+ },
760
+ "detail": {
761
+ "type": "string",
762
+ "maxLength": 4000
763
+ }
764
+ },
765
+ "additionalProperties": false
766
+ }
767
+ ]
768
+ }
769
+ },
770
+ "title": {
771
+ "type": "string",
772
+ "maxLength": 300,
773
+ "description": "Optional plan title, used as the leading line of the sized text."
774
+ },
775
+ "repo": {
776
+ "type": "string",
777
+ "maxLength": 200,
778
+ "description": "Repo the work will land in, when known. Selects that repo's calibrated ladder if one exists."
779
+ },
780
+ "project": {
781
+ "type": "string",
782
+ "maxLength": 200,
783
+ "description": "Optional project/product grouping. Recorded as context; does not change the estimate."
784
+ },
785
+ "provider": {
786
+ "type": "string",
787
+ "enum": [
788
+ "claude",
789
+ "codex"
790
+ ],
791
+ "description": "Which coding assistant produced the plan (claude or codex). Recorded as context; does not change the estimate."
792
+ },
793
+ "model": {
794
+ "type": "string",
795
+ "maxLength": 120,
796
+ "description": "Model id the caller knows produced the plan. Recorded as context; does not change the estimate."
797
+ },
798
+ "lookbackDays": {
799
+ "type": "integer",
800
+ "minimum": 1,
801
+ "maximum": 365,
802
+ "description": "History window to size against (default 90 days)."
803
+ },
804
+ "limit": {
805
+ "type": "integer",
806
+ "minimum": 1,
807
+ "maximum": 5000,
808
+ "description": "Maximum historical sessions to load (default 1000)."
809
+ }
810
+ },
811
+ "additionalProperties": false
812
+ }
813
+ },
698
814
  {
699
815
  "name": "estimate_linear_issue",
700
816
  "title": "T-shirt size an existing Linear issue",