@omnidim-ai/mcp-server 0.2.8 → 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
 
9
- import { writeApiKey } from "./credentials.js";
5
+ import { buildTargets, describeInstallError } from "./clients.js";
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"], { 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,45 +122,75 @@ 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();
185
- process.stdout.write(` Get a key at ${dim("omnidim.io/api-management")}\n`);
135
+ void emitSetupStarted();
186
136
 
187
137
  let rl: ReadlineInterface | null = null;
188
138
  try {
189
139
  let apiKey = "";
190
- for (let i = 0; i < 3 && !apiKey; i++) {
191
- const input = (await readMaskedLine(" API key: ")).trim();
192
- if (!input) {
193
- process.stdout.write(red(" empty input, try again\n"));
194
- continue;
195
- }
140
+
141
+ // If we already have a saved key, validate it and offer to reuse.
142
+ const saved = readApiKey();
143
+ if (saved) {
144
+ process.stdout.write(` Saved key found at ${dim(CREDENTIALS_PATH)}\n`);
196
145
  process.stdout.write(` ${dim("checking...")}\n`);
197
- const err = await validateApiKey(input);
198
- if (err === null) {
199
- apiKey = input;
200
- break;
146
+ const check = await validateApiKey(saved);
147
+ if (check.ok) {
148
+ rl = createInterface({ input: process.stdin, output: process.stdout });
149
+ const ans = (await rl.question(" Reuse this key? [Y/n] ")).trim().toLowerCase();
150
+ rl.close();
151
+ rl = null;
152
+ if (ans !== "n" && ans !== "no") {
153
+ apiKey = saved;
154
+ void emitSetupKeyResult("reused");
155
+ process.stdout.write(` ${teal("●")} using saved key\n\n`);
156
+ }
157
+ } else {
158
+ process.stdout.write(red(` saved key: ${check.message}\n`));
201
159
  }
202
- process.stdout.write(red(` ${err}, try again\n`));
203
160
  }
161
+
204
162
  if (!apiKey) {
205
- process.stdout.write(red("\n three failed attempts, aborting.\n"));
206
- return 1;
207
- }
163
+ process.stdout.write(` Get a key at ${dim("omnidim.io/api-management")}\n`);
164
+ let lastReason: KeyFailureReason | null = null;
165
+ for (let i = 0; i < 3 && !apiKey; i++) {
166
+ const input = (await readMaskedLine(" API key: ")).trim();
167
+ if (!input) {
168
+ process.stdout.write(red(" empty input, try again\n"));
169
+ continue;
170
+ }
171
+ process.stdout.write(` ${dim("checking...")}\n`);
172
+ const check = await validateApiKey(input);
173
+ if (check.ok) {
174
+ apiKey = input;
175
+ break;
176
+ }
177
+ lastReason = check.reason;
178
+ process.stdout.write(red(` ${check.message}, try again\n`));
179
+ }
180
+ if (!apiKey) {
181
+ void emitSetupKeyResult(keyOutcomeFromReason(lastReason));
182
+ process.stdout.write(red("\n three failed attempts, aborting.\n"));
183
+ return 1;
184
+ }
208
185
 
209
- const path = writeApiKey(apiKey);
210
- process.stdout.write(` ${teal("●")} key saved to ${dim(path)}\n\n`);
186
+ void emitSetupKeyResult("entered");
187
+ const path = writeApiKey(apiKey);
188
+ process.stdout.write(` ${teal("●")} key saved to ${dim(path)}\n\n`);
189
+ }
211
190
 
212
- const detected = TARGETS.filter((t) => existsSync(t.configPath));
191
+ const detected = buildTargets().filter((t) => t.detect());
213
192
  if (detected.length === 0) {
193
+ void emitSetupFinished(0, 0);
214
194
  process.stdout.write(` ${dim("no MCP clients detected. Add manually:")}\n`);
215
195
  process.stdout.write(` claude mcp add omnidim -- npx -y @omnidim-ai/mcp-server\n\n`);
216
196
  return 0;
@@ -221,13 +201,22 @@ export async function runSetup(): Promise<number> {
221
201
 
222
202
  rl = createInterface({ input: process.stdin, output: process.stdout });
223
203
  const ans = (await rl.question("\n Install for all? [Y/n] ")).trim().toLowerCase();
224
- if (ans === "n" || ans === "no") return 0;
204
+ if (ans === "n" || ans === "no") {
205
+ void emitSetupFinished(0, 0);
206
+ return 0;
207
+ }
225
208
 
209
+ let installed = 0;
210
+ let failed = 0;
226
211
  for (const t of detected) {
227
212
  try {
228
213
  t.install(apiKey);
214
+ installed++;
215
+ void emitSetupClientResult(t.id, "installed");
229
216
  process.stdout.write(` ${teal("●")} installed for ${t.name}\n`);
230
217
  } catch (e) {
218
+ failed++;
219
+ void emitSetupClientResult(t.id, "failed", describeInstallError(e));
231
220
  const msg = e instanceof Error ? e.message : String(e);
232
221
  process.stdout.write(red(` failed for ${t.name}: ${msg}\n`));
233
222
  process.stdout.write(
@@ -235,6 +224,7 @@ export async function runSetup(): Promise<number> {
235
224
  );
236
225
  }
237
226
  }
227
+ void emitSetupFinished(installed, failed);
238
228
  if (isTelemetryDisabled()) {
239
229
  process.stdout.write(`\n ${dim("Telemetry off")}\n`);
240
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
  }