@omnidim-ai/mcp-server 0.2.9 → 0.3.1

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/src/setup.ts CHANGED
@@ -1,14 +1,19 @@
1
- import { execFileSync } from "node:child_process";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
5
1
  import { createInterface, Interface as ReadlineInterface } from "node:readline/promises";
6
2
 
7
3
  import axios from "axios";
8
4
 
5
+ import { buildTargets, describeInstallError } from "./clients.js";
9
6
  import { CREDENTIALS_PATH, readApiKey, writeApiKey } from "./credentials.js";
10
7
  import { printAnimatedSetupBanner } from "./helpers.js";
11
- import { emitInstall, isTelemetryDisabled } from "./telemetry.js";
8
+ import {
9
+ emitInstall,
10
+ emitSetupClientResult,
11
+ emitSetupFinished,
12
+ emitSetupKeyResult,
13
+ emitSetupStarted,
14
+ isTelemetryDisabled,
15
+ type SetupKeyOutcome,
16
+ } from "./telemetry.js";
12
17
 
13
18
  const PROD_API = "https://backend.omnidim.io/api/v1";
14
19
 
@@ -29,80 +34,6 @@ export function pickClosingLine(): string {
29
34
  return CLOSING_LINES[Math.floor(Math.random() * CLOSING_LINES.length)];
30
35
  }
31
36
 
32
- interface ClientTarget {
33
- name: string;
34
- configPath: string;
35
- install: (apiKey: string) => void;
36
- }
37
-
38
- const TARGETS: ClientTarget[] = [
39
- {
40
- name: "Claude Code",
41
- configPath: join(homedir(), ".claude.json"),
42
- install: installClaudeCode,
43
- },
44
- {
45
- name: "Claude Desktop",
46
- configPath: join(
47
- homedir(),
48
- "Library",
49
- "Application Support",
50
- "Claude",
51
- "claude_desktop_config.json",
52
- ),
53
- install: (key) => upsertJsonConfig(TARGETS[1].configPath, key),
54
- },
55
- {
56
- name: "Cursor",
57
- configPath: join(homedir(), ".cursor", "mcp.json"),
58
- install: (key) => upsertJsonConfig(TARGETS[2].configPath, key),
59
- },
60
- {
61
- name: "Windsurf",
62
- configPath: join(homedir(), ".codeium", "windsurf", "mcp_config.json"),
63
- install: (key) => upsertJsonConfig(TARGETS[3].configPath, key),
64
- },
65
- ];
66
-
67
- function upsertJsonConfig(configPath: string, apiKey: string): void {
68
- const config = existsSync(configPath)
69
- ? (JSON.parse(readFileSync(configPath, "utf8")) as Record<string, unknown>)
70
- : {};
71
- const servers = ((config.mcpServers as Record<string, unknown>) ?? {}) as Record<string, unknown>;
72
- servers.omnidim = {
73
- command: "npx",
74
- args: ["-y", "@omnidim-ai/mcp-server"],
75
- env: { OMNIDIM_API_KEY: apiKey },
76
- };
77
- config.mcpServers = servers;
78
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
79
- }
80
-
81
- function installClaudeCode(apiKey: string): void {
82
- try {
83
- execFileSync("claude", ["mcp", "remove", "omnidim", "--scope", "user"], { stdio: "ignore" });
84
- } catch {
85
- // not registered, fine
86
- }
87
- try {
88
- // Name before the variadic -e so commander doesn't gobble it as an env value.
89
- execFileSync(
90
- "claude",
91
- [
92
- "mcp", "add", "omnidim",
93
- "--scope", "user",
94
- "-e", `OMNIDIM_API_KEY=${apiKey}`,
95
- "--", "npx", "-y", "@omnidim-ai/mcp-server",
96
- ],
97
- { stdio: ["ignore", "pipe", "pipe"] },
98
- );
99
- } catch (e) {
100
- const err = e as { stderr?: Buffer; stdout?: Buffer; message: string };
101
- const detail = (err.stderr ?? err.stdout ?? Buffer.from("")).toString().trim();
102
- throw new Error(detail || err.message);
103
- }
104
- }
105
-
106
37
  // Echoes `*` per input char so pasted keys never land in scrollback.
107
38
  function readMaskedLine(prompt: string): Promise<string> {
108
39
  process.stdout.write(prompt);
@@ -164,7 +95,26 @@ function readMaskedLine(prompt: string): Promise<string> {
164
95
  });
165
96
  }
166
97
 
