nixflex-mcp 0.3.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.
@@ -0,0 +1,51 @@
1
+ # K6 number features — 4 November 2026
2
+
3
+ Engine contract: deb63749acc74fe5d1d840dbf3589b2c40b5627e (B50/B50b/B51/B52). No engine changes. Public Cal.com methods remain unchanged.
4
+
5
+ | HTTP operation (number is URL-encoded E.164) | Node / CLI command | Python sync + async | MCP |
6
+ | --- | --- | --- | --- |
7
+ | POST /v1/integrations/google-calendar/number/{number}/connect | integrations.connectGoogleCalendar / integrations connectGoogleCalendar | integrations.connect_google_calendar | connect_google_calendar |
8
+ | GET /v1/integrations/google-calendar/number/{number} | integrations.getGoogleCalendar / integrations getGoogleCalendar | integrations.get_google_calendar | get_google_calendar |
9
+ | DELETE /v1/integrations/google-calendar/number/{number} | integrations.disconnectGoogleCalendar / integrations disconnectGoogleCalendar | integrations.disconnect_google_calendar | disconnect_google_calendar |
10
+ | PATCH /v1/integrations/google-calendar/number/{number} | integrations.updateGoogleCalendarSettings / integrations updateGoogleCalendarSettings | integrations.update_google_calendar_settings | update_google_calendar_settings |
11
+ | POST /v1/phone-numbers/{number}/credentials | phoneNumbers.updateCredentials / numbers updateCredentials | phone_numbers.update_credentials | update_phone_number_credentials |
12
+
13
+ ## Calendar contract
14
+
15
+ Connect sends only `{return_url}` and returns `{url, expires_at}`. A human opens the short-lived Google consent link; the kits never open a browser. It contains OAuth state, not access/refresh tokens: do not log or redistribute it. HTTPS return URLs must have no credentials, fragment, whitespace, backslash, localhost or OAuth code/state/token query parameters. Custom application schemes need the server's account allowlist.
16
+
17
+ After consent, the engine redirects with `status=connected&phone_number=...`, or `status=error&code=...`. Query status again; a redirect is not a substitute for checking current state. Links last ten minutes.
18
+
19
+ GET returns exactly `connected`, nullable `account_email`, `calendar_id`, nullable `connected_at`, `needs_reconnect`, `send_invites`. `connected:true` plus `needs_reconnect:true` needs new consent. The GET can refresh provider credentials inside the engine; it does not connect a new account or change calendar settings.
20
+
21
+ PATCH sends a nonempty subset of `timezone`, `hours`, `slot_minutes`, `calendar_id`, `send_invites`. Omitted fields preserve saved values. `send_invites` is a strict boolean; false is retained, absent stored value defaults true. It controls Google's invitation request, not delivery proof. `timezone` is an IANA name (max 100 chars). `slot_minutes` is 15, 30, 45 or 60. `calendar_id` is nonblank, max 1024, no whitespace/control characters; `primary` selects the main calendar.
22
+
23
+ When supplying `hours`, include all seven lowercase weekday names; each is null (closed) or `["09:00","17:00"]`. Times are HH:MM, close after open, no overnight interval. PATCH returns the five safe settings. DELETE returns `{ok:true,connected:false}`; remote revocation is best effort and may protect shared connections. Do not claim remote removal or recall already dispatched bookings.
24
+
25
+ SDK errors: `NixflexCalendarError`, `NixflexCredentialError`; inspect status/code, not raw text. All known engine codes remain exact. Private response details are replaced by safe messages. Unknown future codes become `request_failed`; a known uncertain write is never represented as success. Exported calendar codes include invalid_return_url, number_not_found, already_connected, booking_provider_conflict, not_connected, agent_not_assigned, invalid_settings, invalid_timezone, invalid_hours, invalid_slot_minutes, invalid_calendar_id, invalid_send_invites, calendar_unavailable, expired_link, not_configured, guard_unavailable. MCP returns a structured error with type/code/status and safe details.
26
+
27
+ ## Carrier details
28
+
29
+ Supply exactly `{twilio_sid,twilio_token}` OR `{telnyx_api_key,telnyx_connection_id}` for the number's current carrier; no provider field goes on the HTTP wire. The number, settings and history remain in place. This is a sensitive carrier routing change; Telnyx can require fresh verification. SDK callers supply the pair privately in memory. CLI uses the fixed environment names below or bounded JSON stdin; never credentials in arguments or files. MCP's schema accepts only phone_number, provider and confirm; it reads the selected pair privately from its process environment only AFTER confirmation. Never paste secrets into an assistant conversation.
30
+
31
+ - Twilio: NIXFLEX_TWILIO_SID + NIXFLEX_TWILIO_TOKEN.
32
+ - Telnyx: NIXFLEX_TELNYX_API_KEY + NIXFLEX_TELNYX_CONNECTION_ID.
33
+ - CLI/API authentication: NIXFLEX_API_KEY, separate from carrier credentials.
34
+
35
+ The only success output is `{phone_number,provider,updated:true}`. CLI writes require --confirm; MCP writes require confirm:true. Without it, zero requests and zero credential reads. A Desktop host must privately provide these environment variables to its server process; the bundle adds no secret input form. If it cannot, use the CLI/SDK instead. Missing private configuration returns credentials_not_configured and sends nothing.
36
+
37
+ Known errors: invalid_request, invalid_credentials, number_not_found, number_not_in_account, account_unavailable, carrier_mismatch, number_operation_pending, number_release_pending, carrier_unavailable, credential_update_unavailable, carrier_outcome_unknown, credential_save_pending. A safe UUID operation_id is retained when supplied; no input, response body, token or private URL is echoed.
38
+
39
+ `carrier_outcome_unknown`: routing is unconfirmed; contact support before retrying. `credential_save_pending`: carrier change is confirmed but database saving is pending; manually retry with EXACTLY the same details to finish saving. Never automatically repeat a write, including 429, 503, malformed success or lost connection. Uncertain writes carry safe_to_retry:false. SDK API keys retain normal owner/active checks; these clients cannot bypass the server's ownership/busy guards.
40
+
41
+ ## SMS suppression compatibility
42
+
43
+ New response: HTTP 409, type `conflict`, code `do_not_contact`. Node/Python raise NixflexDoNotContactError (a NixflexConflictError); MCP/CLI retain the structured status/type/code. The message was not sent. Stop: never remove suppression or retry to bypass it. Older servers may return 400 invalid_request; retain the application's legacy handling as well, but do not classify every 400 as suppression. There is no automatic SMS retry. Campaign holds remain separate.
44
+
45
+ ## Booking webhook model
46
+
47
+ Node/Python export Booking, CallCompletedBookingEvent and SmsBookingEvent. MCP ships bookingSchema, callCompletedBookingSchema and smsBookingSchema in k6-schemas.js (models, not extra tools). Verify the original raw-body webhook signature first using the existing verifier; these models do not authenticate a delivery.
48
+
49
+ Required booking keys: action (`created`/`rescheduled`/`cancelled`), booking_uid, start, end, attendee_name, attendee_email, service, timezone. Every field except action can be null; service can also be a string or number. Do not turn null into fabricated dates or attendee data. The flat call.completed event has bookings[], sms.booking has booking. Duplicate `already_exists` lookup is internal and is NOT a public booking mutation. Event models describe the booking part; other existing envelope fields remain available. No webhook receiver or listener is added.
50
+
51
+ See KIT-EXAMPLES-K6.md in the K6 handoff for all SDK/CLI/MCP examples. Live successful writes and human consent remain manual checks; offline tests use fakes only.
@@ -0,0 +1,14 @@
1
+ # Organisations in the main MCP server
2
+
3
+ K1 0.4.0 registers all nine tools in `nixflex-mcp`; no second install, process or key.
4
+ Remove the old optional `nixflex-organisations-mcp` configuration when adopting K1.
5
+ Reads: get_organisation, list_organisation_members, list_organisation_activity.
6
+ Changes: invite_organisation_member, resend_organisation_invite,
7
+ revoke_organisation_invite, remove_organisation_member,
8
+ update_organisation_member_role, claim_organisation_owner.
9
+ Every change still previews without `confirm: true`. Lost change responses never retry.
10
+ The same existing full API key and explicitly bound approved API URL are used.
11
+ An API key has Owner authority; it is not a restricted dashboard Member credential.
12
+ Removing a dashboard member does not revoke a key shared externally; the Owner must rotate it.
13
+ No personal acceptance, Leave, ownership transfer, account deletion or signing-secret tool.
14
+ The rebuilt Desktop bundles include these nine tools. They remain unpublished candidates.
package/README.md CHANGED
@@ -1,13 +1,40 @@
1
- # nixflex-mcp
2
-
3
- MCP server for the [Nixflex](https://nixflex.com) voice AI platform. Manage agents, calls, phone numbers and caller context from Claude Desktop, Cursor, VS Code or any MCP client.
4
-
5
- ```json
6
- { "mcpServers": { "nixflex": { "command": "npx", "args": ["-y", "nixflex-mcp"], "env": { "NIXFLEX_API_KEY": "nxf_xxx:nxfs_xxx" } } } }
7
- ```
8
-
9
- Or, with the Nixflex CLI installed: `nixflex mcp setup claude`.
10
-
11
- 35 tools: agents, calls, campaigns, numbers, caller context, SMS, webhooks, bring-your-own. Every destructive tool previews unless `confirm: true`.
12
-
13
- Docs: https://docs.nixflex.com/mcp/overview
1
+ # Nixflex MCP — 0.5.0 candidate
2
+ > **Building with AI?** Tell your assistant to read https://docs.nixflex.com/ai-rules.md first - the rules for building on Nixflex (safe defaults, costs, what to ask before acting). Full docs: https://docs.nixflex.com
3
+
4
+ B57 deletion and voice campaign delete: see [B57-DELETES.md](B57-DELETES.md). K9 is an unpublished candidate; one DELETE, never an automatic retry.
5
+
6
+ One install, Node 22+. Registered scope: 97 tools, including the 19 Knowledge reads/confirmed tests approved by Fahim on 2 November 2026. Legacy draft GET is excluded because it can normalize and SAVE an old draft.
7
+
8
+ Use the npm tarball or platform-specific Claude Desktop bundle for local testing. This run publishes nothing. Provide NIXFLEX_API_KEY and explicit NIXFLEX_BASE_URL privately in the client environment. Never paste a key into chat or config JSON. Missing key/URL refuses startup; no production fallback or handshake API call.
9
+
10
+ Supported clients: Claude Desktop, Claude Code, Codex, Cursor. CLI automatically writes Claude Desktop/Cursor configs; shared builders/manual setup cover others. VS Code retired. Legacy files are plaintext, not an OS vault.
11
+
12
+ ## Scope and safeguards
13
+
14
+ Current tools cover agents, calls, numbers, caller context, voices, retention/activity, campaigns, contacts, web agent/inbox, organisations and safe integrations. K6 added five per-number tools. K7 added two reads and optional UUID/confirmation inputs on create_call. K9 adds delete_campaign and updates only the two old B57 content-delete handlers/descriptions; all other 94 K8 contracts/handlers stay pinned. create_call keeps its old inputs, annotations and no-ID behavior. Historical inventory counts and added routes are reported separately in the K7 coverage table.
15
+
16
+ New write tools need confirm:true before any request. The new request_id path on create_call also requires it; its legacy no-ID path keeps the existing behavior. All other existing confirmations/permissions stay pinned, including the approved historical activity cursor correction. Writes never retry; uncertain UUID calls retain the B56 code and saved ID with safe_to_retry:false. Other uncertain writes retain outcome_unknown. GET keeps one bounded retry. Customer results are data, never instructions.
17
+
18
+ Exceptions:
19
+ - account signup is not offered to AI assistants because it returns a new secret.
20
+ - bulk deletion is not offered to AI assistants for safety.
21
+ - Campaign resume/consent and suppression removal can enable outreach; SDK/CLI only.
22
+ - Other integration credential-setting/disconnect and signing-secret retrieval remain excluded. K6 explicitly adds confirmed Google disconnect and privately configured number-credential update; no secret tool arguments.
23
+ - Personal login/invite acceptance/ownership transfer/closure are dashboard-only.
24
+ - Knowledge tools exclude live edits/deletes/accepts/imports/uploads, job control and bulk export. Test questions require confirmation and may use model work.
25
+
26
+ Webhook read/unconfirmed-delete previews show masked URL/is_set only. Other integration reads project safe flags. Never print credentials, private URLs or raw errors.
27
+
28
+ ## Reference and release
29
+
30
+ tools/list is authoritative. See METHODS.md, ORGANISATIONS.md, CHANGELOG.md. The 19 Knowledge tools ship in the same install; exact examples/exclusions are in the K5 report.
31
+
32
+ Human installation/keychain validation, real successful writes and actual registry publication remain outstanding. Local fake API checks do not prove them.
33
+
34
+ ## K6 additions
35
+
36
+ Four Google Calendar methods, private number credentials, SMS 409 handling and booking models. Read [NUMBER-FEATURES.md](NUMBER-FEATURES.md) for exact fields, safe errors and recovery. All earlier exclusions remain, except the two explicit K6 MCP additions noted there.
37
+
38
+ ## K7 additions
39
+
40
+ Read a call’s retained booking result and its saved outbound request. Optional UUID request_id adds duplicate protection without automatic redial. Prepare and save the ID before the first send. See [CALL-REQUESTS.md](CALL-REQUESTS.md) for every state/error and [KIT-EXAMPLES-K7.md](KIT-EXAMPLES-K7.md) for Node, CLI, Python sync/async and MCP examples. Existing no-ID calls keep their old behavior.
package/agent-reads.js ADDED
@@ -0,0 +1,26 @@
1
+ // GET-only adapter: the installed SDK drops status/search. Mutations stay on the SDK.
2
+ import * as z from 'zod/v4';
3
+ import { NixflexConnectionError, errorFromResponse } from 'nixflex';
4
+ export const agentListSchema = z.object({
5
+ limit: z.number().int().min(1).max(200).optional(),
6
+ offset: z.number().int().min(0).max(1000000).optional(),
7
+ status: z.enum(['active','disabled','all']).optional().describe('Default active; all includes disabled.'),
8
+ search: z.string().max(200).regex(/^[^\u0000-\u001f\u007f]*$/).optional().describe('Literal case-insensitive name or ID substring.')
9
+ });
10
+ export function agentReads(apiKey, baseUrl = 'https://api.nixflex.com', fetcher = fetch) {
11
+ return async function read(args = {}) {
12
+ const values = agentListSchema.parse(args);
13
+ const url = new URL(baseUrl.replace(/\/+$/, '') + '/v1/agents');
14
+ for (const [key, value] of Object.entries(values)) if (value !== undefined) url.searchParams.set(key, String(value));
15
+ let response, body;
16
+ try {
17
+ response = await fetcher(url.toString(), { method: 'GET', redirect: 'error', signal: AbortSignal.timeout(30000),
18
+ headers: { Authorization: 'Bearer ' + apiKey, Accept: 'application/json' } });
19
+ } catch { throw new NixflexConnectionError('Could not read agents.'); }
20
+ try { body = await response.json(); } catch { throw new NixflexConnectionError('Invalid agent list response.'); }
21
+ if (!response.ok) throw errorFromResponse(response.status, body, response.headers.get('x-railway-request-id') || undefined,
22
+ Number(response.headers.get('retry-after')) || undefined);
23
+ if (!Array.isArray(body)) throw new NixflexConnectionError('Invalid agent list response.');
24
+ return body;
25
+ };
26
+ }
@@ -0,0 +1,24 @@
1
+ import * as z from 'zod/v4';
2
+ // Do not strip unknown keys: the engine must return its mixed-key warnings.
3
+ const shape = {};
4
+ for (const key of 'name system_prompt welcome_message language timezone llm_model fallback_message post_call_sms_template'.split(' ')) shape[key] = z.string().optional();
5
+ for (const key of 'voice_id voice_key webhook_url phone_number transfer_number transfer_whisper boosted_keywords voicemail_message'.split(' ')) shape[key] = z.string().nullable().optional();
6
+ for (const key of 'is_active ai_speaks_first dynamic_greeting func_end_call func_cold_transfer func_send_sms record_call post_call_sms_enabled incall_sms_enabled amd_enabled greet_by_name remember_callers require_booking_confirmation voicemail_leave_enabled'.split(' ')) shape[key] = z.boolean().optional();
7
+ shape.temperature = z.number().min(0).max(0.7).optional();
8
+ shape.response_eagerness = z.number().int().min(0).max(1000).optional();
9
+ shape.stt_confidence = z.number().min(0).max(1).optional();
10
+ shape.stt_max_silence_ms = z.number().int().min(0).max(2147483647).optional();
11
+ shape.interruption_sensitivity = z.number().int().min(0).max(100).optional();
12
+ for (const key of ['max_call_duration_seconds', 'silence_hangup_seconds']) shape[key] = z.number().int().min(1).max(2147483).nullable().optional();
13
+ shape.wait_tag_seconds = z.number().int().min(30).max(120).nullable().optional();
14
+ shape.ivr_timeout_seconds = z.number().int().min(1).max(1800).optional();
15
+ shape.speaking_rate = z.union([z.number(), z.null(), z.literal('')]).optional();
16
+ shape.voice_speed = z.number().min(0.01).max(100).optional();
17
+ shape.pickup_delay = z.unknown().optional().describe('Legacy setting, unchanged in this release.');
18
+ shape.dtmf_enabled = z.boolean().nullable().optional();
19
+ shape.recording_source = z.string().nullable().optional().describe('provider/nixflex, case-normalized by the existing engine parser; null/empty clears to provider.');
20
+ shape.response_length = z.enum(['short', 'medium', 'long']).optional();
21
+ shape.transfer_type = z.enum(['cold', 'warm']).optional();
22
+ shape.data_extraction_fields = z.array(z.object({ name: z.string(), type: z.enum(['text', 'selector', 'boolean', 'number']), description: z.string().optional(), optional: z.boolean().optional(), format_example: z.string().optional(), choices: z.array(z.string()).optional() }).passthrough()).max(50).optional();
23
+ export const agentCreateFields = z.object(shape).passthrough().describe('Agent settings: temperature 0..0.7, SMS, voicemail, STT and extraction. Retention inherits the account default. The engine validates all values.');
24
+ export const agentUpdateFields = agentCreateFields.extend({ call_retention_days: z.union([z.literal(90), z.literal(30), z.literal(7), z.literal(1), z.literal(0)]).optional() });
package/c5-schemas.js ADDED
@@ -0,0 +1,17 @@
1
+ import * as z from 'zod/v4';
2
+ // Additive C5 schemas. Omission is preserved; no consent or server defaults are invented.
3
+ export const s97 = z.object({"status": z.string().optional(), "limit": z.number().int().min(1).max(200).optional()}).strict();
4
+ export const s91 = z.object({"id": z.string().min(1).max(100).regex(new RegExp("^[A-Za-z0-9_-]+$")), "confirm": z.boolean().optional()}).strict();
5
+ export const s179 = z.object({"id": z.string(), "body": z.object({"is_active": z.boolean().optional(), "reply_context_prompt": z.union([z.string(), z.null()]).optional(), "reply_window_hours": z.number().int().min(1).optional()}).strict().refine(v => Object.keys(v).length >= 1, "Supply at least one setting"), "confirm": z.boolean().optional()}).strict();
6
+ export const s180 = z.object({"id": z.string().min(1).max(100).regex(new RegExp("^[A-Za-z0-9_-]+$")), "confirm": z.boolean().optional()}).strict();
7
+ export const s98 = z.object({"agent_id": z.string().regex(new RegExp("^[A-Za-z0-9_-]{1,64}$")), "recipients": z.array(z.object({"phone": z.string().max(32), "country": z.string().max(2).optional(), "timezone": z.string().max(80).optional()}).strict()).min(1).max(20), "campaign": z.object({"allow_wider_hours": z.boolean().optional(), "start": z.string().regex(new RegExp("^(?:[01][0-9]|2[0-3]):[0-5][0-9]$")).optional(), "end": z.string().regex(new RegExp("^(?:[01][0-9]|2[0-3]):[0-5][0-9]$")).optional(), "days": z.array(z.enum(["sun", "mon", "tue", "wed", "thu", "fri", "sat"])).min(1).max(7).optional(), "scheduled_date": z.string().optional()}).passthrough().optional()}).strict();
8
+ export const s100 = z.object({"channel": z.enum(["all", "voice", "sms"]).optional(), "after": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$")).optional()}).strict();
9
+ export const s101 = z.object({"phone_numbers": z.array(z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$"))).min(1).max(1000), "channel": z.enum(["all", "voice", "sms"]).optional(), "confirm": z.boolean().optional()}).strict();
10
+ export const s58 = z.object({"number": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$"))}).strict();
11
+ export const s59 = z.object({"number": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$")), "body": z.object({"revision": z.string().regex(new RegExp("^[0-9]{1,18}$")), "settings": z.object({"web_prompt": z.string().max(16000).refine(v => v.length <= 16000, "Maximum 16000 UTF-16 code units").optional(), "web_design": z.number().int().min(1).max(10).optional(), "web_color": z.string().regex(new RegExp("^#[0-9a-fA-F]{6}$")).optional(), "web_name": z.string().max(80).optional(), "web_chips": z.string().max(323).optional(), "web_calls_enabled": z.boolean().optional(), "web_appearance": z.object({"version": z.literal(1), "launcher": z.string().regex(new RegExp("^[a-z][a-z0-9-]{0,31}$")), "window": z.enum(["compact", "side", "centre", "full"]), "visit": z.enum(["nothing", "greeting", "open"]), "theme": z.enum(["dark", "light"]), "colourMode": z.enum(["solid", "gradient"]), "colour": z.string().regex(new RegExp("^#[0-9a-fA-F]{6}$")), "colour2": z.string().regex(new RegExp("^#[0-9a-fA-F]{6}$")), "text": z.object({"greeting": z.string().max(500).optional(), "button": z.string().max(500).optional(), "title": z.string().max(500).optional(), "subtitle": z.string().max(500).optional(), "call": z.string().max(500).optional(), "chat": z.string().max(500).optional(), "welcome": z.string().max(500).optional(), "placeholder": z.string().max(500).optional(), "status": z.string().max(500).optional(), "send": z.string().max(500).optional(), "close": z.string().max(500).optional(), "footer": z.string().max(500).optional(), "typing": z.string().max(500).optional(), "error": z.string().max(500).optional(), "contact": z.string().max(500).optional(), "contactNote": z.string().max(500).optional(), "contactName": z.string().max(500).optional(), "contactPhone": z.string().max(500).optional(), "avatar": z.string().max(500).optional(), "voiceConnecting": z.string().max(500).optional(), "voicePrivacy": z.string().max(500).optional(), "voiceMute": z.string().max(500).optional(), "voiceUnmute": z.string().max(500).optional(), "voiceEnd": z.string().max(500).optional(), "voiceAllow": z.string().max(500).optional(), "voiceCancel": z.string().max(500).optional(), "voiceEnded": z.string().max(500).optional(), "voiceYouEnded": z.string().max(500).optional(), "voiceUnavailable": z.string().max(500).optional(), "voiceUnavailableNote": z.string().max(500).optional(), "voiceDisabled": z.string().max(500).optional(), "voiceInsecure": z.string().max(500).optional(), "voiceInsecureNote": z.string().max(500).optional(), "voicePermission": z.string().max(500).optional(), "voicePermissionNote": z.string().max(500).optional(), "voiceChecking": z.string().max(500).optional(), "voiceNeeded": z.string().max(500).optional(), "voiceBlocked": z.string().max(500).optional(), "voiceMissing": z.string().max(500).optional(), "voiceInUse": z.string().max(500).optional(), "voiceMicError": z.string().max(500).optional(), "voiceBusy": z.string().max(500).optional(), "voiceBusyNote": z.string().max(500).optional(), "voiceRinging": z.string().max(500).optional(), "voiceLive": z.string().max(500).optional(), "voiceError": z.string().max(500).optional(), "contactSave": z.string().max(500).optional(), "contactSavedEdit": z.string().max(500).optional(), "contactRequired": z.string().max(500).optional(), "beforeCallStart": z.string().max(500).optional(), "beforeCallCancel": z.string().max(500).optional()}).strict(), "contactFields": z.array(z.object({"id": z.string().regex(new RegExp("^(name|phone|email|order|custom_[1-5])$")), "label": z.string().min(1).max(60), "enabled": z.boolean(), "required": z.boolean(), "askInChat": z.boolean().optional()}).strict()).max(9).optional(), "beforeCall": z.object({"enabled": z.boolean(), "message": z.string().max(500), "fields": z.array(z.object({"id": z.string().regex(new RegExp("^(name|phone|email|order|custom_[1-5])$")), "required": z.boolean()}).strict()).max(9)}).strict().optional()}).strict().optional()}).strict().refine(v => Object.keys(v).length >= 1, "Supply at least one setting")}).strict(), "confirm": z.boolean().optional()}).strict();
12
+ export const s52 = z.object({"channel": z.enum(["sms", "web"]), "number": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$")), "archived": z.boolean().optional(), "unread": z.boolean().optional(), "search": z.string().max(160).optional(), "since": z.string().optional(), "period": z.enum(["all", "today", "7", "30", "90"]).optional(), "limit": z.number().int().min(1).max(100).optional(), "offset": z.number().int().min(0).max(10000).optional()}).strict();
13
+ export const s53 = z.object({"channel": z.enum(["sms", "web"]), "number": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$")), "thread": z.string().min(1).max(160), "limit": z.number().int().min(1).max(200).optional(), "before": z.string().optional(), "before_id": z.string().max(80).optional()}).strict();
14
+ export const s54 = z.object({"channel": z.enum(["sms", "web"]), "number": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$")), "thread": z.string().min(1).max(160), "body": z.object({"archived": z.boolean().optional(), "read_version": z.string().regex(new RegExp("^[0-9]{1,18}$")).optional()}).strict().refine(v => Object.keys(v).length >= 1, "Supply at least one setting"), "confirm": z.boolean().optional()}).strict();
15
+ export const s55 = z.object({}).strict();
16
+ export const s56 = z.object({"offset": z.number().int().min(0).max(10000).optional()}).strict();
17
+ export const s57 = z.object({"number": z.string().regex(new RegExp("^\\+[1-9][0-9]{6,14}$")).optional()}).strict();
package/c5-tools.js ADDED
@@ -0,0 +1,31 @@
1
+ import * as schemas from './c5-schemas.js';
2
+ import { executeTool, errorBody } from './safe-tools.js';
3
+
4
+ export function registerC5Tools(server, request) {
5
+ const enc = encodeURIComponent;
6
+ const add = (name, schema, description, read, fn) => server.registerTool(name, {
7
+ title: name.replaceAll('_', ' '), description: description + (read ? ' Use only when the user requests this information or advisory preview.' : ' Use only for the user\'s explicitly requested change. Requires confirm:true. Without confirmation sends zero requests. Never automatically repeat an uncertain write.'),
8
+ inputSchema: schema, annotations: { title: name.replaceAll('_', ' '), readOnlyHint: read, destructiveHint: !read, idempotentHint: read, openWorldHint: true },
9
+ }, async args => {
10
+ try {
11
+ const { confirm, ...input } = args;
12
+ const data = !read && confirm !== true ? { confirmation_required: true, sent: false, message: 'No request sent. Confirm only this intentional change.' } : await executeTool(name, fn, input);
13
+ return { content: [{ type: 'text', text: JSON.stringify(data) }] };
14
+ } catch (error) { return { isError: true, content: [{ type: 'text', text: JSON.stringify(errorBody(error)) }] }; }
15
+ });
16
+ add('list_campaigns', schemas.s97, "Default 50, cap 200; no cursor.", true, (query) => request('GET', `/campaigns`, undefined, query));
17
+ add('cancel_campaign', schemas.s91, "Stops future work; in-progress calls may finish.", false, ({ id, ...query }) => request('POST', `/calls/batch/${enc(id)}/cancel`, undefined, undefined));
18
+ add('update_sms_campaign', schemas.s179, "Changes reply settings only; does not cancel dispatch.", false, ({ id, ...query }) => request('PATCH', `/sms/campaigns/${enc(id)}`, query.body, undefined));
19
+ add('cancel_sms_campaign', schemas.s180, "Stops future work; in-progress sends may finish.", false, ({ id, ...query }) => request('POST', `/sms/campaigns/${enc(id)}/cancel`, undefined, undefined));
20
+ add('preview_contact_hours', schemas.s98, "Advisory only, expires after one minute. Never a permission token; POST is never automatically retried.", true, (query) => request('POST', `/contact-hours/preview`, query, undefined));
21
+ add('list_contact_suppressions', schemas.s100, "Fixed 200 rows; all is a separate bucket, not a union. Continue after next_cursor until null.", true, (query) => request('GET', `/contact-suppressions`, undefined, query));
22
+ add('add_contact_suppressions', schemas.s101, "Blocks contact for the explicit 1\u20131000 numbers; preserves locked opt-out evidence.", false, (query) => request('POST', `/contact-suppressions`, query, undefined));
23
+ add('get_web_agent', schemas.s58, "Read current revision before changing settings.", true, ({ number, ...query }) => request('GET', `/agent-web/${enc(number)}`, undefined, query));
24
+ add('update_web_agent', schemas.s59, "Revision is a string. Appearance is a COMPLETE replacement, not a merge. On conflict reload and compare; never retry the stale update.", false, ({ number, ...query }) => request('PATCH', `/agent-web/${enc(number)}`, query.body, undefined));
25
+ add('list_inbox_conversations', schemas.s52, "Reads do not mark messages read; unread_total counts conversations, not messages. since and period cannot be combined.", true, ({ channel, number, ...query }) => request('GET', `/agent-inbox/${enc(channel)}/${enc(number)}`, undefined, query));
26
+ add('get_inbox_thread', schemas.s53, "Before and before_id are paired; read_version covers the whole thread. Reading never acknowledges messages.", true, ({ channel, number, thread, ...query }) => request('GET', `/agent-inbox/${enc(channel)}/${enc(number)}/thread/${enc(thread)}`, undefined, query));
27
+ add('update_inbox_thread', schemas.s54, "Use the whole-thread string read_version; archive is not erasure.", false, ({ channel, number, thread, ...query }) => request('PATCH', `/agent-inbox/${enc(channel)}/${enc(number)}/thread/${enc(thread)}`, query.body, undefined));
28
+ add('get_inbox_features', schemas.s55, "Feature availability, not proof of database readiness.", true, (query) => request('GET', `/agent-inbox/features`, undefined, query));
29
+ add('list_inbox_numbers', schemas.s56, "Fixed 100 rows; agents capped at 1,000. No automatic pagination.", true, (query) => request('GET', `/agent-inbox/numbers`, undefined, query));
30
+ add('get_inbox_retention', schemas.s57, "Zero days means the next cleanup after reply. Archive does not change retention.", true, (query) => request('GET', `/agent-inbox/retention`, undefined, query));
31
+ }
package/c6-output.js ADDED
@@ -0,0 +1,32 @@
1
+ const allowed = new Set(['ok','phone_number','agent_id','provider','is_active','deleted','web_calls_enabled',
2
+ 'id','name','functions','method','timeout_ms','has_headers','is_set','api_key_set','webhook_url_set',
3
+ 'post_call_url_set','in_call_url_set','pit_set','username','event_slug','default_timezone','location_id','tags','tool_name']);
4
+ export function integrationOutput(value) {
5
+ if (Array.isArray(value)) return value.map(integrationOutput);
6
+ if (!value || typeof value !== 'object') return value;
7
+ const result = { private_fields_omitted: true };
8
+ for (const [key, item] of Object.entries(value)) {
9
+ if (/(?:^|_)url(?:_2)?$/.test(key)) result[key] = item == null ? null : '[omitted: private URL]';
10
+ else if (allowed.has(key)) result[key] = integrationOutput(item);
11
+ }
12
+ return result;
13
+ }
14
+ const codes = new Set(['invalid_filter','not_found','server_error','organisation_disabled','organisation_unavailable',
15
+ 'unauthorized','invalid_api_key','forbidden','rate_limit_exceeded','owner_required','outcome_unknown','invalid_business_name']);
16
+ export function privateError(error) {
17
+ const unknown = error?.code === 'outcome_unknown';
18
+ return { error: { code: codes.has(error?.code) ? error.code : 'request_failed',
19
+ status: Number.isInteger(error?.status) && error.status >= 0 && error.status <= 599 ? error.status : 0,
20
+ message: unknown ? 'Outcome unknown. Check current state before retrying.' : 'Request failed. Private error details omitted.',
21
+ ...(unknown ? { outcome: 'unknown', safe_to_retry: false } : {}) } };
22
+ }
23
+ /** Approved success-output change only. Preserve errors, retries and all other fields. */
24
+ export async function privateWebhookRead(action) {
25
+ const value = await action();
26
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
27
+ const result = { ...value };
28
+ for (const field of ['webhook_url', 'webhook_url_2']) {
29
+ if (Object.hasOwn(result, field) && result[field] !== null) result[field] = '[omitted: private URL]';
30
+ }
31
+ return result;
32
+ }
package/c6-tools.js ADDED
@@ -0,0 +1,35 @@
1
+ import * as z from 'zod/v4';
2
+ import { executeTool } from './safe-tools.js';
3
+ import { integrationOutput, privateError } from './c6-output.js';
4
+
5
+ /** K4 scope approved by Fahim, 2 November 2026. */
6
+ export function registerC6Tools(server, request) {
7
+ const number = z.string().regex(/^\+[1-9]\d{6,14}$/);
8
+ const identity = z.object({ phone_number: number });
9
+ const agent = z.object({ agent_id: z.string().min(1).max(200) });
10
+ const enc = encodeURIComponent;
11
+ const add = (name, schema, description, read, fn, project = value => value) => server.registerTool(name, {
12
+ title: name.replaceAll('_', ' '), description: description + (read ? ' Use only for information the user requests.' : " Use only for the user's explicitly requested change. Requires confirm:true before any request; never automatically repeat an uncertain change."),
13
+ inputSchema: schema, annotations: { title: name.replaceAll('_', ' '), readOnlyHint: read, destructiveHint: !read, idempotentHint: read, openWorldHint: true },
14
+ }, async args => {
15
+ try {
16
+ const { confirm, ...input } = args;
17
+ const data = !read && confirm !== true ? { confirmation_required: true, sent: false, message: 'No request sent. Confirm only this intentional change.' } : project(await executeTool(name, fn, input));
18
+ return { content: [{ type: 'text', text: JSON.stringify(data) }] };
19
+ } catch (error) { return { isError: true, content: [{ type: 'text', text: JSON.stringify(privateError(error)) }] }; }
20
+ });
21
+ for (const [provider, name] of [['calcom','get_calcom'],['slack','get_slack'],['zapier','get_zapier'],['make','get_make'],['gohighlevel','get_gohighlevel'],['web-calls','get_number_web_calls'],['precall','get_number_precall']]) {
22
+ add(name, identity, 'Read saved '+provider+' settings on an owned number. Credentials, private URLs and free-form configuration are omitted. Saved flags do not prove effective availability; a missing config may return 404.', true,
23
+ ({ phone_number }) => request('GET', `/integrations/${provider}/number/${enc(phone_number)}`), integrationOutput);
24
+ }
25
+ add('get_agent_precall', agent, 'Read the saved agent pre-call default. Private URL omitted. A number override takes precedence.', true,
26
+ ({ agent_id }) => request('GET', `/integrations/precall/agent/${enc(agent_id)}`), integrationOutput);
27
+ add('list_custom_functions', identity, 'List at most 15 saved functions. No paging. Empty does not prove number ownership. URLs, private headers, schemas and free-form text are omitted.', true,
28
+ ({ phone_number }) => request('GET', `/integrations/custom-functions/number/${enc(phone_number)}`), integrationOutput);
29
+ add('list_organisation_activity_filtered', z.object({ before: z.string().regex(/^\d{1,18}$/).optional(), actor: z.uuid().optional(), from: z.iso.date().optional(), to: z.iso.date().optional() }),
30
+ 'Read up to 50 activity events using inclusive UTC dates within retained history. Keep IDs and next_cursor as strings; pass next_cursor as before. API key has Owner authority. Full CSV export is SDK/CLI only.', true,
31
+ query => request('GET', '/organisation/activity', undefined, query));
32
+ add('rename_organisation', z.object({ name: z.string().min(2).max(100).regex(/^[^\u0000-\u001f\u007f]+$/), confirm: z.boolean().optional() }),
33
+ 'Change only the business name. API key has Owner authority; no membership or ownership transfer.', false,
34
+ body => request('PATCH', '/organisation/name', body));
35
+ }
package/call-reads.js ADDED
@@ -0,0 +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
+ }
package/call-tools.js ADDED
@@ -0,0 +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
+ }
@@ -0,0 +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()});
package/core-tools.js ADDED
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }