@articul8/bivia-mcp 0.0.0-stage → 1.1.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.
package/server.js ADDED
@@ -0,0 +1,759 @@
1
+ #!/usr/bin/env node
2
+ // @articul8/bivia-mcp — Model Context Protocol server exposing the Bivia
3
+ // decision API as tools. Works in any MCP host (Claude Code, Codex,
4
+ // VS Code, …) over stdio via `npx -y @articul8/bivia-mcp`.
5
+ //
6
+ // 8 tools: bivia_boolean, bivia_choice, bivia_score, bivia_set, bivia_span,
7
+ // bivia_decide, bivia_ground, bivia_ds.
8
+ //
9
+ // Tools are always listable (no API key required to list). A missing
10
+ // A8_API_KEY only fails at call time with a clear, actionable message.
11
+
12
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
13
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14
+ import {
15
+ CallToolRequestSchema,
16
+ ListToolsRequestSchema,
17
+ } from "@modelcontextprotocol/sdk/types.js";
18
+
19
+ import Bivia, { APIError, APIConnectionError } from "@articul8/bivia";
20
+
21
+ import { formatAnswer, formatDistribution } from "./format.js";
22
+ import {
23
+ OAuthError,
24
+ resolveAuthConfig,
25
+ refreshCredentialsIfNeeded,
26
+ oauthLogin,
27
+ getAuthStatus,
28
+ describeAuthStatus,
29
+ saveApiKey,
30
+ maskKey,
31
+ clearCredentials,
32
+ credentialsPath,
33
+ SWITCH_ACCOUNT_NOTE,
34
+ loadCredentials,
35
+ cleanToken,
36
+ hasOAuthSession,
37
+ signupUrl,
38
+ openBrowserUrl,
39
+ isAllowedPlatformUrl,
40
+ } from "./oauth.js";
41
+ import { readFileSync } from "node:fs";
42
+ import { AsyncLocalStorage } from "node:async_hooks";
43
+
44
+ const PKG_NAME = "@articul8/bivia-mcp";
45
+ // read from package.json at run time, so a release bump shows up everywhere (MCP handshake, X-A8-Client-App)
46
+ const PKG_VERSION = (() => {
47
+ try { return JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version || "0.0.0"; } catch { return "0.0.0"; }
48
+ })();
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // The Bivia API, through @articul8/bivia.
52
+ // ---------------------------------------------------------------------------
53
+ class ToolError extends Error {
54
+ constructor(message, code) {
55
+ super(message);
56
+ this.code = code;
57
+ }
58
+ }
59
+
60
+ // Created on the first tool call (and recreated if the OAuth token refreshes),
61
+ // so a missing key does not stop the server from listing its tools.
62
+ let client = null;
63
+ let clientKey = "";
64
+ let clientBase = "";
65
+ let clientApp = "";
66
+
67
+ // Which app made the call (X-A8-Client-App). The gateway's allowlist names the editor this server runs in —
68
+ // mcp:claude-code, mcp:codex, mcp:cursor — so take it from the MCP handshake (clientInfo.name); until the
69
+ // editor has introduced itself, plain "mcp". Always "<name>/<this package's version>".
70
+ let CLIENT_APP = "mcp";
71
+ function mcpClientApp(name) {
72
+ const n = String(name || "").toLowerCase();
73
+ if (!n) return "mcp";
74
+ if (/claude[- ]?code/.test(n)) return "mcp:claude-code";
75
+ if (/codex/.test(n)) return "mcp:codex";
76
+ if (/cursor/.test(n)) return "mcp:cursor";
77
+ if (/claude[- ]?(ai|desktop)/.test(n)) return "mcp:claude-desktop";
78
+ if (/visual studio code|vscode|vs code/.test(n)) return "mcp:vscode";
79
+ if (/windsurf/.test(n)) return "mcp:windsurf";
80
+ const slug = n.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
81
+ return slug ? "mcp:" + slug : "mcp";
82
+ }
83
+
84
+ async function getAuthedClient() {
85
+ const auth = await resolveAuthConfig();
86
+ if (!auth.apiKey) {
87
+ throw new ToolError(
88
+ "No API key or OAuth session. Call the `bivia_login` tool, run `npx @articul8/bivia-mcp login`, or set A8_API_KEY in the environment.",
89
+ "no_api_key"
90
+ );
91
+ }
92
+ const base = auth.baseURL || "";
93
+ if (!client || clientKey !== auth.apiKey || clientBase !== base || clientApp !== CLIENT_APP) {
94
+ client = new Bivia({
95
+ apiKey: auth.apiKey,
96
+ baseURL: auth.baseURL || undefined,
97
+ maxRetries: 1, // a 503 is a cold start: retry once
98
+ // which app made the call; overrides the SDK's own bivia-node/<version>
99
+ defaultHeaders: { "X-A8-Client-App": `${CLIENT_APP}/${PKG_VERSION}` },
100
+ });
101
+ clientKey = auth.apiKey;
102
+ clientBase = base;
103
+ clientApp = CLIENT_APP;
104
+ }
105
+ return { client, source: auth.source };
106
+ }
107
+
108
+ // @articul8/bivia 1.0.0 ignores `defaultHeaders` (it sends only Authorization + Accept), so X-A8-Client-App
109
+ // never left this server. Add it to the SDK's own requests: fetch is wrapped once, and only calls made inside
110
+ // callBivia (which tags them through AsyncLocalStorage — safe with concurrent tool calls) get the header. If a
111
+ // later SDK sends the header itself, it is left as is.
112
+ const sdkCall = new AsyncLocalStorage();
113
+ const baseFetch = globalThis.fetch;
114
+ globalThis.fetch = (input, init = {}) => {
115
+ const tag = sdkCall.getStore();
116
+ if (!tag) return baseFetch(input, init);
117
+ const headers = new Headers(init.headers || {});
118
+ if (!headers.has("X-A8-Client-App")) headers.set("X-A8-Client-App", tag.clientApp);
119
+ return baseFetch(input, { ...init, headers });
120
+ };
121
+
122
+ async function callBivia(fn) {
123
+ const { client: c, source } = await getAuthedClient();
124
+ const run = (cl) => sdkCall.run({ clientApp: `${CLIENT_APP}/${PKG_VERSION}` }, () => fn(cl));
125
+ try {
126
+ return await run(c);
127
+ } catch (err) {
128
+ if (err instanceof APIError && err.status === 401 && source === "oauth") {
129
+ let refreshed = null;
130
+ try {
131
+ refreshed = await refreshCredentialsIfNeeded({ force: true });
132
+ } catch {
133
+ /* handled below */
134
+ }
135
+ if (refreshed && refreshed.access_token && refreshed.access_token !== clientKey) {
136
+ client = null;
137
+ const { client: retryClient } = await getAuthedClient();
138
+ return await run(retryClient);
139
+ }
140
+ // the sign-in can't be renewed (refresh token expired or revoked) — say what to do
141
+ throw new ToolError(
142
+ "Your Articul8 sign-in has expired. Call the `bivia_login` tool or run `npx @articul8/bivia-mcp login` to sign in again.",
143
+ "oauth_expired"
144
+ );
145
+ }
146
+ if (err instanceof APIError && err.status === 401 && KEY_SOURCES[source]) {
147
+ throw new ToolError(
148
+ `Bivia rejected the API key ${maskKey(clientKey)} (${KEY_SOURCES[source]}). ${KEY_FIXES[source]}`,
149
+ "api_key_rejected"
150
+ );
151
+ }
152
+ throw err;
153
+ }
154
+ }
155
+
156
+ // Where a key came from, for the "rejected" message.
157
+ const KEY_SOURCES = {
158
+ api_key: "saved with login --key",
159
+ env: "from the A8_API_KEY / BIVIA_API_KEY environment variable",
160
+ config: "the bivia CLI's key in ~/.bivia/config",
161
+ };
162
+ // An environment key wins over everything saved, so it has to be fixed where it is set.
163
+ const KEY_FIXES = {
164
+ api_key: "Replace it with `npx @articul8/bivia-mcp login --key <KEY>`, or call the `bivia_login` tool to sign in with Articul8.",
165
+ env: "Fix or unset A8_API_KEY / BIVIA_API_KEY in the MCP server's environment.",
166
+ config: "Replace it with `npx @articul8/bivia-mcp login --key <KEY>`, or call the `bivia_login` tool to sign in with Articul8.",
167
+ };
168
+
169
+ // platform_url in a tool call comes from the model: only an Articul8 address or the platform set in
170
+ // BIVIA_PLATFORM_URL, so a prompt cannot point the browser or the OAuth flow at another site.
171
+ function toolPlatformUrl(raw) {
172
+ if (!raw) return undefined;
173
+ if (!isAllowedPlatformUrl(raw)) {
174
+ throw new ToolError(
175
+ "platform_url must be an Articul8 address (https://*.articul8.ai). To use another platform, set BIVIA_PLATFORM_URL in the MCP server's environment.",
176
+ "invalid_platform_url"
177
+ );
178
+ }
179
+ return raw;
180
+ }
181
+
182
+ // Request defaults: fast mode, the model may abstain, and never think (think:true 500s).
183
+ const withDefaults = (body) => ({ domain: null, mode: "fast", allow_abstain: true, ...body, think: false });
184
+
185
+ // "Test", as in the browser extension popup: one real call with the active credential (and the same body).
186
+ const TEST_TEXT = {
187
+ ok: "OK",
188
+ key_rejected: "the API key was rejected",
189
+ sign_in_rejected: "the Articul8 sign-in was rejected; sign in again",
190
+ unauthenticated: "not signed in",
191
+ failed: "the test call failed",
192
+ };
193
+ // The same test call with a key that is not saved yet (login --key): the key itself, never renewed through
194
+ // the sign-in. Returns { ok } or { rejected, why } or { why }.
195
+ async function checkKey(key) {
196
+ const saved = loadCredentials();
197
+ const c = new Bivia({
198
+ apiKey: key,
199
+ baseURL: process.env.BIVIA_API_BASE || (saved && saved.api_base) || undefined,
200
+ maxRetries: 1,
201
+ defaultHeaders: { "X-A8-Client-App": `${CLIENT_APP}/${PKG_VERSION}` },
202
+ });
203
+ try {
204
+ await sdkCall.run({ clientApp: `${CLIENT_APP}/${PKG_VERSION}` }, () =>
205
+ c.decisions.boolean(withDefaults({ state: "ok", question: "Does the text say ok?" }))
206
+ );
207
+ return { ok: true };
208
+ } catch (err) {
209
+ const code = errorCode(err);
210
+ return { rejected: code === "http_401" || code === "http_403", why: code };
211
+ }
212
+ }
213
+
214
+ // Returns { test, test_error? }: test is a TEST_TEXT key; test_error keeps the error code of a failed call.
215
+ async function testConnection() {
216
+ try {
217
+ await callBivia((c) => c.decisions.boolean(withDefaults({ state: "ok", question: "Does the text say ok?" })));
218
+ return { test: "ok" };
219
+ } catch (err) {
220
+ const code = errorCode(err);
221
+ if (code === "api_key_rejected") return { test: "key_rejected" };
222
+ if (code === "oauth_expired") return { test: "sign_in_rejected" };
223
+ if (code === "no_api_key") return { test: "unauthenticated" };
224
+ if (code === "http_401" || code === "http_403") {
225
+ return { test: getAuthStatus().method === "oauth" ? "sign_in_rejected" : "key_rejected" };
226
+ }
227
+ return { test: "failed", test_error: code };
228
+ }
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Shared JSON-schema fragments.
233
+ // ---------------------------------------------------------------------------
234
+ const STATE = {
235
+ type: "string",
236
+ description:
237
+ "The situation/context as plain text (NOTE: a plain string). Optional for most endpoints.",
238
+ };
239
+ const QUESTION = {
240
+ type: "string",
241
+ description: "The question to decide. Required.",
242
+ };
243
+
244
+ // ---------------------------------------------------------------------------
245
+ // Tool definitions: { name, description, inputSchema (JSON Schema), run }.
246
+ // ---------------------------------------------------------------------------
247
+ const TOOLS = [
248
+ {
249
+ name: "bivia_boolean",
250
+ description:
251
+ "Ask Bivia a yes/no question and get a calibrated true/false with confidence. Use for binary decisions.",
252
+ inputSchema: {
253
+ type: "object",
254
+ properties: { state: STATE, question: QUESTION },
255
+ required: ["question"],
256
+ },
257
+ run: (a) =>
258
+ callBivia((c) =>
259
+ c.decisions.boolean(withDefaults({ state: a.state ?? "", question: a.question }))
260
+ ),
261
+ },
262
+ {
263
+ name: "bivia_choice",
264
+ description:
265
+ "Pick the single best option from a list of choices, with a calibrated distribution over all of them. Also drives optimization loops (choices = candidate actions).",
266
+ inputSchema: {
267
+ type: "object",
268
+ properties: {
269
+ state: STATE,
270
+ question: QUESTION,
271
+ choices: {
272
+ type: "array",
273
+ items: { type: "string" },
274
+ description: "The candidate options to choose from. Required.",
275
+ },
276
+ },
277
+ required: ["question", "choices"],
278
+ },
279
+ run: (a) =>
280
+ callBivia((c) =>
281
+ c.decisions.choice(
282
+ withDefaults({ state: a.state ?? "", question: a.question, choices: a.choices })
283
+ )
284
+ ),
285
+ },
286
+ {
287
+ name: "bivia_score",
288
+ description:
289
+ "Rate something on a numeric range (e.g. 0-10). Returns the chosen score and a per-bucket distribution.",
290
+ inputSchema: {
291
+ type: "object",
292
+ properties: {
293
+ state: STATE,
294
+ question: QUESTION,
295
+ range: {
296
+ type: "array",
297
+ items: { type: "number" },
298
+ minItems: 2,
299
+ maxItems: 2,
300
+ description: "[min, max] of the scoring range. Optional (defaults apply).",
301
+ },
302
+ },
303
+ required: ["question"],
304
+ },
305
+ run: (a) =>
306
+ callBivia((c) =>
307
+ c.decisions.score(
308
+ withDefaults({
309
+ state: a.state ?? "",
310
+ question: a.question,
311
+ buckets: 11,
312
+ ...(a.range ? { range: a.range } : {}),
313
+ })
314
+ )
315
+ ),
316
+ },
317
+ {
318
+ name: "bivia_set",
319
+ description:
320
+ "Pick the valid SUBSET of options (zero, one, or many may apply). Returns the chosen set and a distribution.",
321
+ inputSchema: {
322
+ type: "object",
323
+ properties: {
324
+ state: STATE,
325
+ question: QUESTION,
326
+ options: {
327
+ type: "array",
328
+ items: { type: "string" },
329
+ description: "The candidate options; any valid subset may be selected. Required.",
330
+ },
331
+ },
332
+ required: ["question", "options"],
333
+ },
334
+ run: (a) =>
335
+ callBivia((c) =>
336
+ c.decisions.multiSelect(
337
+ withDefaults({ state: a.state ?? "", question: a.question, options: a.options })
338
+ )
339
+ ),
340
+ },
341
+ {
342
+ name: "bivia_span",
343
+ description:
344
+ "Localize the text evidence that answers the question. Returns verbatim quotes with character offsets into `state`. `state` is required here.",
345
+ inputSchema: {
346
+ type: "object",
347
+ properties: {
348
+ state: {
349
+ type: "string",
350
+ description: "The text to find evidence in. REQUIRED for span.",
351
+ },
352
+ question: QUESTION,
353
+ },
354
+ required: ["state", "question"],
355
+ },
356
+ run: (a) =>
357
+ callBivia((c) =>
358
+ c.decisions.span(withDefaults({ state: a.state, question: a.question }))
359
+ ),
360
+ },
361
+ {
362
+ name: "bivia_decide",
363
+ description:
364
+ "Generic typed decision across arbitrary outcomes. Returns the chosen outcome and a distribution.",
365
+ inputSchema: {
366
+ type: "object",
367
+ properties: {
368
+ state: STATE,
369
+ question: QUESTION,
370
+ outcomes: {
371
+ type: "array",
372
+ items: { type: "string" },
373
+ description: "The candidate outcomes to decide among. Required.",
374
+ },
375
+ },
376
+ required: ["question", "outcomes"],
377
+ },
378
+ run: (a) =>
379
+ callBivia((c) =>
380
+ c.decisions.create(
381
+ withDefaults({ state: a.state ?? "", question: a.question, outcomes: a.outcomes })
382
+ )
383
+ ),
384
+ },
385
+ {
386
+ name: "bivia_ground",
387
+ description:
388
+ "Visual grounding: find and localize regions in an image. Returns labeled bounding boxes (coords normalized [0,1000]).",
389
+ inputSchema: {
390
+ type: "object",
391
+ properties: {
392
+ question: QUESTION,
393
+ image: {
394
+ type: "object",
395
+ description: "One image, by URL or base64.",
396
+ properties: {
397
+ url: { type: "string", description: "Image URL." },
398
+ b64: { type: "string", description: "Base64-encoded image bytes." },
399
+ mime: { type: "string", description: 'MIME type, e.g. "image/png".' },
400
+ },
401
+ },
402
+ },
403
+ required: ["question", "image"],
404
+ },
405
+ run: (a) =>
406
+ callBivia((c) =>
407
+ c.grounding.image(
408
+ withDefaults({ state: "", question: a.question, images: a.image ? [a.image] : [] })
409
+ )
410
+ ),
411
+ },
412
+ {
413
+ name: "bivia_ds",
414
+ description:
415
+ "Data-science / signal decision over numeric time-series. The host CPU profiler folds a data profile into state; you send raw numbers.",
416
+ inputSchema: {
417
+ type: "object",
418
+ properties: {
419
+ question: QUESTION,
420
+ signals: {
421
+ type: "array",
422
+ description:
423
+ 'Signals: [{ name, data:[channels][samples], fs?, dtype:"float32" }]. Required.',
424
+ items: { type: "object" },
425
+ },
426
+ options: {
427
+ type: "array",
428
+ items: { type: "string" },
429
+ description: "Candidate methods/answers. Required.",
430
+ },
431
+ kind: {
432
+ type: "string",
433
+ enum: ["choice", "set", "boolean"],
434
+ description: 'How to decide (default "choice").',
435
+ },
436
+ },
437
+ required: ["question", "signals", "options"],
438
+ },
439
+ run: (a) =>
440
+ callBivia((c) =>
441
+ c.data.decide(
442
+ withDefaults({
443
+ state: "",
444
+ question: a.question,
445
+ signals: a.signals,
446
+ options: a.options,
447
+ kind: a.kind ?? "choice",
448
+ })
449
+ )
450
+ ),
451
+ },
452
+ {
453
+ name: "bivia_login",
454
+ description:
455
+ "Sign in to Articul8 Bivia in your browser using OAuth 2.1 + PKCE, select your Tenant and Group scopes on the consent screen, and save credentials to ~/.bivia/credentials.json.",
456
+ inputSchema: {
457
+ type: "object",
458
+ properties: {
459
+ platform_url: {
460
+ type: "string",
461
+ description:
462
+ "Optional Articul8 platform URL: an https://*.articul8.ai address or the BIVIA_PLATFORM_URL value (defaults to BIVIA_PLATFORM_URL or https://app.articul8.ai).",
463
+ },
464
+ switch_account: {
465
+ type: "boolean",
466
+ description:
467
+ "Sign in again to pick another organization, tenant or group (or another account, after signing out of Articul8 in the browser).",
468
+ },
469
+ },
470
+ },
471
+ run: async (a) => {
472
+ const creds = await oauthLogin({
473
+ platformUrl: toolPlatformUrl(a.platform_url),
474
+ clientName: "Bivia MCP Server",
475
+ switchAccount: Boolean(a.switch_account),
476
+ });
477
+ client = null;
478
+ const signedIn = `Signed in to tenant ${creds.tenant_id || "default"} (group: ${creds.group_id || "default"}, permission: ${creds.permission || "write"})`;
479
+ return {
480
+ type: "auth",
481
+ status: "authenticated",
482
+ value: a.switch_account ? `${signedIn}. ${SWITCH_ACCOUNT_NOTE}` : signedIn,
483
+ tenant_id: creds.tenant_id,
484
+ group_id: creds.group_id,
485
+ group_ids: creds.group_ids,
486
+ permission: creds.permission,
487
+ scope: creds.scope,
488
+ };
489
+ },
490
+ },
491
+ {
492
+ name: "bivia_signup",
493
+ description:
494
+ "Create a free Articul8 account: opens the Articul8 sign-up page in the browser. Once the account exists, call bivia_login to sign in.",
495
+ inputSchema: {
496
+ type: "object",
497
+ properties: {
498
+ platform_url: {
499
+ type: "string",
500
+ description:
501
+ "Optional Articul8 platform URL: an https://*.articul8.ai address or the BIVIA_PLATFORM_URL value (defaults to BIVIA_PLATFORM_URL or https://app.articul8.ai).",
502
+ },
503
+ },
504
+ },
505
+ run: async (a) => {
506
+ if (hasOAuthSession()) {
507
+ throw new ToolError(
508
+ "Already signed in to Articul8. Call `bivia_login` with switch_account to use another organization or account.",
509
+ "already_signed_in"
510
+ );
511
+ }
512
+ const url = signupUrl(toolPlatformUrl(a.platform_url));
513
+ openBrowserUrl(url);
514
+ return {
515
+ type: "auth",
516
+ status: "signup_opened",
517
+ value: `Open the Articul8 sign-up page in your browser (opened automatically when this machine can): ${url} — once your account is ready, call bivia_login to sign in.`,
518
+ url,
519
+ };
520
+ },
521
+ },
522
+ {
523
+ name: "bivia_auth_status",
524
+ description:
525
+ "Check the active Articul8 Bivia authentication status: a sign-in (tenant, group, permission) or an API key (masked), and the endpoint. Set test to make one real call with it (a normal, billed Bivia call; use it when asked, not on every turn).",
526
+ inputSchema: {
527
+ type: "object",
528
+ properties: {
529
+ test: {
530
+ type: "boolean",
531
+ description: "Also make one real (billed) Bivia call to check the credential works.",
532
+ },
533
+ },
534
+ },
535
+ run: async (a) => {
536
+ const st = getAuthStatus();
537
+ const t = a.test ? await testConnection() : null;
538
+ const testText = t ? `. Test: ${TEST_TEXT[t.test]}${t.test_error ? ` (${t.test_error})` : ""}` : "";
539
+ return {
540
+ type: "auth",
541
+ status: st.authenticated ? "authenticated" : "unauthenticated",
542
+ value: describeAuthStatus(st) + testText,
543
+ ...st,
544
+ ...(t || {}),
545
+ };
546
+ },
547
+ },
548
+ ];
549
+
550
+ const TOOL_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
551
+
552
+ // ---------------------------------------------------------------------------
553
+ // Render a response envelope into MCP content (text + structured).
554
+ // ---------------------------------------------------------------------------
555
+ function renderResult(res) {
556
+ const lines = [formatAnswer(res)];
557
+ const dist = formatDistribution(res);
558
+ if (dist) lines.push("", "distribution:", dist);
559
+ if (res && res.status) lines.push("", `status: ${res.status}`);
560
+ return {
561
+ content: [{ type: "text", text: lines.join("\n") }],
562
+ structuredContent: res,
563
+ };
564
+ }
565
+
566
+ function errorCode(err) {
567
+ if (err instanceof APIConnectionError) return "network_error";
568
+ if (err instanceof APIError && err.status) return `http_${err.status}`;
569
+ if (err instanceof OAuthError && err.code) return err.code;
570
+ return (err && err.code) || "error";
571
+ }
572
+
573
+ function renderError(err) {
574
+ const code = errorCode(err);
575
+ const hint =
576
+ code === "no_api_key" || code === "api_key_rejected"
577
+ ? ""
578
+ : "\n(If this is a connectivity error, check your internet connection and BIVIA_API_BASE.)";
579
+ return {
580
+ isError: true,
581
+ content: [{ type: "text", text: `Bivia error [${code}]: ${err.message}${hint}` }],
582
+ };
583
+ }
584
+
585
+ // ---------------------------------------------------------------------------
586
+ // Wire up the stdio server & CLI auth subcommands.
587
+ // ---------------------------------------------------------------------------
588
+ const SERVER_INSTRUCTIONS = [
589
+ "Bivia is a calibrated decision engine. Use it when you need a structured, calibrated decision (with probabilities and honest abstention) rather than a free-form guess.",
590
+ "Tool selection: bivia_boolean (yes/no), bivia_choice (pick one from a list), bivia_score (numeric rating on a range), bivia_set (multi-select subset), bivia_span (exact supporting text offsets in state), bivia_decide (auto-detect type), bivia_ground (bounding boxes in an image), bivia_ds (raw numeric signals).",
591
+ "Always pass relevant context in `state` as plain text. When `status` is \"abstained\" (reported as \"unsure\"), do not fabricate a pick — gather more context or escalate to the user.",
592
+ "If a call reports missing credentials, guide the user to run `bivia_login` (or `bivia_signup` if they need an account) or set A8_API_KEY.",
593
+ ].join("\n");
594
+
595
+ const server = new Server(
596
+ { name: PKG_NAME, version: PKG_VERSION },
597
+ { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
598
+ );
599
+
600
+ // once the editor has introduced itself, every Bivia call names it (X-A8-Client-App: mcp:<editor>/<version>)
601
+ server.oninitialized = () => {
602
+ const info = server.getClientVersion();
603
+ CLIENT_APP = mcpClientApp(info && info.name);
604
+ };
605
+
606
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
607
+ tools: TOOLS.map(({ name, description, inputSchema }) => ({
608
+ name,
609
+ description,
610
+ inputSchema,
611
+ })),
612
+ }));
613
+
614
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
615
+ const { name, arguments: args = {} } = req.params;
616
+ const tool = TOOL_BY_NAME.get(name);
617
+ if (!tool) {
618
+ return renderError(new ToolError(`Unknown tool: ${name}`, "unknown_tool"));
619
+ }
620
+ try {
621
+ const res = await tool.run(args);
622
+ return renderResult(res);
623
+ } catch (err) {
624
+ return renderError(err);
625
+ }
626
+ });
627
+
628
+ async function browserLogin(platformUrl, switchAccount) {
629
+ console.error("Opening browser to sign in to Articul8 Bivia...");
630
+ const creds = await oauthLogin({
631
+ platformUrl: platformUrl || undefined,
632
+ clientName: "Bivia MCP Server",
633
+ switchAccount,
634
+ onAuthUrl: (url) => {
635
+ console.error(`If your browser does not open automatically, visit:\n ${url}\n`);
636
+ },
637
+ });
638
+ console.error(
639
+ `✓ Signed in to Articul8 (tenant: ${creds.tenant_id || "default"}, group: ${creds.group_id || "default"}, permission: ${creds.permission || "write"})`
640
+ );
641
+ console.error(`Credentials saved to ${credentialsPath()}`);
642
+ if (switchAccount) console.error(SWITCH_ACCOUNT_NOTE);
643
+ }
644
+
645
+ function waitForEnter(prompt) {
646
+ console.error(prompt);
647
+ return new Promise((resolve) => {
648
+ process.stdin.once("data", () => {
649
+ process.stdin.pause();
650
+ resolve();
651
+ });
652
+ });
653
+ }
654
+
655
+ // login --key. credentials.json is shared with the bivia CLI, which reads it first, so a key replaces a
656
+ // sign-in (or a saved key) only once one test call accepts it, or with --force: a mistyped or revoked key
657
+ // never destroys a working sign-in. With nothing to replace, the key is saved without a call. Same rule
658
+ // as `bivia key`.
659
+ async function saveKey(raw, force) {
660
+ const key = cleanToken(raw);
661
+ if (!key) throw new OAuthError("The API key is empty", "empty_api_key");
662
+ const current = loadCredentials();
663
+ const replacing = Boolean(current && current.access_token);
664
+ if (replacing && !force) {
665
+ const check = await checkKey(key);
666
+ if (!check.ok) {
667
+ console.error(
668
+ check.rejected
669
+ ? `Bivia rejected this key (${check.why}). Nothing changed: your current sign-in or key is kept.`
670
+ : `Could not check this key (${check.why}). Nothing changed: your current sign-in or key is kept.`
671
+ );
672
+ console.error("Check the key, or run `npx @articul8/bivia-mcp login --key <KEY> --force` to replace it anyway.");
673
+ process.exitCode = 1;
674
+ return;
675
+ }
676
+ }
677
+ saveApiKey(key);
678
+ console.error(`Saved API key to ${credentialsPath()}.`);
679
+ if (hasOAuthSession(current)) console.error(`It replaces the Articul8 sign-in (tenant ${current.tenant_id || "unknown"}).`);
680
+ else if (replacing) console.error("It replaces the key saved before.");
681
+ }
682
+
683
+ async function runCliCommand(argv) {
684
+ const cmd = argv[0];
685
+ if (cmd === "login") {
686
+ let platformUrl = "";
687
+ let manualKey = null;
688
+ let switchAccount = false;
689
+ let force = false;
690
+ for (let i = 1; i < argv.length; i++) {
691
+ if (argv[i] === "--platform" && argv[i + 1]) platformUrl = argv[++i];
692
+ // --key by presence: an empty or missing value is an error, never a fall-through to the browser login
693
+ else if (argv[i] === "--key") manualKey = argv[++i] ?? "";
694
+ else if (argv[i] === "--switch") switchAccount = true;
695
+ else if (argv[i] === "--force") force = true;
696
+ }
697
+ if (manualKey !== null) {
698
+ await saveKey(manualKey, force);
699
+ return true;
700
+ }
701
+ await browserLogin(platformUrl, switchAccount);
702
+ return true;
703
+ }
704
+ if (cmd === "signup") {
705
+ let platformUrl = "";
706
+ for (let i = 1; i < argv.length; i++) {
707
+ if (argv[i] === "--platform" && argv[i + 1]) platformUrl = argv[++i];
708
+ }
709
+ if (hasOAuthSession()) {
710
+ console.error("Already signed in to Articul8. Use `npx @articul8/bivia-mcp login --switch` to use another organization or account.");
711
+ process.exitCode = 1;
712
+ return true;
713
+ }
714
+ const url = signupUrl(platformUrl || undefined);
715
+ console.error(`Opening the Articul8 sign-up page:\n ${url}\n`);
716
+ openBrowserUrl(url);
717
+ if (!process.stdin.isTTY) {
718
+ console.error("Once your account is ready, run `npx @articul8/bivia-mcp login` to sign in.");
719
+ return true;
720
+ }
721
+ await waitForEnter("Press Enter once your account is ready to sign in...");
722
+ await browserLogin(platformUrl, false);
723
+ return true;
724
+ }
725
+ if (cmd === "logout") {
726
+ clearCredentials();
727
+ console.error("✓ Signed out and cleared ~/.bivia credentials.");
728
+ return true;
729
+ }
730
+ if (cmd === "status") {
731
+ const st = getAuthStatus();
732
+ if (argv.includes("--test")) {
733
+ Object.assign(st, await testConnection());
734
+ if (st.test !== "ok") process.exitCode = 1;
735
+ }
736
+ console.log(JSON.stringify(st, null, 2));
737
+ return true;
738
+ }
739
+ return false;
740
+ }
741
+
742
+ async function main() {
743
+ const argv = process.argv.slice(2);
744
+ if (argv.length > 0 && ["login", "signup", "logout", "status"].includes(argv[0])) {
745
+ await runCliCommand(argv);
746
+ return;
747
+ }
748
+ const transport = new StdioServerTransport();
749
+ await server.connect(transport);
750
+ // Logs go to stderr so they never corrupt the stdio JSON-RPC stream.
751
+ console.error(`${PKG_NAME} v${PKG_VERSION} running on stdio (${TOOLS.length} tools).`);
752
+ }
753
+
754
+ main().catch((err) => {
755
+ // an auth problem (timeout, denied consent, empty key, bad platform URL) is one line, not a stack trace
756
+ if (err instanceof OAuthError) console.error(`Error: ${err.message}`);
757
+ else console.error("Fatal:", err);
758
+ process.exit(1);
759
+ });