@codetelemetry/mcp 0.3.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/LICENSE +21 -0
  2. package/README.md +242 -0
  3. package/dist/src/client/agent.d.ts +379 -0
  4. package/dist/src/client/agent.js +204 -0
  5. package/dist/src/client/codexConfig.d.ts +23 -0
  6. package/dist/src/client/codexConfig.js +265 -0
  7. package/dist/src/client/config.d.ts +26 -0
  8. package/dist/src/client/config.js +32 -0
  9. package/dist/src/client/connectivity.d.ts +27 -0
  10. package/dist/src/client/connectivity.js +54 -0
  11. package/dist/src/client/deviceClient.d.ts +32 -0
  12. package/dist/src/client/deviceClient.js +112 -0
  13. package/dist/src/client/keys.d.ts +5 -0
  14. package/dist/src/client/keys.js +24 -0
  15. package/dist/src/client/onboard.d.ts +47 -0
  16. package/dist/src/client/onboard.js +84 -0
  17. package/dist/src/client/otlp.d.ts +18 -0
  18. package/dist/src/client/otlp.js +60 -0
  19. package/dist/src/client/repositoryHook.d.ts +17 -0
  20. package/dist/src/client/repositoryHook.js +631 -0
  21. package/dist/src/client/settings.d.ts +28 -0
  22. package/dist/src/client/settings.js +97 -0
  23. package/dist/src/index.d.ts +2 -0
  24. package/dist/src/index.js +2 -0
  25. package/dist/src/manifest.d.ts +29 -0
  26. package/dist/src/manifest.js +93 -0
  27. package/dist/src/mcpServer.d.ts +3 -0
  28. package/dist/src/mcpServer.js +18 -0
  29. package/dist/src/server.d.ts +2 -0
  30. package/dist/src/server.js +16 -0
  31. package/dist/src/session.d.ts +21 -0
  32. package/dist/src/session.js +44 -0
  33. package/dist/src/tools.d.ts +28 -0
  34. package/dist/src/tools.js +697 -0
  35. package/dist/src/version.d.ts +2 -0
  36. package/dist/src/version.js +2 -0
  37. package/package.json +55 -0
  38. package/tool-manifest.json +474 -0
@@ -0,0 +1,97 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { assertKey } from "./keys.js";
4
+ import { installRepositoryObservationHook, removeRepositoryObservationFiles, removeRepositoryObservationHook, } from "./repositoryHook.js";
5
+ export function baseEnv(key, ingestEndpoint) {
6
+ return {
7
+ CLAUDE_CODE_ENABLE_TELEMETRY: "1",
8
+ OTEL_METRICS_EXPORTER: "otlp",
9
+ OTEL_LOGS_EXPORTER: "otlp",
10
+ OTEL_EXPORTER_OTLP_PROTOCOL: "http/protobuf",
11
+ OTEL_EXPORTER_OTLP_ENDPOINT: ingestEndpoint,
12
+ OTEL_EXPORTER_OTLP_HEADERS: `Authorization=Bearer ${key}`,
13
+ };
14
+ }
15
+ export function enrichEnv() {
16
+ return {
17
+ OTEL_METRICS_INCLUDE_SESSION_ID: "true",
18
+ OTEL_LOG_USER_PROMPTS: "1",
19
+ OTEL_LOG_TOOL_DETAILS: "1",
20
+ OTEL_LOG_TOOL_CONTENT: "1",
21
+ OTEL_LOG_RAW_API_BODIES: "1",
22
+ };
23
+ }
24
+ export const LEGACY_BROKEN_RESOURCE_ATTRS = "project.path=$PWD";
25
+ export function buildEnvBlock(key, ingestEndpoint, enrich) {
26
+ const base = baseEnv(key, ingestEndpoint);
27
+ return enrich ? { ...base, ...enrichEnv() } : base;
28
+ }
29
+ function readJson(filePath) {
30
+ if (!fs.existsSync(filePath))
31
+ return {};
32
+ const raw = fs.readFileSync(filePath, "utf8").trim();
33
+ if (!raw)
34
+ return {};
35
+ try {
36
+ const parsed = JSON.parse(raw);
37
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
38
+ return parsed;
39
+ throw new Error("settings.json is not a JSON object");
40
+ }
41
+ catch (err) {
42
+ throw new Error(`refusing to overwrite ${filePath}: it isn't valid JSON (${err.message}). ` +
43
+ `Fix or move it, then retry.`);
44
+ }
45
+ }
46
+ export function mergeSettings(existing, env) {
47
+ const prevEnv = existing.env && typeof existing.env === "object" && !Array.isArray(existing.env)
48
+ ? { ...existing.env }
49
+ : {};
50
+ if (prevEnv.OTEL_RESOURCE_ATTRIBUTES === LEGACY_BROKEN_RESOURCE_ATTRS) {
51
+ delete prevEnv.OTEL_RESOURCE_ATTRIBUTES;
52
+ }
53
+ return { ...existing, env: { ...prevEnv, ...env } };
54
+ }
55
+ export function writeSettings(opts) {
56
+ const key = assertKey(opts.key);
57
+ const env = buildEnvBlock(key, opts.ingestEndpoint, !!opts.enrich);
58
+ const filePath = path.resolve(opts.settingsPath);
59
+ const existed = fs.existsSync(filePath);
60
+ const existing = readJson(filePath);
61
+ const envMerged = mergeSettings(existing, env);
62
+ const merged = opts.repositoryObservation
63
+ ? installRepositoryObservationHook(envMerged, filePath)
64
+ : removeRepositoryObservationHook(envMerged);
65
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
66
+ let backupPath = null;
67
+ if (existed && opts.backup !== false) {
68
+ backupPath = `${filePath}.bak`;
69
+ fs.copyFileSync(filePath, backupPath);
70
+ }
71
+ fs.writeFileSync(filePath, JSON.stringify(merged, null, 2) + "\n", { mode: 0o600 });
72
+ try {
73
+ fs.chmodSync(filePath, 0o600);
74
+ }
75
+ catch {
76
+ }
77
+ if (!opts.repositoryObservation)
78
+ removeRepositoryObservationFiles(filePath);
79
+ return { path: filePath, wrote: Object.keys(env), backupPath, created: !existed };
80
+ }
81
+ export function readSettingsSummary(filePath) {
82
+ if (!fs.existsSync(filePath))
83
+ return { exists: false, otelKeys: [], hasKey: false };
84
+ let obj;
85
+ try {
86
+ obj = readJson(filePath);
87
+ }
88
+ catch {
89
+ return { exists: true, otelKeys: [], hasKey: false };
90
+ }
91
+ const env = obj.env && typeof obj.env === "object" && !Array.isArray(obj.env)
92
+ ? obj.env
93
+ : {};
94
+ const otelKeys = Object.keys(env).filter((k) => k.startsWith("OTEL_") || k === "CLAUDE_CODE_ENABLE_TELEMETRY");
95
+ const hasKey = typeof env.OTEL_EXPORTER_OTLP_HEADERS === "string" && env.OTEL_EXPORTER_OTLP_HEADERS.includes("cot_");
96
+ return { exists: true, otelKeys, hasKey };
97
+ }
@@ -0,0 +1,2 @@
1
+ export { TOOLS, TOOLS_BY_NAME, callTool, type ToolContext, type ToolDef, type ToolResult, } from "./tools.ts";
2
+ export { OnboardingSession, type KeySource } from "./session.ts";
@@ -0,0 +1,2 @@
1
+ export { TOOLS, TOOLS_BY_NAME, callTool, } from "./tools.js";
2
+ export { OnboardingSession } from "./session.js";
@@ -0,0 +1,29 @@
1
+ import { type ToolDef } from "./tools.ts";
2
+ export type ToolManifestEntry = {
3
+ name: string;
4
+ title: string;
5
+ description: string;
6
+ inputSchema: Record<string, unknown>;
7
+ };
8
+ export type ToolManifest = {
9
+ serverName: string;
10
+ serverVersion: string;
11
+ registryHash: string;
12
+ toolCount: number;
13
+ tools: ToolManifestEntry[];
14
+ };
15
+ export declare function manifestEntries(tools: readonly ToolDef[]): ToolManifestEntry[];
16
+ export declare function canonicalJson(value: unknown): string;
17
+ export declare function registryHash(tools: readonly ToolManifestEntry[], serverName?: string): string;
18
+ export declare function toolManifest(tools: readonly ToolDef[]): ToolManifest;
19
+ export declare function registryIdentity(tools: readonly ToolDef[]): {
20
+ name: string;
21
+ version: string;
22
+ registryHash: string;
23
+ toolCount: number;
24
+ };
25
+ export declare function normalizeEntries(value: unknown): ToolManifestEntry[];
26
+ export declare function diffEntries(expected: readonly ToolManifestEntry[], actual: readonly ToolManifestEntry[], labels?: {
27
+ expected: string;
28
+ actual: string;
29
+ }): string[];
@@ -0,0 +1,93 @@
1
+ import { createHash } from "node:crypto";
2
+ import {} from "./tools.js";
3
+ import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from "./version.js";
4
+ export function manifestEntries(tools) {
5
+ return tools.map((t) => ({
6
+ name: t.name,
7
+ title: t.title,
8
+ description: t.description,
9
+ inputSchema: t.inputSchema,
10
+ }));
11
+ }
12
+ export function canonicalJson(value) {
13
+ if (value === undefined)
14
+ return "null";
15
+ if (value === null || typeof value !== "object")
16
+ return JSON.stringify(value) ?? "null";
17
+ if (Array.isArray(value))
18
+ return `[${value.map(canonicalJson).join(",")}]`;
19
+ const record = value;
20
+ const parts = Object.keys(record)
21
+ .sort()
22
+ .filter((k) => record[k] !== undefined)
23
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`);
24
+ return `{${parts.join(",")}}`;
25
+ }
26
+ export function registryHash(tools, serverName = MCP_SERVER_NAME) {
27
+ return createHash("sha256").update(canonicalJson({ serverName, tools })).digest("hex");
28
+ }
29
+ export function toolManifest(tools) {
30
+ const entries = manifestEntries(tools);
31
+ return {
32
+ serverName: MCP_SERVER_NAME,
33
+ serverVersion: MCP_SERVER_VERSION,
34
+ registryHash: registryHash(entries),
35
+ toolCount: entries.length,
36
+ tools: entries,
37
+ };
38
+ }
39
+ export function registryIdentity(tools) {
40
+ const entries = manifestEntries(tools);
41
+ return {
42
+ name: MCP_SERVER_NAME,
43
+ version: MCP_SERVER_VERSION,
44
+ registryHash: registryHash(entries),
45
+ toolCount: entries.length,
46
+ };
47
+ }
48
+ export function normalizeEntries(value) {
49
+ if (!Array.isArray(value))
50
+ return [];
51
+ return value.map((raw) => {
52
+ const t = (raw ?? {});
53
+ return {
54
+ name: typeof t.name === "string" ? t.name : "",
55
+ title: typeof t.title === "string" ? t.title : "",
56
+ description: typeof t.description === "string" ? t.description : "",
57
+ inputSchema: t.inputSchema && typeof t.inputSchema === "object" && !Array.isArray(t.inputSchema)
58
+ ? t.inputSchema
59
+ : {},
60
+ };
61
+ });
62
+ }
63
+ export function diffEntries(expected, actual, labels = { expected: "expected", actual: "actual" }) {
64
+ const problems = [];
65
+ const byName = (entries) => new Map(entries.map((e) => [e.name, e]));
66
+ const want = byName(expected);
67
+ const got = byName(actual);
68
+ for (const name of want.keys()) {
69
+ if (!got.has(name))
70
+ problems.push(`tool "${name}" is in the ${labels.expected} registry but MISSING from the ${labels.actual} registry`);
71
+ }
72
+ for (const name of got.keys()) {
73
+ if (!want.has(name))
74
+ problems.push(`tool "${name}" is in the ${labels.actual} registry but not in the ${labels.expected} registry`);
75
+ }
76
+ for (const [name, w] of want) {
77
+ const g = got.get(name);
78
+ if (!g)
79
+ continue;
80
+ for (const field of ["title", "description"]) {
81
+ if (w[field] !== g[field])
82
+ problems.push(`tool "${name}": ${field} differs (${labels.expected} vs ${labels.actual})`);
83
+ }
84
+ if (canonicalJson(w.inputSchema) !== canonicalJson(g.inputSchema)) {
85
+ problems.push(`tool "${name}": inputSchema differs (${labels.expected} vs ${labels.actual})`);
86
+ }
87
+ }
88
+ const order = (entries) => entries.map((e) => e.name).join(",");
89
+ if (!problems.length && order(expected) !== order(actual)) {
90
+ problems.push(`tool ORDER differs: ${labels.expected}=[${order(expected)}] ${labels.actual}=[${order(actual)}]`);
91
+ }
92
+ return problems;
93
+ }
@@ -0,0 +1,3 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { type ToolContext } from "./tools.ts";
3
+ export declare function buildServer(ctx: ToolContext): Server;
@@ -0,0 +1,18 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
+ import { TOOLS, callTool } from "./tools.js";
4
+ import { manifestEntries } from "./manifest.js";
5
+ import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from "./version.js";
6
+ export function buildServer(ctx) {
7
+ const server = new Server({ name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION }, { capabilities: { tools: {} } });
8
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: manifestEntries(TOOLS) }));
9
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
10
+ const result = await callTool(req.params.name, (req.params.arguments ?? {}), ctx);
11
+ return {
12
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
13
+ structuredContent: result,
14
+ isError: result.ok === false,
15
+ };
16
+ });
17
+ return server;
18
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { buildServer } from "./mcpServer.js";
4
+ import {} from "./tools.js";
5
+ import { OnboardingSession } from "./session.js";
6
+ const ctx = {
7
+ session: new OnboardingSession(),
8
+ endpointsOverride: {
9
+ apiBase: process.env.CODETELEMETRY_API_BASE,
10
+ ingestEndpoint: process.env.CODETELEMETRY_INGEST_ENDPOINT,
11
+ },
12
+ };
13
+ const server = buildServer(ctx);
14
+ const transport = new StdioServerTransport();
15
+ await server.connect(transport);
16
+ process.stderr.write("codetelemetry MCP server ready (stdio)\n");
@@ -0,0 +1,21 @@
1
+ export type KeySource = "device-flow" | "pasted";
2
+ export declare class OnboardingSession {
3
+ #private;
4
+ keyHash: string | null;
5
+ source: KeySource | null;
6
+ ingestEndpoint: string | null;
7
+ apiBase: string | null;
8
+ deviceCode: string | null;
9
+ userCode: string | null;
10
+ lastProbeId: string | null;
11
+ setKey(plaintext: string, source: KeySource, ingestEndpoint?: string): void;
12
+ hasKey(): boolean;
13
+ useKey(): string;
14
+ view(): {
15
+ hasKey: boolean;
16
+ masked: string | null;
17
+ keyHash: string | null;
18
+ source: KeySource | null;
19
+ };
20
+ clear(): void;
21
+ }
@@ -0,0 +1,44 @@
1
+ import { mask, keyHash, looksLikeKey } from "./client/keys.js";
2
+ export class OnboardingSession {
3
+ #key = null;
4
+ keyHash = null;
5
+ source = null;
6
+ ingestEndpoint = null;
7
+ apiBase = null;
8
+ deviceCode = null;
9
+ userCode = null;
10
+ lastProbeId = null;
11
+ setKey(plaintext, source, ingestEndpoint) {
12
+ if (!looksLikeKey(plaintext))
13
+ throw new Error("not a valid CodeTelemetry ingest key (expected cot_…)");
14
+ this.#key = plaintext.trim();
15
+ this.keyHash = keyHash(this.#key);
16
+ this.source = source;
17
+ if (ingestEndpoint)
18
+ this.ingestEndpoint = ingestEndpoint;
19
+ }
20
+ hasKey() {
21
+ return this.#key !== null;
22
+ }
23
+ useKey() {
24
+ if (this.#key === null)
25
+ throw new Error("no key in session — authenticate or provide a key first");
26
+ return this.#key;
27
+ }
28
+ view() {
29
+ return {
30
+ hasKey: this.hasKey(),
31
+ masked: this.#key ? mask(this.#key) : null,
32
+ keyHash: this.keyHash,
33
+ source: this.source,
34
+ };
35
+ }
36
+ clear() {
37
+ this.#key = null;
38
+ this.keyHash = null;
39
+ this.source = null;
40
+ this.deviceCode = null;
41
+ this.userCode = null;
42
+ this.lastProbeId = null;
43
+ }
44
+ }
@@ -0,0 +1,28 @@
1
+ import { type FetchLike } from "./client/otlp.ts";
2
+ import { OnboardingSession } from "./session.ts";
3
+ export type ToolContext = {
4
+ session: OnboardingSession;
5
+ endpointsOverride?: {
6
+ apiBase?: string;
7
+ ingestEndpoint?: string;
8
+ };
9
+ configPathsOverride?: {
10
+ claude?: string;
11
+ codex?: string;
12
+ };
13
+ fetchImpl?: FetchLike;
14
+ };
15
+ export type ToolResult = {
16
+ ok: boolean;
17
+ } & Record<string, unknown>;
18
+ export type ToolDef = {
19
+ name: string;
20
+ title: string;
21
+ description: string;
22
+ inputSchema: Record<string, unknown>;
23
+ handler: (args: Record<string, unknown>, ctx: ToolContext) => Promise<ToolResult>;
24
+ };
25
+ export declare const ISSUE_SIZING_ERRORS: ReadonlySet<string>;
26
+ export declare const TOOLS: ToolDef[];
27
+ export declare const TOOLS_BY_NAME: Record<string, ToolDef>;
28
+ export declare function callTool(name: string, args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;