167
- async function validateApiKey(apiKey: string): Promise<string | null> {
98
+ type KeyFailureReason = "rejected_401" | "network_error" | "unexpected";
99
+
100
+ type KeyCheck = { ok: true } | { ok: false; reason: KeyFailureReason; message: string };
101
+
102
+ // Maps the last key-check failure to the telemetry outcome. `null` means the
103
+ // user never submitted a key (only empty input), i.e. a genuine abort.
104
+ export function keyOutcomeFromReason(reason: KeyFailureReason | null): SetupKeyOutcome {
105
+ switch (reason) {
106
+ case "rejected_401":
107
+ return "rejected_401";
108
+ case "network_error":
109
+ return "network_error";
110
+ case "unexpected":
111
+ return "server_error";
112
+ default:
113
+ return "aborted";
114
+ }
115
+ }
116
+
117
+ async function validateApiKey(apiKey: string): Promise<KeyCheck> {
168
118
  try {
169
119
  const res = await axios.get(`${PROD_API}/agents`, {
170
120
  params: { pagesize: 1 },
@@ -172,16 +122,17 @@ async function validateApiKey(apiKey: string): Promise<string | null> {
172
122
  timeout: 10_000,
173
123
  validateStatus: () => true,
174
124
  });
175
- if (res.status === 200) return null;
176
- if (res.status === 401) return "Uh oh! Key rejected";
177
- return `unexpected status ${res.status}`;
125
+ if (res.status === 200) return { ok: true };
126
+ if (res.status === 401) return { ok: false, reason: "rejected_401", message: "Uh oh! Key rejected" };
127
+ return { ok: false, reason: "unexpected", message: `unexpected status ${res.status}` };
178
128
  } catch (e) {
179
- return e instanceof Error ? e.message : "network error";
129
+ return { ok: false, reason: "network_error", message: e instanceof Error ? e.message : "network error" };
180
130
  }
181
131
  }
182
132
 
183
133
  export async function runSetup(): Promise<number> {
184
134
  await printAnimatedSetupBanner();
135
+ void emitSetupStarted();
185
136
 
186
137
  let rl: ReadlineInterface | null = null;
187
138
  try {
@@ -192,23 +143,25 @@ export async function runSetup(): Promise<number> {
192
143
  if (saved) {
193
144
  process.stdout.write(` Saved key found at ${dim(CREDENTIALS_PATH)}\n`);
194
145
  process.stdout.write(` ${dim("checking...")}\n`);
195
- const err = await validateApiKey(saved);
196
- if (err === null) {
146
+ const check = await validateApiKey(saved);
147
+ if (check.ok) {
197
148
  rl = createInterface({ input: process.stdin, output: process.stdout });
198
149
  const ans = (await rl.question(" Reuse this key? [Y/n] ")).trim().toLowerCase();
199
150
  rl.close();
200
151
  rl = null;
201
152
  if (ans !== "n" && ans !== "no") {
202
153
  apiKey = saved;
154
+ void emitSetupKeyResult("reused");
203
155
  process.stdout.write(` ${teal("●")} using saved key\n\n`);
204
156
  }
205
157
  } else {
206
- process.stdout.write(red(` saved key: ${err}\n`));
158
+ process.stdout.write(red(` saved key: ${check.message}\n`));
207
159
  }
208
160
  }
209
161
 
210
162
  if (!apiKey) {
211
163
  process.stdout.write(` Get a key at ${dim("omnidim.io/api-management")}\n`);
164
+ let lastReason: KeyFailureReason | null = null;
212
165
  for (let i = 0; i < 3 && !apiKey; i++) {
213
166
  const input = (await readMaskedLine(" API key: ")).trim();
214
167
  if (!input) {
@@ -216,24 +169,28 @@ export async function runSetup(): Promise<number> {
216
169
  continue;
217
170
  }
218
171
  process.stdout.write(` ${dim("checking...")}\n`);
219
- const err = await validateApiKey(input);
220
- if (err === null) {
172
+ const check = await validateApiKey(input);
173
+ if (check.ok) {
221
174
  apiKey = input;
222
175
  break;
223
176
  }
224
- process.stdout.write(red(` ${err}, try again\n`));
177
+ lastReason = check.reason;
178
+ process.stdout.write(red(` ${check.message}, try again\n`));
225
179
  }
226
180
  if (!apiKey) {
181
+ void emitSetupKeyResult(keyOutcomeFromReason(lastReason));
227
182
  process.stdout.write(red("\n three failed attempts, aborting.\n"));
228
183
  return 1;
229
184
  }
230
185
 
186
+ void emitSetupKeyResult("entered");
231
187
  const path = writeApiKey(apiKey);
232
188
  process.stdout.write(` ${teal("●")} key saved to ${dim(path)}\n\n`);
233
189
  }
234
190
 
235
- const detected = TARGETS.filter((t) => existsSync(t.configPath));
191
+ const detected = buildTargets().filter((t) => t.detect());
236
192
  if (detected.length === 0) {
193
+ void emitSetupFinished(0, 0);
237
194
  process.stdout.write(` ${dim("no MCP clients detected. Add manually:")}\n`);
238
195
  process.stdout.write(` claude mcp add omnidim -- npx -y @omnidim-ai/mcp-server\n\n`);
239
196
  return 0;
@@ -244,13 +201,22 @@ export async function runSetup(): Promise<number> {
244
201
 
245
202
  rl = createInterface({ input: process.stdin, output: process.stdout });
246
203
  const ans = (await rl.question("\n Install for all? [Y/n] ")).trim().toLowerCase();
247
- if (ans === "n" || ans === "no") return 0;
204
+ if (ans === "n" || ans === "no") {
205
+ void emitSetupFinished(0, 0);
206
+ return 0;
207
+ }
248
208
 
209
+ let installed = 0;
210
+ let failed = 0;
249
211
  for (const t of detected) {
250
212
  try {
251
213
  t.install(apiKey);
214
+ installed++;
215
+ void emitSetupClientResult(t.id, "installed");
252
216
  process.stdout.write(` ${teal("●")} installed for ${t.name}\n`);
253
217
  } catch (e) {
218
+ failed++;
219
+ void emitSetupClientResult(t.id, "failed", describeInstallError(e));
254
220
  const msg = e instanceof Error ? e.message : String(e);
255
221
  process.stdout.write(red(` failed for ${t.name}: ${msg}\n`));
256
222
  process.stdout.write(
@@ -258,6 +224,7 @@ export async function runSetup(): Promise<number> {
258
224
  );
259
225
  }
260
226
  }
227
+ void emitSetupFinished(installed, failed);
261
228
  if (isTelemetryDisabled()) {
262
229
  process.stdout.write(`\n ${dim("Telemetry off")}\n`);
263
230
  } else {
package/src/telemetry.ts CHANGED
@@ -101,6 +101,28 @@ async function send(event: string, extra: Record<string, unknown> = {}): Promise
101
101
  }
102
102
  }
103
103
 
104
+ export interface SanitizedError {
105
+ error_class: string;
106
+ error_code: string;
107
+ }
108
+
109
+ // Reduce any thrown value to two low-cardinality, non-identifying fields.
110
+ // Never returns a message, stack, path, or payload, since those can carry
111
+ // usernames and file paths. Node's documented errno strings (ENOENT,
112
+ // EACCES, ...) and the error constructor name are safe to keep.
113
+ export function sanitizeError(error: unknown): SanitizedError {
114
+ if (error && typeof error === "object") {
115
+ const e = error as { name?: unknown; code?: unknown; constructor?: { name?: string } };
116
+ const rawName =
117
+ typeof e.name === "string" && e.name ? e.name : e.constructor?.name ?? "Error";
118
+ const error_class = /^[A-Za-z][A-Za-z0-9]{0,39}$/.test(rawName) ? rawName : "Error";
119
+ const error_code =
120
+ typeof e.code === "string" && /^[A-Z][A-Z0-9_]{1,31}$/.test(e.code) ? e.code : "unknown";
121
+ return { error_class, error_code };
122
+ }
123
+ return { error_class: "Error", error_code: "unknown" };
124
+ }
125
+
104
126
  export async function emitInstall(): Promise<void> {
105
127
  await send("install");
106
128
  }
@@ -109,31 +131,123 @@ export async function emitSessionStart(): Promise<void> {
109
131
  await send("session_start");
110
132
  }
111
133
 
112
- interface SessionEndPayload {
134
+ export type SetupKeyOutcome =
135
+ | "reused"
136
+ | "entered"
137
+ | "rejected_401"
138
+ | "network_error"
139
+ | "server_error"
140
+ | "aborted";
141
+
142
+ export async function emitSetupStarted(): Promise<void> {
143
+ await send("setup_started");
144
+ }
145
+
146
+ export async function emitSetupKeyResult(outcome: SetupKeyOutcome): Promise<void> {
147
+ await send("setup_key_result", { outcome });
148
+ }
149
+
150
+ export async function emitSetupClientResult(
151
+ client: string,
152
+ outcome: "installed" | "failed",
153
+ error?: SanitizedError & { exit_code?: number },
154
+ ): Promise<void> {
155
+ await send("setup_client_result", { client, outcome, ...(error ?? {}) });
156
+ }
157
+
158
+ export async function emitSetupFinished(
159
+ clientsInstalled: number,
160
+ clientsFailed: number,
161
+ ): Promise<void> {
162
+ await send("setup_finished", {
163
+ clients_installed: clientsInstalled,
164
+ clients_failed: clientsFailed,
165
+ });
166
+ }
167
+
168
+ interface ToolUsage {
169
+ tool: string;
170
+ count: number;
171
+ ok: number;
172
+ errors: Array<{ code: string; count: number }>;
173
+ }
174
+
175
+ export interface SessionSummary {
113
176
  duration_s: number;
114
- tools_called: Array<{ tool: string; count: number }>;
177
+ tools_called: ToolUsage[];
178
+ tool_errors_total: number;
115
179
  }
116
180
 
117
- export async function emitSessionEnd(payload: SessionEndPayload): Promise<void> {
118
- await send("session_end", { ...payload });
181
+ interface ToolStat {
182
+ count: number;
183
+ ok: number;
184
+ errors: Map<string, number>;
119
185
  }
120
186
 
121
- const toolCounts = new Map<string, number>();
187
+ const toolStats = new Map<string, ToolStat>();
122
188
  let sessionStartMs: number | null = null;
189
+ // Guards against one session reporting twice (a crash racing graceful
190
+ // shutdown), which would otherwise log an empty ghost event.
191
+ let terminated = false;
123
192
 
124
- export function recordToolCall(name: string): void {
125
- toolCounts.set(name, (toolCounts.get(name) ?? 0) + 1);
193
+ // outcome is "ok" for a successful call, otherwise a category code
194
+ // ("http_401", "network", "timeout", "validation", "upstream_html",
195
+ // "no_api_key", "unknown"). Never a tool's input or output.
196
+ export function recordToolResult(name: string, outcome: string): void {
197
+ let stat = toolStats.get(name);
198
+ if (!stat) {
199
+ stat = { count: 0, ok: 0, errors: new Map() };
200
+ toolStats.set(name, stat);
201
+ }
202
+ stat.count += 1;
203
+ if (outcome === "ok") {
204
+ stat.ok += 1;
205
+ } else {
206
+ stat.errors.set(outcome, (stat.errors.get(outcome) ?? 0) + 1);
207
+ }
126
208
  }
127
209
 
128
210
  export function beginSession(): void {
129
211
  sessionStartMs = Date.now();
212
+ terminated = false;
130
213
  void emitSessionStart();
131
214
  }
132
215
 
133
- export function endSession(): SessionEndPayload {
216
+ function drainSession(): SessionSummary {
134
217
  const duration_s = sessionStartMs ? Math.round((Date.now() - sessionStartMs) / 1000) : 0;
135
- const tools_called = Array.from(toolCounts.entries()).map(([tool, count]) => ({ tool, count }));
218
+ let tool_errors_total = 0;
219
+ const tools_called: ToolUsage[] = Array.from(toolStats.entries()).map(([tool, stat]) => {
220
+ const errors = Array.from(stat.errors.entries()).map(([code, count]) => {
221
+ tool_errors_total += count;
222
+ return { code, count };
223
+ });
224
+ return { tool, count: stat.count, ok: stat.ok, errors };
225
+ });
136
226
  sessionStartMs = null;
137
- toolCounts.clear();
138
- return { duration_s, tools_called };
227
+ toolStats.clear();
228
+ return { duration_s, tools_called, tool_errors_total };
229
+ }
230
+
231
+ export function endSession(): SessionSummary {
232
+ return drainSession();
233
+ }
234
+
235
+ export async function emitSessionEnd(payload: SessionSummary): Promise<void> {
236
+ if (terminated) return;
237
+ terminated = true;
238
+ await send("session_end", { ...payload });
239
+ }
240
+
241
+ // Fires on a crash so the session still terminates with a record carrying
242
+ // its tool-call summary; a clean session_end never runs on a crash path.
243
+ export async function emitSessionCrash(error: unknown): Promise<void> {
244
+ if (terminated) return;
245
+ terminated = true;
246
+ const active = sessionStartMs !== null;
247
+ const summary = drainSession();
248
+ await send("session_crash", {
249
+ phase: active ? "runtime" : "startup",
250
+ ...sanitizeError(error),
251
+ ...summary,
252
+ });
139
253
  }