nixflex-mcp 0.5.0 → 0.5.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/call-reads.js CHANGED
@@ -1,43 +1,43 @@
1
- // GET-only compatibility adapter for installed SDK 0.8.0. Mutations stay unchanged.
2
- import * as z from 'zod/v4';
3
- import { NixflexConnectionError, errorFromResponse } from 'nixflex';
4
- import { summariseCall } from './call-tools.js';
5
- export const callListSchema = z.object({
6
- history: z.boolean().optional().describe('True: filtered metadata, totals and next_cursor. Default: legacy summary array.'),
7
- limit: z.number().int().min(1).max(200).optional(), offset: z.number().int().min(0).max(1000000).optional(),
8
- cursor: z.string().max(4096).optional(), agent_id: z.string().max(200).optional(), agent: z.string().max(200).optional(),
9
- number: z.string().max(80).optional(), search: z.string().max(120).optional(),
10
- direction: z.enum(['all','inbound','outbound','web']).optional(),
11
- outcome: z.enum(['all','successful','unsuccessful','unknown','failed']).optional(),
12
- source: z.enum(['all','campaign','web','test','other']).optional(),
13
- period: z.enum(['all','today','week','month']).optional(), since: z.string().max(40).optional(), until: z.string().max(40).optional()
14
- });
15
- export const callGetSchema = z.object({call_id:z.string().min(1).max(200),view:z.enum(['detail','recording']).optional()});
16
- export function callReads(apiKey, baseUrl='https://api.nixflex.com', fetcher=fetch) {
17
- async function get(path, params={}) {
18
- const url=new URL(baseUrl.replace(/\/+$/,'')+'/v1'+path);
19
- for(const [k,v] of Object.entries(params))if(v!==undefined)url.searchParams.set(k,String(v));
20
- let r,body;
21
- try{r=await fetcher(url.toString(),{method:'GET',redirect:'error',signal:AbortSignal.timeout(30000),headers:{Authorization:'Bearer '+apiKey,Accept:'application/json'}});}
22
- catch{throw new NixflexConnectionError('Could not read calls.');}
23
- try{body=await r.json();}catch{throw new NixflexConnectionError('Invalid call response.');}
24
- if(!r.ok)throw errorFromResponse(r.status,body,r.headers.get('x-railway-request-id')||undefined,Number(r.headers.get('retry-after'))||undefined);
25
- return body;
26
- }
27
- return {
28
- async list(args={}, summary=summariseCall) {
29
- const {history,agent_id,...params}=callListSchema.parse(args);
30
- if(agent_id!==undefined&&params.agent!==undefined)throw Error('Use agent or agent_id, not both.');
31
- if(agent_id!==undefined)params.agent=agent_id;
32
- const enhanced=history===true||Object.keys(params).some(k=>!['limit','offset'].includes(k));
33
- if(!enhanced){const rows=await get('/calls',params);if(!Array.isArray(rows))throw new NixflexConnectionError('Invalid call list.');return rows.map(summary);}
34
- const page=await get('/calls/history',params);
35
- if(!Array.isArray(page?.data)||!page.totals||typeof page.has_more!=='boolean')throw new NixflexConnectionError('Invalid call history.');
36
- return history===true?{...page,data:page.data.map(row=>({...summary(row),cost:row.cost,payload_deleted_at:row.payload_deleted_at??null}))}:page.data.map(summary);
37
- },
38
- async one(args) {
39
- const {call_id,view}=callGetSchema.parse(args),path='/calls/'+encodeURIComponent(call_id);
40
- return get(view&&view!=='detail'?path+'/'+view:path,view==='detail'?{view:'detail'}:{});
41
- }
42
- };
43
- }
1
+ // GET-only compatibility adapter for installed SDK 0.8.0. Mutations stay unchanged.
2
+ import * as z from 'zod/v4';
3
+ import { NixflexConnectionError, errorFromResponse } from 'nixflex';
4
+ import { summariseCall } from './call-tools.js';
5
+ export const callListSchema = z.object({
6
+ history: z.boolean().optional().describe('True: filtered metadata, totals and next_cursor. Default: legacy summary array.'),
7
+ limit: z.number().int().min(1).max(200).optional(), offset: z.number().int().min(0).max(1000000).optional(),
8
+ cursor: z.string().max(4096).optional(), agent_id: z.string().max(200).optional(), agent: z.string().max(200).optional(),
9
+ number: z.string().max(80).optional(), search: z.string().max(120).optional(),
10
+ direction: z.enum(['all','inbound','outbound','web']).optional(),
11
+ outcome: z.enum(['all','successful','unsuccessful','unknown','failed']).optional(),
12
+ source: z.enum(['all','campaign','web','test','other']).optional(),
13
+ period: z.enum(['all','today','week','month']).optional(), since: z.string().max(40).optional(), until: z.string().max(40).optional()
14
+ });
15
+ export const callGetSchema = z.object({call_id:z.string().min(1).max(200),view:z.enum(['detail','recording']).optional()});
16
+ export function callReads(apiKey, baseUrl='https://api.nixflex.com', fetcher=fetch) {
17
+ async function get(path, params={}) {
18
+ const url=new URL(baseUrl.replace(/\/+$/,'')+'/v1'+path);
19
+ for(const [k,v] of Object.entries(params))if(v!==undefined)url.searchParams.set(k,String(v));
20
+ let r,body;
21
+ try{r=await fetcher(url.toString(),{method:'GET',redirect:'error',signal:AbortSignal.timeout(30000),headers:{Authorization:'Bearer '+apiKey,Accept:'application/json'}});}
22
+ catch{throw new NixflexConnectionError('Could not read calls.');}
23
+ try{body=await r.json();}catch{throw new NixflexConnectionError('Invalid call response.');}
24
+ if(!r.ok)throw errorFromResponse(r.status,body,r.headers.get('x-railway-request-id')||undefined,Number(r.headers.get('retry-after'))||undefined);
25
+ return body;
26
+ }
27
+ return {
28
+ async list(args={}, summary=summariseCall) {
29
+ const {history,agent_id,...params}=callListSchema.parse(args);
30
+ if(agent_id!==undefined&&params.agent!==undefined)throw Error('Use agent or agent_id, not both.');
31
+ if(agent_id!==undefined)params.agent=agent_id;
32
+ const enhanced=history===true||Object.keys(params).some(k=>!['limit','offset'].includes(k));
33
+ if(!enhanced){const rows=await get('/calls',params);if(!Array.isArray(rows))throw new NixflexConnectionError('Invalid call list.');return rows.map(summary);}
34
+ const page=await get('/calls/history',params);
35
+ if(!Array.isArray(page?.data)||!page.totals||typeof page.has_more!=='boolean')throw new NixflexConnectionError('Invalid call history.');
36
+ return history===true?{...page,data:page.data.map(row=>({...summary(row),cost:row.cost,payload_deleted_at:row.payload_deleted_at??null}))}:page.data.map(summary);
37
+ },
38
+ async one(args) {
39
+ const {call_id,view}=callGetSchema.parse(args),path='/calls/'+encodeURIComponent(call_id);
40
+ return get(view&&view!=='detail'?path+'/'+view:path,view==='detail'?{view:'detail'}:{});
41
+ }
42
+ };
43
+ }
package/call-tools.js CHANGED
@@ -1,22 +1,22 @@
1
- // Translate the existing ergonomic tool argument, not the campaign recipient shape.
2
- export function createCallBody({ variables, ...body }) {
3
- if (variables !== undefined) {
4
- if (Object.hasOwn(body, 'dynamic_vars')) throw new Error('Use variables or dynamic_vars, not both.');
5
- body.dynamic_vars = variables;
6
- }
7
- return body;
8
- }
9
-
10
- export function summariseCall(c) {
11
- // Current API uses call_direction/call_type; retain older direction fallback.
12
- const direction = [c.call_direction, c.call_type, c.direction]
13
- .find(value => ['inbound', 'outbound', 'web'].includes(value)) ?? null;
14
- return {
15
- call_id: c.call_id, direction, from_number: c.from_number, to_number: c.to_number,
16
- agent_id: c.agent_id, call_status: c.call_status, ended_reason: c.ended_reason,
17
- duration_ms: c.duration_ms, started_at: c.start_timestamp ?? c.created_at ?? null,
18
- call_summary: c.call_summary, call_successful: c.call_successful,
19
- caller_sentiment: c.caller_sentiment,
20
- bookings: Array.isArray(c.bookings) ? c.bookings.length : null,
21
- };
22
- }
1
+ // Translate the existing ergonomic tool argument, not the campaign recipient shape.
2
+ export function createCallBody({ variables, ...body }) {
3
+ if (variables !== undefined) {
4
+ if (Object.hasOwn(body, 'dynamic_vars')) throw new Error('Use variables or dynamic_vars, not both.');
5
+ body.dynamic_vars = variables;
6
+ }
7
+ return body;
8
+ }
9
+
10
+ export function summariseCall(c) {
11
+ // Current API uses call_direction/call_type; retain older direction fallback.
12
+ const direction = [c.call_direction, c.call_type, c.direction]
13
+ .find(value => ['inbound', 'outbound', 'web'].includes(value)) ?? null;
14
+ return {
15
+ call_id: c.call_id, direction, from_number: c.from_number, to_number: c.to_number,
16
+ agent_id: c.agent_id, call_status: c.call_status, ended_reason: c.ended_reason,
17
+ duration_ms: c.duration_ms, started_at: c.start_timestamp ?? c.created_at ?? null,
18
+ call_summary: c.call_summary, call_successful: c.call_successful,
19
+ caller_sentiment: c.caller_sentiment,
20
+ bookings: Array.isArray(c.bookings) ? c.bookings.length : null,
21
+ };
22
+ }
@@ -1,38 +1,38 @@
1
- import * as z from 'zod/v4';
2
- const phone = z.string().regex(/^\+[1-9]\d{6,14}$/);
3
- export const contactLocation = {
4
- recipient_country: z.string().optional(), recipient_timezone: z.string().optional(),
5
- };
6
- const recipient = z.object({ phone, country: z.string().optional(), timezone: z.string().optional(),
7
- variables: z.record(z.string(), z.string()).optional(), prompt_override: z.string().optional() });
8
- const policy = {
9
- consent_confirmed: z.boolean().optional(), duplicate_policy: z.enum(['allow','warn','reject']).optional(),
10
- allow_wider_hours: z.boolean().optional(), hours_confirmation: z.string().min(20).max(1000).optional(),
11
- schedule_type: z.enum(['now','schedule']).optional(), scheduled_date: z.string().optional(),
12
- window_start_minutes: z.number().int().optional(), window_end_minutes: z.number().int().optional(),
13
- window_days: z.array(z.enum(['sun','mon','tue','wed','thu','fri','sat'])).optional(),
14
- timezone: z.string().optional(), skip_invalid: z.boolean().optional(),
15
- reply_window_hours: z.number().optional(), reply_context_prompt: z.string().optional(),
16
- };
17
- const common = { agent_id: z.string(), from_number: phone, name: z.string().optional(),
18
- recipients: z.array(recipient).min(1), ...policy, fields: z.record(z.string(), z.unknown()).optional() };
19
- export const voiceCampaignSchema = z.object({ ...common, prompt: z.string() });
20
- export const smsCampaignSchema = z.object({ ...common,
21
- message: z.string().optional().describe('Compatibility alias for message_template; provide only one.'),
22
- message_template: z.string().optional(),
23
- }).refine(a => (a.message !== undefined) !== (a.message_template !== undefined || a.fields?.message_template !== undefined),
24
- { message: 'Provide message or message_template, not both.' });
25
- export function campaignBody({ fields, ...rest }) {
26
- for (const key of Object.keys(fields || {})) if (rest[key] !== undefined)
27
- throw new Error('Use a top-level field or fields.' + key + ', not both.');
28
- const body = { ...rest, ...fields };
29
- if (body.message !== undefined) { body.message_template = body.message; delete body.message; }
30
- if (body.scheduled_at !== undefined) {
31
- if (body.scheduled_date !== undefined) throw new Error('Use scheduled_date only.');
32
- body.scheduled_date = body.scheduled_at; delete body.scheduled_at;
33
- }
34
- return body;
35
- }
36
- export const smsListSchema = z.object({status:z.string().optional(),limit:z.number().int().min(1).max(1000).optional(),before:z.string().optional()});
37
- export const smsDetailSchema = z.object({campaign_id:z.string(),limit:z.number().int().min(1).max(500).optional(),
38
- recipient_cursor:z.string().optional(),message_cursor:z.string().optional()});
1
+ import * as z from 'zod/v4';
2
+ const phone = z.string().regex(/^\+[1-9]\d{6,14}$/);
3
+ export const contactLocation = {
4
+ recipient_country: z.string().optional(), recipient_timezone: z.string().optional(),
5
+ };
6
+ const recipient = z.object({ phone, country: z.string().optional(), timezone: z.string().optional(),
7
+ variables: z.record(z.string(), z.string()).optional(), prompt_override: z.string().optional() });
8
+ const policy = {
9
+ consent_confirmed: z.boolean().optional(), duplicate_policy: z.enum(['allow','warn','reject']).optional(),
10
+ allow_wider_hours: z.boolean().optional(), hours_confirmation: z.string().min(20).max(1000).optional(),
11
+ schedule_type: z.enum(['now','schedule']).optional(), scheduled_date: z.string().optional(),
12
+ window_start_minutes: z.number().int().optional(), window_end_minutes: z.number().int().optional(),
13
+ window_days: z.array(z.enum(['sun','mon','tue','wed','thu','fri','sat'])).optional(),
14
+ timezone: z.string().optional(), skip_invalid: z.boolean().optional(),
15
+ reply_window_hours: z.number().optional(), reply_context_prompt: z.string().optional(),
16
+ };
17
+ const common = { agent_id: z.string(), from_number: phone, name: z.string().optional(),
18
+ recipients: z.array(recipient).min(1), ...policy, fields: z.record(z.string(), z.unknown()).optional() };
19
+ export const voiceCampaignSchema = z.object({ ...common, prompt: z.string() });
20
+ export const smsCampaignSchema = z.object({ ...common,
21
+ message: z.string().optional().describe('Compatibility alias for message_template; provide only one.'),
22
+ message_template: z.string().optional(),
23
+ }).refine(a => (a.message !== undefined) !== (a.message_template !== undefined || a.fields?.message_template !== undefined),
24
+ { message: 'Provide message or message_template, not both.' });
25
+ export function campaignBody({ fields, ...rest }) {
26
+ for (const key of Object.keys(fields || {})) if (rest[key] !== undefined)
27
+ throw new Error('Use a top-level field or fields.' + key + ', not both.');
28
+ const body = { ...rest, ...fields };
29
+ if (body.message !== undefined) { body.message_template = body.message; delete body.message; }
30
+ if (body.scheduled_at !== undefined) {
31
+ if (body.scheduled_date !== undefined) throw new Error('Use scheduled_date only.');
32
+ body.scheduled_date = body.scheduled_at; delete body.scheduled_at;
33
+ }
34
+ return body;
35
+ }
36
+ export const smsListSchema = z.object({status:z.string().optional(),limit:z.number().int().min(1).max(1000).optional(),before:z.string().optional()});
37
+ export const smsDetailSchema = z.object({campaign_id:z.string(),limit:z.number().int().min(1).max(500).optional(),
38
+ recipient_cursor:z.string().optional(),message_cursor:z.string().optional()});
package/core-tools.js CHANGED
@@ -1,36 +1,36 @@
1
- import * as z from 'zod/v4';
2
- import { executeTool, errorBody } from './safe-tools.js';
3
-
4
- /** Additive K2 tools. Existing registrations and their confirmation behaviour stay intact. */
5
- export function registerCoreTools(server, request) {
6
- const context = { agent_id: z.string().optional(), agent_language: z.string().optional() };
7
- const add = (name, title, description, read, schema, fn) => server.registerTool(name, {
8
- title, description: description + (read ? ' Use only when the user requests this account information.' :
9
- ' Use only for the user\'s explicitly requested change. Requires confirm:true; otherwise previews only. Never automatically repeat an uncertain write.'),
10
- inputSchema: schema,
11
- annotations: { title, readOnlyHint: read, destructiveHint: !read, idempotentHint: read, openWorldHint: true },
12
- }, async args => {
13
- try {
14
- const data = await executeTool(name, fn, args);
15
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
16
- } catch (error) {
17
- return { content: [{ type: 'text', text: JSON.stringify(errorBody(error)) }], isError: true };
18
- }
19
- });
20
- add('get_account_retention', 'Read account retention defaults',
21
- 'Read saved defaults for new agents. processing_enabled is not proof of erasure.', true,
22
- z.object({}), () => request('GET', '/account/retention'));
23
- add('get_key_activity', 'Read API request activity',
24
- 'Retained request counts and top endpoints, not organisation audit events. Defaults to today in UTC.', true,
25
- z.object({ period: z.enum(['today', '7d']).optional() }), args => request('GET', '/keys/activity', undefined, args));
26
- add('list_voices', 'List available catalog voices',
27
- 'Neutral voice keys and compatibility. Defaults limit 50/availability active; server clamps limit 1..100. locale is a preference. agent_language overrides agent_id. Keep filters with next_cursor; on cursor_expired restart and deduplicate by voice_key. No total count.', true,
28
- z.object({ ...context, language: z.string().optional(), gender: z.enum(['male', 'female', 'unknown']).optional(),
29
- locale: z.string().optional(), availability: z.enum(['active', 'all']).optional(),
30
- limit: z.number().int().optional(), cursor: z.string().optional() }),
31
- args => request('GET', '/voices', undefined, args));
32
- add('get_voice', 'Read one catalog voice',
33
- 'Read a voice by voice_key with optional agent compatibility. selectable:false is a valid result; missing preview does not mean unavailable.', true,
34
- z.object({ voice_key: z.string(), ...context }), ({ voice_key, ...query }) =>
35
- request('GET', '/voices/' + encodeURIComponent(voice_key), undefined, query));
36
- }
1
+ import * as z from 'zod/v4';
2
+ import { executeTool, errorBody } from './safe-tools.js';
3
+
4
+ /** Additive K2 tools. Existing registrations and their confirmation behaviour stay intact. */
5
+ export function registerCoreTools(server, request) {
6
+ const context = { agent_id: z.string().optional(), agent_language: z.string().optional() };
7
+ const add = (name, title, description, read, schema, fn) => server.registerTool(name, {
8
+ title, description: description + (read ? ' Use only when the user requests this account information.' :
9
+ ' Use only for the user\'s explicitly requested change. Requires confirm:true; otherwise previews only. Never automatically repeat an uncertain write.'),
10
+ inputSchema: schema,
11
+ annotations: { title, readOnlyHint: read, destructiveHint: !read, idempotentHint: read, openWorldHint: true },
12
+ }, async args => {
13
+ try {
14
+ const data = await executeTool(name, fn, args);
15
+ return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
16
+ } catch (error) {
17
+ return { content: [{ type: 'text', text: JSON.stringify(errorBody(error)) }], isError: true };
18
+ }
19
+ });
20
+ add('get_account_retention', 'Read account retention defaults',
21
+ 'Read saved defaults for new agents. processing_enabled is not proof of erasure.', true,
22
+ z.object({}), () => request('GET', '/account/retention'));
23
+ add('get_key_activity', 'Read API request activity',
24
+ 'Retained request counts and top endpoints, not organisation audit events. Defaults to today in UTC.', true,
25
+ z.object({ period: z.enum(['today', '7d']).optional() }), args => request('GET', '/keys/activity', undefined, args));
26
+ add('list_voices', 'List available catalog voices',
27
+ 'Neutral voice keys and compatibility. Defaults limit 50/availability active; server clamps limit 1..100. locale is a preference. agent_language overrides agent_id. Keep filters with next_cursor; on cursor_expired restart and deduplicate by voice_key. No total count.', true,
28
+ z.object({ ...context, language: z.string().optional(), gender: z.enum(['male', 'female', 'unknown']).optional(),
29
+ locale: z.string().optional(), availability: z.enum(['active', 'all']).optional(),
30
+ limit: z.number().int().optional(), cursor: z.string().optional() }),
31
+ args => request('GET', '/voices', undefined, args));
32
+ add('get_voice', 'Read one catalog voice',
33
+ 'Read a voice by voice_key with optional agent compatibility. selectable:false is a valid result; missing preview does not mean unavailable.', true,
34
+ z.object({ voice_key: z.string(), ...context }), ({ voice_key, ...query }) =>
35
+ request('GET', '/voices/' + encodeURIComponent(voice_key), undefined, query));
36
+ }
@@ -1,48 +1,48 @@
1
- // Shared installer/runtime policy. Keep byte-identical in MCP and CLI.
2
- import { readFileSync } from 'node:fs';
3
- import { homedir } from 'node:os';
4
- import { join, isAbsolute } from 'node:path';
5
- import { APPROVED_ORIGINS, approvedOrigin } from './origins.mjs';
6
- export { APPROVED_ORIGINS, approvedOrigin } from './origins.mjs';
7
- export function readLegacy(file, read = readFileSync) {
8
- let raw;
9
- try { raw = read(file, 'utf8'); }
10
- catch (error) {
11
- if (error.code === 'ENOENT') throw new Error('No MCP credentials. Use a full key and explicit API URL in the client environment, or an existing nixflex login file.');
12
- throw new Error('Cannot read the Nixflex credential file; no fallback was used.');
13
- }
14
- let cfg;
15
- try { cfg = JSON.parse(raw); } catch { throw new Error('Malformed Nixflex credential file; no fallback was used.'); }
16
- if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg))
17
- throw new Error('Invalid Nixflex credential file.');
18
- return cfg;
19
- }
20
- export function resolveConnection({ env = process.env, home = homedir(), read = readFileSync } = {}) {
21
- const source = env.NIXFLEX_CREDENTIAL_SOURCE || (env.NIXFLEX_API_KEY ? 'environment' : 'legacy');
22
- if (!['environment', 'legacy'].includes(source)) throw new Error('Invalid MCP credential source.');
23
- let key, baseUrl, configFile;
24
- if (source === 'environment') {
25
- if (env.NIXFLEX_PROFILE) throw new Error('Choose an environment pair or a legacy profile, not both.');
26
- if (!env.NIXFLEX_BASE_URL) throw new Error('NIXFLEX_BASE_URL is required with an environment key; no production default was used.');
27
- key = env.NIXFLEX_API_KEY;
28
- baseUrl = approvedOrigin(env.NIXFLEX_BASE_URL);
29
- } else {
30
- configFile = env.NIXFLEX_CONFIG_FILE || join(home, '.nixflex', 'config.json');
31
- if (!isAbsolute(configFile)) throw new Error('NIXFLEX_CONFIG_FILE must be an absolute path.');
32
- let cfg = readLegacy(configFile, read);
33
- if (env.NIXFLEX_PROFILE) {
34
- const name = env.NIXFLEX_PROFILE;
35
- if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name) || !cfg.profiles ||
36
- !Object.hasOwn(cfg.profiles, name) || !cfg.profiles[name]?.base_url)
37
- throw new Error('Legacy MCP profile missing or has no explicit API URL; no fallback was used.');
38
- cfg = cfg.profiles[name];
39
- }
40
- key = cfg.api_key;
41
- baseUrl = approvedOrigin(cfg.base_url === undefined ? APPROVED_ORIGINS[0] : cfg.base_url);
42
- if (env.NIXFLEX_BASE_URL && approvedOrigin(env.NIXFLEX_BASE_URL) !== baseUrl)
43
- throw new Error('MCP credential file destination changed or conflicts with this installation; refusing to retarget the key.');
44
- }
45
- if (typeof key !== 'string' || !/^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i.test(key))
46
- throw new Error('Missing or invalid full MCP API key. No request was sent.');
47
- return { key, baseUrl, source, configFile, profile: env.NIXFLEX_PROFILE };
48
- }
1
+ // Shared installer/runtime policy. Keep byte-identical in MCP and CLI.
2
+ import { readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, isAbsolute } from 'node:path';
5
+ import { APPROVED_ORIGINS, approvedOrigin } from './origins.mjs';
6
+ export { APPROVED_ORIGINS, approvedOrigin } from './origins.mjs';
7
+ export function readLegacy(file, read = readFileSync) {
8
+ let raw;
9
+ try { raw = read(file, 'utf8'); }
10
+ catch (error) {
11
+ if (error.code === 'ENOENT') throw new Error('No MCP credentials. Use a full key and explicit API URL in the client environment, or an existing nixflex login file.');
12
+ throw new Error('Cannot read the Nixflex credential file; no fallback was used.');
13
+ }
14
+ let cfg;
15
+ try { cfg = JSON.parse(raw); } catch { throw new Error('Malformed Nixflex credential file; no fallback was used.'); }
16
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg))
17
+ throw new Error('Invalid Nixflex credential file.');
18
+ return cfg;
19
+ }
20
+ export function resolveConnection({ env = process.env, home = homedir(), read = readFileSync } = {}) {
21
+ const source = env.NIXFLEX_CREDENTIAL_SOURCE || (env.NIXFLEX_API_KEY ? 'environment' : 'legacy');
22
+ if (!['environment', 'legacy'].includes(source)) throw new Error('Invalid MCP credential source.');
23
+ let key, baseUrl, configFile;
24
+ if (source === 'environment') {
25
+ if (env.NIXFLEX_PROFILE) throw new Error('Choose an environment pair or a legacy profile, not both.');
26
+ if (!env.NIXFLEX_BASE_URL) throw new Error('NIXFLEX_BASE_URL is required with an environment key; no production default was used.');
27
+ key = env.NIXFLEX_API_KEY;
28
+ baseUrl = approvedOrigin(env.NIXFLEX_BASE_URL);
29
+ } else {
30
+ configFile = env.NIXFLEX_CONFIG_FILE || join(home, '.nixflex', 'config.json');
31
+ if (!isAbsolute(configFile)) throw new Error('NIXFLEX_CONFIG_FILE must be an absolute path.');
32
+ let cfg = readLegacy(configFile, read);
33
+ if (env.NIXFLEX_PROFILE) {
34
+ const name = env.NIXFLEX_PROFILE;
35
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name) || !cfg.profiles ||
36
+ !Object.hasOwn(cfg.profiles, name) || !cfg.profiles[name]?.base_url)
37
+ throw new Error('Legacy MCP profile missing or has no explicit API URL; no fallback was used.');
38
+ cfg = cfg.profiles[name];
39
+ }
40
+ key = cfg.api_key;
41
+ baseUrl = approvedOrigin(cfg.base_url === undefined ? APPROVED_ORIGINS[0] : cfg.base_url);
42
+ if (env.NIXFLEX_BASE_URL && approvedOrigin(env.NIXFLEX_BASE_URL) !== baseUrl)
43
+ throw new Error('MCP credential file destination changed or conflicts with this installation; refusing to retarget the key.');
44
+ }
45
+ if (typeof key !== 'string' || !/^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i.test(key))
46
+ throw new Error('Missing or invalid full MCP API key. No request was sent.');
47
+ return { key, baseUrl, source, configFile, profile: env.NIXFLEX_PROFILE };
48
+ }
@@ -1,39 +1,39 @@
1
- // Shared, secret-free builders. Keep byte-identical in MCP and CLI.
2
- import { approvedOrigin } from './origins.mjs';
3
- export const SUPPORTED_CLIENTS = Object.freeze(['claude', 'claude-code', 'codex', 'cursor']);
4
- export function buildServerConfig({ client, platform, version, baseUrl, source = 'environment', configFile, profile }) {
5
- if (!SUPPORTED_CLIENTS.includes(client)) throw new Error('Supported tools: Claude Desktop, Claude Code, Codex and Cursor. VS Code setup is retired.');
6
- if (!['win32', 'darwin', 'linux'].includes(platform) || (client === 'claude' && platform === 'linux'))
7
- throw new Error('This client/platform combination is not supported.');
8
- if (typeof version !== 'string' || version !== version.trim() || !/^\d+\.\d+\.\d+$/.test(version)) throw new Error('MCP launch requires a fixed release version.');
9
- if (!['environment', 'legacy'].includes(source)) throw new Error('Invalid credential source.');
10
- const origin = approvedOrigin(baseUrl);
11
- const env = { NIXFLEX_CREDENTIAL_SOURCE: source, NIXFLEX_BASE_URL: origin };
12
- if (source === 'legacy') {
13
- if (typeof configFile !== 'string' || !configFile || /[\r\n]/.test(configFile)) throw new Error('Missing credential file path.');
14
- env.NIXFLEX_CONFIG_FILE = configFile;
15
- if (profile) {
16
- if (!/^[a-zA-Z0-9_-]{1,64}$/.test(profile)) throw new Error('Invalid profile name.');
17
- env.NIXFLEX_PROFILE = profile;
18
- }
19
- }
20
- const entry = platform === 'win32'
21
- ? { command: 'cmd.exe', args: ['/d', '/s', '/c', 'npx -y nixflex-mcp@' + version], env }
22
- : { command: 'npx', args: ['-y', 'nixflex-mcp@' + version], env };
23
- if (source === 'environment' && client === 'cursor') env.NIXFLEX_API_KEY = '${env:NIXFLEX_API_KEY}';
24
- if (source === 'environment' && client === 'codex') entry.env_vars = ['NIXFLEX_API_KEY'];
25
- return entry;
26
- }
27
- export function serverName(baseUrl) {
28
- return approvedOrigin(baseUrl) === 'https://api.nixflex.com' ? 'nixflex' : 'nixflex-staging';
29
- }
30
- export function configSnippet(options) {
31
- const entry = buildServerConfig(options), name = serverName(options.baseUrl);
32
- if (options.client !== 'codex') return JSON.stringify({ mcpServers: { [name]: entry } }, null, 2) + '\n';
33
- const lines = ['[mcp_servers.' + name + ']', 'command = ' + JSON.stringify(entry.command),
34
- 'args = ' + JSON.stringify(entry.args), 'startup_timeout_sec = 30'];
35
- if (entry.env_vars) lines.push('env_vars = ' + JSON.stringify(entry.env_vars));
36
- lines.push('', '[mcp_servers.' + name + '.env]');
37
- for (const [key, value] of Object.entries(entry.env)) lines.push(key + ' = ' + JSON.stringify(value));
38
- return lines.join('\n') + '\n';
39
- }
1
+ // Shared, secret-free builders. Keep byte-identical in MCP and CLI.
2
+ import { approvedOrigin } from './origins.mjs';
3
+ export const SUPPORTED_CLIENTS = Object.freeze(['claude', 'claude-code', 'codex', 'cursor']);
4
+ export function buildServerConfig({ client, platform, version, baseUrl, source = 'environment', configFile, profile }) {
5
+ if (!SUPPORTED_CLIENTS.includes(client)) throw new Error('Supported tools: Claude Desktop, Claude Code, Codex and Cursor. VS Code setup is retired.');
6
+ if (!['win32', 'darwin', 'linux'].includes(platform) || (client === 'claude' && platform === 'linux'))
7
+ throw new Error('This client/platform combination is not supported.');
8
+ if (typeof version !== 'string' || version !== version.trim() || !/^\d+\.\d+\.\d+$/.test(version)) throw new Error('MCP launch requires a fixed release version.');
9
+ if (!['environment', 'legacy'].includes(source)) throw new Error('Invalid credential source.');
10
+ const origin = approvedOrigin(baseUrl);
11
+ const env = { NIXFLEX_CREDENTIAL_SOURCE: source, NIXFLEX_BASE_URL: origin };
12
+ if (source === 'legacy') {
13
+ if (typeof configFile !== 'string' || !configFile || /[\r\n]/.test(configFile)) throw new Error('Missing credential file path.');
14
+ env.NIXFLEX_CONFIG_FILE = configFile;
15
+ if (profile) {
16
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(profile)) throw new Error('Invalid profile name.');
17
+ env.NIXFLEX_PROFILE = profile;
18
+ }
19
+ }
20
+ const entry = platform === 'win32'
21
+ ? { command: 'cmd.exe', args: ['/d', '/s', '/c', 'npx -y nixflex-mcp@' + version], env }
22
+ : { command: 'npx', args: ['-y', 'nixflex-mcp@' + version], env };
23
+ if (source === 'environment' && client === 'cursor') env.NIXFLEX_API_KEY = '${env:NIXFLEX_API_KEY}';
24
+ if (source === 'environment' && client === 'codex') entry.env_vars = ['NIXFLEX_API_KEY'];
25
+ return entry;
26
+ }
27
+ export function serverName(baseUrl) {
28
+ return approvedOrigin(baseUrl) === 'https://api.nixflex.com' ? 'nixflex' : 'nixflex-staging';
29
+ }
30
+ export function configSnippet(options) {
31
+ const entry = buildServerConfig(options), name = serverName(options.baseUrl);
32
+ if (options.client !== 'codex') return JSON.stringify({ mcpServers: { [name]: entry } }, null, 2) + '\n';
33
+ const lines = ['[mcp_servers.' + name + ']', 'command = ' + JSON.stringify(entry.command),
34
+ 'args = ' + JSON.stringify(entry.args), 'startup_timeout_sec = 30'];
35
+ if (entry.env_vars) lines.push('env_vars = ' + JSON.stringify(entry.env_vars));
36
+ lines.push('', '[mcp_servers.' + name + '.env]');
37
+ for (const [key, value] of Object.entries(entry.env)) lines.push(key + ' = ' + JSON.stringify(value));
38
+ return lines.join('\n') + '\n';
39
+ }
@@ -1,21 +1,21 @@
1
- // Isolated MCP process only: even the installed SDK must never follow redirects.
2
- export function installOriginFence(baseUrl, version) {
3
- const original = globalThis.fetch;
4
- globalThis.fetch = (input, options = {}) => {
5
- const target = new URL(typeof input === 'string' || input instanceof URL ? input : input.url);
6
- if (target.origin !== baseUrl || !target.pathname.startsWith('/v1/'))
7
- throw new Error('MCP request destination refused.');
8
- const headers = new Headers(options.headers);
9
- if (version) headers.set('User-Agent', 'nixflex-mcp/' + version);
10
- const signal = AbortSignal.any([AbortSignal.timeout(30000), ...(options.signal ? [options.signal] : [])]);
11
- return (async () => {
12
- const response = await original(input, { ...options, headers, signal, redirect: 'error' });
13
- // Also bound old SDK response-body reads, and bridge its legacy request-ID header.
14
- const bytes = response.status === 204 ? null : await response.arrayBuffer();
15
- const resultHeaders = new Headers(response.headers);
16
- if (resultHeaders.has('x-request-id')) resultHeaders.set('x-railway-request-id', resultHeaders.get('x-request-id'));
17
- return new Response(bytes, { status: response.status, statusText: response.statusText, headers: resultHeaders });
18
- })();
19
- };
20
- return () => { globalThis.fetch = original; };
21
- }
1
+ // Isolated MCP process only: even the installed SDK must never follow redirects.
2
+ export function installOriginFence(baseUrl, version) {
3
+ const original = globalThis.fetch;
4
+ globalThis.fetch = (input, options = {}) => {
5
+ const target = new URL(typeof input === 'string' || input instanceof URL ? input : input.url);
6
+ if (target.origin !== baseUrl || !target.pathname.startsWith('/v1/'))
7
+ throw new Error('MCP request destination refused.');
8
+ const headers = new Headers(options.headers);
9
+ if (version) headers.set('User-Agent', 'nixflex-mcp/' + version);
10
+ const signal = AbortSignal.any([AbortSignal.timeout(30000), ...(options.signal ? [options.signal] : [])]);
11
+ return (async () => {
12
+ const response = await original(input, { ...options, headers, signal, redirect: 'error' });
13
+ // Also bound old SDK response-body reads, and bridge its legacy request-ID header.
14
+ const bytes = response.status === 204 ? null : await response.arrayBuffer();
15
+ const resultHeaders = new Headers(response.headers);
16
+ if (resultHeaders.has('x-request-id')) resultHeaders.set('x-railway-request-id', resultHeaders.get('x-request-id'));
17
+ return new Response(bytes, { status: response.status, statusText: response.statusText, headers: resultHeaders });
18
+ })();
19
+ };
20
+ return () => { globalThis.fetch = original; };
21
+ }
@@ -1,15 +1,15 @@
1
- // Pure policy: safe to reuse in dashboard snippet generation (no Node imports).
2
- export const APPROVED_ORIGINS = Object.freeze([
3
- 'https://api.nixflex.com',
4
- 'https://nixflex-voice-engine-staging.up.railway.app',
5
- ]);
6
- export function approvedOrigin(value) {
7
- if (typeof value !== 'string' || value !== value.trim() || /[\\\s]/.test(value))
8
- throw new Error('MCP API destination must be an approved HTTPS Nixflex origin.');
9
- let url;
10
- try { url = new URL(value); } catch { throw new Error('Invalid MCP API destination.'); }
11
- if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
12
- !APPROVED_ORIGINS.includes(url.origin))
13
- throw new Error('MCP API destination must be an approved HTTPS Nixflex origin.');
14
- return url.origin;
15
- }
1
+ // Pure policy: safe to reuse in dashboard snippet generation (no Node imports).
2
+ export const APPROVED_ORIGINS = Object.freeze([
3
+ 'https://api.nixflex.com',
4
+ 'https://nixflex-voice-engine-staging.up.railway.app',
5
+ ]);
6
+ export function approvedOrigin(value) {
7
+ if (typeof value !== 'string' || value !== value.trim() || /[\\\s]/.test(value))
8
+ throw new Error('MCP API destination must be an approved HTTPS Nixflex origin.');
9
+ let url;
10
+ try { url = new URL(value); } catch { throw new Error('Invalid MCP API destination.'); }
11
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
12
+ !APPROVED_ORIGINS.includes(url.origin))
13
+ throw new Error('MCP API destination must be an approved HTTPS Nixflex origin.');
14
+ return url.origin;
15
+ }