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,44 @@
1
+ // Presentation only: never changes tool inputs, outputs, dispatch or authorization.
2
+ const TITLES = Object.freeze({
3
+ get_usage: 'Read account usage and balance',
4
+ rotate_api_key: 'Replace the API secret',
5
+ list_agents: 'List agents', get_agent: 'Read one agent',
6
+ create_agent: 'Create an agent', update_agent: 'Update an agent', delete_agent: 'Disable an agent',
7
+ create_call: 'Place a paid phone call', list_calls: 'List call summaries',
8
+ get_call: 'Read one full call', delete_call: 'Delete one call and recording',
9
+ create_campaign: 'Create a voice campaign', launch_campaign: 'Launch a paid voice campaign',
10
+ list_phone_numbers: 'Read phone numbers and usage', import_phone_number: 'Connect a carrier number',
11
+ update_phone_number: 'Update or move a phone number', delete_phone_number: 'Disconnect a phone number',
12
+ set_number_monitor: 'Change live-monitor eligibility', set_number_web_calls: 'Enable or disable website calls',
13
+ get_caller_context: 'Read a caller record', set_caller_context: 'Update a caller record',
14
+ import_caller_context: 'Import caller records', delete_caller_context: 'Erase one caller record',
15
+ send_sms: 'Send a paid text message', create_sms_campaign: 'Create an SMS campaign',
16
+ launch_sms_campaign: 'Launch a paid SMS campaign', list_sms_campaigns: 'List SMS campaigns',
17
+ get_sms_campaign: 'Read one SMS campaign', delete_sms_campaign: 'Delete an SMS campaign',
18
+ set_webhook: 'Set a post-call webhook', get_webhook: 'Read a webhook setting',
19
+ delete_webhook: 'Remove a webhook', get_byo_config: 'Read own-provider settings',
20
+ set_byo_config: 'Connect own storage or AI provider', delete_byo_config: 'Disconnect own storage or AI provider',
21
+ });
22
+ const READS = new Set(['get_usage', 'list_agents', 'get_agent', 'list_calls', 'get_call',
23
+ 'list_phone_numbers', 'get_caller_context', 'list_sms_campaigns', 'get_sms_campaign', 'get_webhook', 'get_byo_config']);
24
+ const DETAILS = Object.freeze({
25
+ rotate_api_key: 'Replace the API secret. The current secret stops working immediately; every integration must be updated. The response can contain the replacement secret, visible to the chat client. Prefer the dashboard for rotation. Requires confirm: true; otherwise returns a preview.',
26
+ set_byo_config: 'Connect your own storage bucket, LLM endpoint or TTS provider. The API verifies the connection with a real probe before saving; provider charges may apply. Changes affect future service behaviour.',
27
+ launch_campaign: 'Request launch of an existing voice campaign; scheduling and recipient-local contact-hour gates still apply before dialling. SPENDS account credit and carrier charges may apply. Only launch the campaign the user explicitly approved.',
28
+ launch_sms_campaign: 'Request launch of an existing SMS campaign; scheduling and recipient-local contact-hour gates still apply before sending. SPENDS credit and carrier charges may apply. Only launch the campaign the user explicitly approved.',
29
+ delete_call: 'Request deletion of one call record and its tracked recording. Busy or unsettled work can refuse deletion; use the actual API result, never claim success from the request alone. Requires confirm: true; otherwise returns a preview.',
30
+ });
31
+ export function toolMetadata(name, originalDescription) {
32
+ const title = TITLES[name];
33
+ if (!title) throw new Error('Missing reviewed metadata for tool: ' + name);
34
+ const read = READS.has(name);
35
+ let description = DETAILS[name] || originalDescription;
36
+ description += read ? ' Use only when the user requests this account information.'
37
+ : ' Use only for the user\'s explicitly requested change. Check uncertain outcomes before retrying.';
38
+ if (name === 'set_caller_context' || name === 'import_caller_context')
39
+ description += ' Save only caller data explicitly supplied for this purpose; do not extract Claude memory or conversation history to build profiles.';
40
+ if (name === 'import_phone_number' || name === 'set_byo_config')
41
+ description += ' Credential fields are sensitive: prefer the Nixflex dashboard for initial credential setup; never ask users to paste secrets into chat.';
42
+ return { title, description, annotations: { title, readOnlyHint: read,
43
+ destructiveHint: !read, idempotentHint: read, openWorldHint: true } };
44
+ }
package/index.js CHANGED
@@ -1,159 +1,165 @@
1
- #!/usr/bin/env node
2
- // ============================================
3
- // nixflex-mcp - the Nixflex MCP server (stdio).
4
- //
5
- // Claude Desktop / Cursor / VS Code: nixflex mcp setup claude (needs `nixflex login` first)
6
- // or by hand:
7
- // { "mcpServers": { "nixflex": { "command": "npx", "args": ["-y", "nixflex-mcp"] } } }
8
- //
9
- // ONE DOOR: every tool is a call into the official `nixflex` SDK - the same code the CLI
10
- // and the docs use, so a tool can never do something the API does not. Coverage mirrors
11
- // the CLI 1:1; tests/tools.test.mjs pins the tool count.
12
- // STDIO RULE: never write to stdout. stdout IS the protocol. All logging goes to stderr.
13
- // SAFETY: every destructive tool requires confirm: true and returns a preview otherwise.
14
- // There is no delete-all tool. Spending tools (create_call, create_campaign, send_sms,
15
- // create_sms_campaign) say so in their description and need every field spelled out.
16
- // GENERIC FIELDS: update/create tools take a `fields` object passed straight to the API,
17
- // so a new API field needs no server update (same rule as the CLI's --set).
18
- // LISTS ARE SUMMARIES: list_calls strips transcripts and analysis - use get_call for one
19
- // call in full. Full transcripts in a list blew the context in the first live audit.
20
- // ============================================
21
- import { McpServer } from '@modelcontextprotocol/server';
22
- import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
23
- import * as z from 'zod/v4';
24
- import Nixflex, { NixflexError } from 'nixflex';
25
- import { readFileSync } from 'node:fs';
26
- import { homedir } from 'node:os';
27
- import { join } from 'node:path';
28
-
29
- const VERSION = '0.2.1';
30
- const log = (...a) => process.stderr.write('[nixflex-mcp] ' + a.join(' ') + '\n');
31
-
32
- // ---- key: env first, then the CLI's config file (so `nixflex login` is enough) ----
33
- function resolveKey() {
34
- if (process.env.NIXFLEX_API_KEY) return process.env.NIXFLEX_API_KEY;
35
- try { return JSON.parse(readFileSync(join(homedir(), '.nixflex', 'config.json'), 'utf8')).api_key; } catch { return undefined; }
36
- }
37
- const key = resolveKey();
38
- if (!key || !/^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i.test(key)) {
39
- log('No API key. Run `nixflex login`, or set NIXFLEX_API_KEY (nxf_xxx:nxfs_xxx) in the server env.');
40
- process.exit(2);
41
- }
42
- const client = new Nixflex({ apiKey: key, baseUrl: process.env.NIXFLEX_BASE_URL });
43
-
44
- // ---- helpers ----
45
- const text = (data) => ({ content: [{ type: 'text', text: typeof data === 'string' ? data : JSON.stringify(data, null, 2) }] });
46
- const fail = (e) => {
47
- const body = e instanceof NixflexError
48
- ? { error: { code: e.code, status: e.status, message: e.message, doc_url: e.docUrl } }
49
- : { error: { message: String((e && e.message) || e) } };
50
- return { content: [{ type: 'text', text: JSON.stringify(body, null, 2) }], isError: true };
51
- };
52
- const run = (fn) => async (args) => { try { return text(await fn(args || {})); } catch (e) { return fail(e); } };
53
- const E164 = z.string().regex(/^\+[1-9]\d{6,14}$/, 'E.164 number, e.g. +447700900123');
54
- const fields = z.record(z.string(), z.unknown()).describe('Any fields the API accepts, passed as-is. Unknown names are rejected by the API, never dropped silently.');
55
- const confirmArg = z.boolean().optional().describe('Required true to actually do it. Without it the tool returns a preview and changes nothing.');
56
- const preview = async (what, fetch) => { let current = null; try { current = await fetch(); } catch { /* preview */ } return { would_delete: what, current, hint: 'Call again with confirm: true.' }; };
57
- const summariseCall = (c) => ({ call_id: c.call_id, direction: c.direction, from_number: c.from_number, to_number: c.to_number, agent_id: c.agent_id, call_status: c.call_status, ended_reason: c.ended_reason, duration_ms: c.duration_ms, started_at: c.start_timestamp || c.created_at, call_summary: c.call_summary, call_successful: c.call_successful, caller_sentiment: c.caller_sentiment, bookings: Array.isArray(c.bookings) ? c.bookings.length : undefined });
58
-
59
- const server = new McpServer({ name: 'nixflex', version: VERSION });
60
- // Annotations are HINTS for clients (Claude asks before destructive tools) - never a
61
- // security control. Rule: name starts with get_/list_ -> read-only; delete_/rotate_ ->
62
- // destructive; everything else writes but is not destructive.
63
- const annotate = (name) => name.startsWith('get_') || name.startsWith('list_')
64
- ? { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
65
- : (name.startsWith('delete_') || name.startsWith('rotate_'))
66
- ? { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
67
- : { readOnlyHint: false, destructiveHint: false, idempotentHint: false };
68
- const T = (name, description, schema, fn) => server.registerTool(name, { description, inputSchema: schema, annotations: annotate(name) }, run(fn));
69
-
70
- // ============ account ============
71
- T('get_usage', 'Usage and balance for this account.', z.object({}), () => client.usage.get());
72
- T('rotate_api_key', 'Replace the API secret. The current secret stops working immediately - every integration must be updated. Requires confirm: true.',
73
- z.object({ confirm: confirmArg }), async ({ confirm }) => confirm ? client.keys.rotate() : { would_rotate: key.split(':')[0], warning: 'The current secret stops working the moment this runs.', hint: 'Call again with confirm: true.' });
74
-
75
- // ============ agents ============
76
- T('list_agents', 'List the agents on this account. Phone numbers, webhooks and integrations are attached per NUMBER, not per agent - use list_phone_numbers to see them.',
77
- z.object({ limit: z.number().int().min(1).max(100).optional() }), ({ limit }) => client.agents.list(limit ? { limit } : {}));
78
- T('get_agent', 'One agent with its prompt and settings.', z.object({ agent_id: z.string() }), ({ agent_id }) => client.agents.get(agent_id));
79
- T('create_agent', 'Create an agent. name and system_prompt are required; any other agent field (voice_id, language, incall_sms_enabled, silence_hangup_seconds, record_call, recording_source = provider or nixflex, ...) goes in fields.',
80
- z.object({ name: z.string(), system_prompt: z.string(), fields: fields.optional() }), ({ name, system_prompt, fields: f }) => client.agents.create({ name, system_prompt, ...(f || {}) }));
81
- T('update_agent', 'Update an agent. Only the fields you pass change. Pass null to clear a nullable field.',
82
- z.object({ agent_id: z.string(), fields }), ({ agent_id, fields: f }) => client.agents.update(agent_id, f));
83
- T('delete_agent', 'Delete an agent. Requires confirm: true; otherwise returns a preview.',
84
- z.object({ agent_id: z.string(), confirm: confirmArg }), async ({ agent_id, confirm }) => confirm ? client.agents.delete(agent_id) : preview('agent ' + agent_id, () => client.agents.get(agent_id)));
85
-
86
- // ============ calls ============
87
- T('create_call', 'Place an outbound phone call now. SPENDS credit. prompt is the purpose of this call in full; variables fill {{placeholders}}.',
88
- z.object({ agent_id: z.string(), to_number: E164, prompt: z.string(), from_number: E164.optional().describe('One of your numbers; defaults to the agent number'), variables: z.record(z.string(), z.string()).optional() }),
89
- (a) => client.calls.create(a));
90
- T('list_calls', 'Recent calls as SUMMARIES (no transcript). Use get_call for the full record of one call.',
91
- z.object({ limit: z.number().int().min(1).max(100).optional(), agent_id: z.string().optional() }),
92
- async ({ limit, agent_id }) => (await client.calls.list({ ...(limit ? { limit } : {}), ...(agent_id ? { agent_id } : {}) })).map(summariseCall));
93
- T('get_call', 'One call in full: transcript, analysis, events, bookings, recording URL.', z.object({ call_id: z.string() }), ({ call_id }) => client.calls.get(call_id));
94
- T('delete_call', 'Delete one call record and its recording (GDPR). Requires confirm: true.',
95
- z.object({ call_id: z.string(), confirm: confirmArg }), async ({ call_id, confirm }) => confirm ? client.calls.delete(call_id) : preview('call ' + call_id + ' and its recording', async () => summariseCall(await client.calls.get(call_id))));
96
-
97
- // ============ campaigns (voice batch) ============
98
- T('create_campaign', 'Create an outbound voice campaign - many calls, one prompt. SPENDS credit when launched. Each recipient: { phone, variables?, prompt_override? }. Scheduling fields go in fields.',
99
- z.object({ agent_id: z.string(), from_number: E164, prompt: z.string(), recipients: z.array(z.object({ phone: E164, variables: z.record(z.string(), z.string()).optional(), prompt_override: z.string().optional() })).min(1), name: z.string().optional(), fields: fields.optional() }),
100
- ({ fields: f, ...rest }) => client.campaigns.create({ ...rest, ...(f || {}) }));
101
- T('launch_campaign', 'Launch a created campaign (starts dialling).', z.object({ campaign_id: z.string() }), ({ campaign_id }) => client.campaigns.launch(campaign_id));
102
-
103
- // ============ phone numbers ============
104
- T('list_phone_numbers', 'Phone numbers on this account and which agent each one uses. Webhooks, calendar and custom functions are configured per number.',
105
- z.object({ agent_id: z.string().optional() }), ({ agent_id }) => client.phoneNumbers.list(agent_id ? { agent_id } : {}));
106
- T('import_phone_number', 'Attach a number you own at Twilio or Telnyx to an agent. Needs carrier credentials in fields (twilio_account_sid + twilio_auth_token, or telnyx_api_key + telnyx_connection_id).',
107
- z.object({ phone_number: E164, agent_id: z.string(), fields }), ({ fields: f, ...rest }) => client.phoneNumbers.import({ ...rest, ...f }));
108
- T('update_phone_number', 'Update per-number settings: custom_prompt, sms_prompt, sms_reply_enabled, web_prompt, dtmf_enabled, record_call, recording_source (provider | nixflex | null = inherit), voice_id, speaking_rate, ... Only passed fields change; null clears.',
109
- z.object({ phone_number: E164, fields }), ({ phone_number, fields: f }) => client.phoneNumbers.update(phone_number, f));
110
- T('delete_phone_number', 'Disconnect a number from Nixflex (the carrier keeps it and keeps billing it). Requires confirm: true.',
111
- z.object({ phone_number: E164, confirm: confirmArg }), async ({ phone_number, confirm }) => confirm ? client.phoneNumbers.delete(phone_number) : { would_delete: 'number ' + phone_number + ' from Nixflex', hint: 'Call again with confirm: true.' });
112
- T('set_number_monitor', 'Turn live call monitoring on or off for a number. On bills that number at the premium rate.',
113
- z.object({ phone_number: E164, enabled: z.boolean() }), ({ phone_number, enabled }) => client.phoneNumbers.setMonitor(phone_number, enabled));
114
- T('set_number_web_calls', 'Turn browser (web) calls on or off for a number.',
115
- z.object({ phone_number: E164, enabled: z.boolean() }), ({ phone_number, enabled }) => client.phoneNumbers.setWebCalls(phone_number, enabled));
116
-
117
- // ============ caller context ============
118
- T('get_caller_context', 'What the agent knows about a caller on one of your numbers. phone_number is YOUR number; caller_number is the customer.',
119
- z.object({ phone_number: E164, caller_number: E164 }), ({ phone_number, caller_number }) => client.callers.get(phone_number, caller_number));
120
- T('set_caller_context', 'Set what the agent should know about a caller: name (full), email, phone, location, reference_id, preference. Omitted fields are kept; null removes one. last_call and open_item are engine-only.',
121
- z.object({ phone_number: E164, caller_number: E164, name: z.string().nullable().optional(), email: z.string().nullable().optional(), phone: z.string().nullable().optional(), location: z.string().nullable().optional(), reference_id: z.string().nullable().optional(), preference: z.string().nullable().optional() }),
122
- ({ phone_number, caller_number, ...f }) => client.callers.set(phone_number, caller_number, f));
123
- T('import_caller_context', 'Load up to 1,000 caller records onto one of your numbers in one go. Every row is validated before any is written.',
124
- z.object({ phone_number: E164, callers: z.array(z.object({ caller_number: E164, name: z.string().optional(), email: z.string().optional(), phone: z.string().optional(), location: z.string().optional(), reference_id: z.string().optional(), preference: z.string().optional() })).min(1).max(1000) }),
125
- ({ phone_number, callers }) => client.callers.import(phone_number, callers));
126
- T('delete_caller_context', 'Erase everything known about a caller on one of your numbers. Requires confirm: true.',
127
- z.object({ phone_number: E164, caller_number: E164, confirm: confirmArg }), async ({ phone_number, caller_number, confirm }) => confirm ? client.callers.delete(phone_number, caller_number) : preview('caller ' + caller_number + ' on ' + phone_number, async () => (await client.callers.get(phone_number, caller_number)).caller));
128
-
129
- // ============ sms ============
130
- T('send_sms', 'Send one text from one of your numbers. SPENDS carrier credit.',
131
- z.object({ agent_id: z.string(), from_number: E164, to: E164, message: z.string().max(600) }), (a) => client.sms.send(a));
132
- T('create_sms_campaign', 'Create a bulk SMS campaign. SPENDS carrier credit when launched. Each recipient: { phone, variables? } - variables fill {{placeholders}} in the message.',
133
- z.object({ agent_id: z.string(), from_number: E164, message: z.string(), recipients: z.array(z.object({ phone: E164, variables: z.record(z.string(), z.string()).optional() })).min(1), name: z.string().optional(), fields: fields.optional() }),
134
- ({ fields: f, ...rest }) => client.sms.campaigns.create({ ...rest, ...(f || {}) }));
135
- T('launch_sms_campaign', 'Launch a created SMS campaign.', z.object({ campaign_id: z.string() }), ({ campaign_id }) => client.sms.campaigns.launch(campaign_id));
136
- T('list_sms_campaigns', 'SMS campaigns, newest first.', z.object({ status: z.string().optional(), limit: z.number().int().min(1).max(100).optional() }), ({ status, limit }) => client.sms.campaigns.list({ ...(status ? { status } : {}), ...(limit ? { limit } : {}) }));
137
- T('get_sms_campaign', 'One SMS campaign with its delivery counts.', z.object({ campaign_id: z.string() }), ({ campaign_id }) => client.sms.campaigns.get(campaign_id));
138
- T('delete_sms_campaign', 'Delete an SMS campaign - pending recipients will not be messaged; sent messages cannot be recalled. Requires confirm: true.',
139
- z.object({ campaign_id: z.string(), confirm: confirmArg }), async ({ campaign_id, confirm }) => confirm ? client.sms.campaigns.delete(campaign_id) : preview('sms campaign ' + campaign_id, () => client.sms.campaigns.get(campaign_id)));
140
-
141
- // ============ webhooks (per number) ============
142
- T('set_webhook', 'Set the post-call webhook URL on a number (slot 1 or 2). Payloads are signed with your key secret.',
143
- z.object({ phone_number: E164, url: z.string().url(), slot: z.union([z.literal(1), z.literal(2)]).optional() }), ({ phone_number, url, slot }) => client.webhooks.set(phone_number, url, slot || 1));
144
- T('get_webhook', 'The webhook URL configured on a number.', z.object({ phone_number: E164, slot: z.union([z.literal(1), z.literal(2)]).optional() }), ({ phone_number, slot }) => client.webhooks.get(phone_number, slot || 1));
145
- T('delete_webhook', 'Remove the webhook URL from a number. Requires confirm: true.',
146
- z.object({ phone_number: E164, slot: z.union([z.literal(1), z.literal(2)]).optional(), confirm: confirmArg }), async ({ phone_number, slot, confirm }) => confirm ? client.webhooks.delete(phone_number, slot || 1) : preview('webhook slot ' + (slot || 1) + ' on ' + phone_number, () => client.webhooks.get(phone_number, slot || 1)));
147
-
148
- // ============ bring your own: storage / llm / tts ============
149
- const BYO = z.enum(['storage', 'llm', 'tts']);
150
- T('get_byo_config', 'Your own storage / LLM / TTS configuration (secrets are never returned).', z.object({ kind: BYO }), ({ kind }) => client[kind].get());
151
- T('set_byo_config', 'Connect your own storage bucket, LLM endpoint or TTS provider. The API verifies the connection with a real probe before saving. See docs.nixflex.com/advanced/your-own-<kind>.',
152
- z.object({ kind: BYO, fields }), ({ kind, fields: f }) => client[kind].set(f));
153
- T('delete_byo_config', 'Disconnect your own storage / LLM / TTS - calls fall back to Nixflex. Requires confirm: true.',
154
- z.object({ kind: BYO, confirm: confirmArg }), async ({ kind, confirm }) => confirm ? client[kind].delete() : preview('your own ' + kind + ' configuration', () => client[kind].get()));
155
-
156
- // ---- start ----
157
- const transport = new StdioServerTransport();
158
- await server.connect(transport);
159
- log('ready v' + VERSION + ' - ' + key.split(':')[0]);
1
+ #!/usr/bin/env node
2
+ // ============================================
3
+ // nixflex-mcp - the Nixflex MCP server (stdio).
4
+ //
5
+ // Supported clients: Claude Desktop, Claude Code, Codex and Cursor.
6
+ // See README.md for OS-specific, pinned setup; never put a key in a snippet.
7
+ //
8
+ // Mutation tools use the official SDK. Group2 number reads have a GET-only adapter
9
+ // for installed SDK 0.8.0 until the new SDK is published. The same code the CLI
10
+ // and the docs use, so a tool can never do something the API does not. Coverage mirrors
11
+ // the CLI 1:1; tests/tools.test.mjs pins the tool count.
12
+ // STDIO RULE: never write to stdout. stdout IS the protocol. All logging goes to stderr.
13
+ // SAFETY: delete/rotate tools require confirm: true and return a preview otherwise.
14
+ // All mutations have destructive hints; hints alone do not add a confirmation gate.
15
+ // There is no delete-all tool. Spending tools (create_call, create_campaign, send_sms,
16
+ // create_sms_campaign) say so in their description and need every field spelled out.
17
+ // GENERIC FIELDS: update/create tools take a `fields` object passed straight to the API,
18
+ // so a new API field needs no server update (same rule as the CLI's --set).
19
+ // LISTS ARE SUMMARIES: list_calls strips transcripts and analysis - use get_call for one
20
+ // call in full. Full transcripts in a list blew the context in the first live audit.
21
+ // ============================================
22
+ import { McpServer } from '@modelcontextprotocol/server';
23
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
24
+ import * as z from 'zod/v4';
25
+ import Nixflex from 'nixflex';
26
+ import { registerOrganisationTools, organisationRequest } from './organisation-tools.js';
27
+ import { registerCoreTools } from './core-tools.js';
28
+ import { registerC6Tools } from './c6-tools.js';
29
+ import { registerKnowledgeTools } from './knowledge-tools.js';
30
+ import { registerK6Tools } from './k6-tools.js';
31
+ import { registerK7Tools } from './k7-tools.js';
32
+ import { registerK7CreateCall } from './k7-call.js';
33
+ import { registerK9Deletes, contentDeleteRequest } from './k9-deletes.js';
34
+ import { knowledgeRequest } from './knowledge-request.js';
35
+ import { privateWebhookRead } from './c6-output.js';
36
+ import { registerC5Tools } from './c5-tools.js';
37
+ import { kitRequest } from './kit-request.js';
38
+ import { contactLocation, voiceCampaignSchema, smsCampaignSchema, campaignBody, smsListSchema, smsDetailSchema } from './campaign-schema.js';
39
+ import { executeTool, errorBody } from './safe-tools.js';
40
+ import { numberReads } from './number-reads.js';
41
+ import { numberReadSchema, numberFields } from './number-schema.js';
42
+ import { agentCreateFields, agentUpdateFields } from './agent-schema.js';
43
+ import { agentReads, agentListSchema } from './agent-reads.js';
44
+ import { createCallBody, summariseCall as callSummary } from './call-tools.js';
45
+ import { callReads, callListSchema, callGetSchema } from './call-reads.js';
46
+ import { readFileSync } from 'node:fs';
47
+ import { resolveConnection } from './foundation/connection.mjs';
48
+ import { installOriginFence } from './foundation/origin-fence.mjs';
49
+ import { toolMetadata } from './foundation/tool-metadata.mjs';
50
+
51
+ const VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
52
+ const log = (...a) => process.stderr.write('[nixflex-mcp] ' + a.join(' ') + '\n');
53
+
54
+ let connection;
55
+ try { connection = resolveConnection(); }
56
+ catch (error) {
57
+ await new Promise(resolve => process.stderr.write('[nixflex-mcp] ' + error.message + '\n', resolve));
58
+ process.exit(2);
59
+ }
60
+ const { key, baseUrl, source } = connection;
61
+ installOriginFence(baseUrl, VERSION);
62
+ const request = kitRequest(key, baseUrl);
63
+ const client = new Nixflex({ apiKey: key, baseUrl, maxRetries: 0 });
64
+ const readNumbers = numberReads(key, baseUrl);
65
+ const readAgents = agentReads(key, baseUrl);
66
+ const readCalls = callReads(key, baseUrl);
67
+
68
+ // ---- helpers ----
69
+ const text = (data) => ({ content: [{ type: 'text', text: typeof data === 'string' ? data : JSON.stringify(data, null, 2) }] });
70
+ const fail = (e) => {
71
+ const body = errorBody(e);
72
+ return { content: [{ type: 'text', text: JSON.stringify(body, null, 2) }], isError: true };
73
+ };
74
+ const run = (name, fn) => async (args) => { try { return text(await executeTool(name, fn, args)); } catch (e) { return fail(e); } };
75
+ const E164 = z.string().regex(/^\+[1-9]\d{6,14}$/, 'E.164 number, e.g. +447700900123');
76
+ const fields = z.record(z.string(), z.unknown()).describe('Any fields the API accepts, passed as-is. Unknown names are rejected by the API, never dropped silently.');
77
+ const confirmArg = z.boolean().optional().describe('Required true to actually do it. Without it the tool returns a preview and changes nothing.');
78
+ const preview = async (what, fetch) => { let current = null; try { current = await fetch(); } catch { /* preview */ } return { would_delete: what, current, hint: 'Call again with confirm: true.' }; };
79
+ const summariseCall = callSummary;
80
+
81
+ const server = new McpServer({ name: 'nixflex', version: VERSION });
82
+ // Client hints, never authorization or a guarantee that the client asks permission.
83
+ const T = (name, description, schema, fn) => server.registerTool(name, { ...toolMetadata(name, description), inputSchema: schema }, run(name, fn));
84
+
85
+ // ============ account ============
86
+ T('get_usage', 'Usage and balance for this account.', z.object({}), () => client.usage.get());
87
+ T('rotate_api_key', 'Replace the API secret. The current secret stops working immediately - every integration must be updated. Requires confirm: true.',
88
+ z.object({ confirm: confirmArg }), async ({ confirm }) => confirm ? client.keys.rotate() : { would_rotate: key.split(':')[0], warning: 'The current secret stops working the moment this runs.', hint: 'Call again with confirm: true.' });
89
+
90
+ // ============ agents ============
91
+ T('list_agents', 'List the agents on this account. Phone numbers, webhooks and integrations are attached per NUMBER, not per agent - use list_phone_numbers to see them.',
92
+ agentListSchema, readAgents);
93
+ T('get_agent', 'One agent with its prompt and settings.', z.object({ agent_id: z.string() }), ({ agent_id }) => client.agents.get(agent_id));
94
+ T('create_agent', 'Create an agent. All fields are optional. New defaults: maximum call 300 seconds, silence hang-up 10 seconds, dynamic greeting on; any other agent field (voice_id, language, incall_sms_enabled, silence_hangup_seconds, record_call, recording_source = provider or nixflex, ...) goes in fields.',
95
+ z.object({ name: z.string().optional(), system_prompt: z.string().optional(), fields: agentCreateFields.optional() }), ({ name, system_prompt, fields: f }) => client.agents.create({ name, system_prompt, ...(f || {}) }));
96
+ T('update_agent', 'Update an agent. Empty/unknown-only updates fail; mixed unknown keys return warnings. Only passed fields change. Pass null only to clear nullable fields.',
97
+ z.object({ agent_id: z.string(), fields: agentUpdateFields }), ({ agent_id, fields: f }) => client.agents.update(agent_id, f));
98
+ T('delete_agent', 'Soft disable an agent, not permanent deletion. Does not detach numbers or erase history. Requires confirm: true; otherwise returns a preview.',
99
+ z.object({ agent_id: z.string(), confirm: confirmArg }), async ({ agent_id, confirm }) => confirm ? client.agents.delete(agent_id) : preview('agent ' + agent_id, () => client.agents.get(agent_id)));
100
+
101
+ // ============ calls ============
102
+ registerK7CreateCall(server, {client, request, metadata:toolMetadata, E164, contactLocation});
103
+ T('list_calls', 'Call summaries without transcript. history:true adds dashboard filters, totals and next_cursor; continue with cursor + limit only. period defaults month; today uses UTC, or pass exact since/until from dashboard.',
104
+ callListSchema, args => readCalls.list(args, summariseCall));
105
+ T('get_call', 'One call. Optional view: detail (nullable retained data), recording (status + link with expires_at; never fetch customer storage). No view preserves the legacy read.', callGetSchema, readCalls.one);
106
+
107
+ // ============ campaigns (voice batch) ============
108
+ T('create_campaign', 'Create an outbound voice campaign - many calls, one prompt. SPENDS credit when launched. Each recipient: { phone, variables?, prompt_override? }. Scheduling fields go in fields.',
109
+ voiceCampaignSchema, args => client.campaigns.create(campaignBody(args)));
110
+ T('launch_campaign', 'Launch a created campaign (starts dialling).', z.object({ campaign_id: z.string() }), ({ campaign_id }) => client.campaigns.launch(campaign_id));
111
+
112
+ // ============ phone numbers ============
113
+ T('list_phone_numbers', 'Read public numbers with optional agent/provider filters and cursor pagination, or phone_number for safe settings. Add usage:true with phone_number for call/SMS/web usage; optional period and time_zone (default all/UTC). Retained history, not a billing ledger; unused means no calls and no SMS. Webhooks, calendar and custom functions are configured per number.',
114
+ numberReadSchema, readNumbers);
115
+ T('import_phone_number', 'Attach a number you own at Twilio or Telnyx to an agent. Needs carrier credentials in fields (twilio_sid + twilio_token, or telnyx_api_key + telnyx_connection_id).',
116
+ z.object({ phone_number: E164, agent_id: z.string(), fields }), ({ fields: f, ...rest }) => client.phoneNumbers.import({ ...rest, ...f }));
117
+ T('update_phone_number', 'Update saved settings and seven boolean switches, or send fields:{agent_id:ID} ALONE to move to an active agent of this account. Busy calls/replies/campaigns/number operations refuse a move. The number keeps its own settings/functions/history; shared agent settings change. Website voice needs Web agent enabled; monitoring eligibility alone does not start listening. Only passed fields change; null clears only nullable overrides.',
118
+ z.object({ phone_number: E164, fields: numberFields }), ({ phone_number, fields: f }) => client.phoneNumbers.update(phone_number, f));
119
+ T('delete_phone_number', 'Disconnect a number from Nixflex (the carrier keeps it and keeps billing it). Requires confirm: true.',
120
+ z.object({ phone_number: E164, confirm: confirmArg }), async ({ phone_number, confirm }) => confirm ? client.phoneNumbers.delete(phone_number) : { would_delete: 'number ' + phone_number + ' from Nixflex', hint: 'Call again with confirm: true.' });
121
+ T('set_number_web_calls', 'Turn browser (web) calls on or off for a number.',
122
+ z.object({ phone_number: E164, enabled: z.boolean() }), ({ phone_number, enabled }) => client.phoneNumbers.setWebCalls(phone_number, enabled));
123
+
124
+ // ============ caller context ============
125
+ T('get_caller_context', 'What the agent knows about a caller on one of your numbers. phone_number is YOUR number; caller_number is the customer.',
126
+ z.object({ phone_number: E164, caller_number: E164 }), ({ phone_number, caller_number }) => client.callers.get(phone_number, caller_number));
127
+ T('set_caller_context', 'Set what the agent should know about a caller: name (full), email, phone, location, reference_id, preference. Omitted fields are kept; null removes one. last_call and open_item are engine-only.',
128
+ z.object({ phone_number: E164, caller_number: E164, name: z.string().nullable().optional(), email: z.string().nullable().optional(), phone: z.string().nullable().optional(), location: z.string().nullable().optional(), reference_id: z.string().nullable().optional(), preference: z.string().nullable().optional() }),
129
+ ({ phone_number, caller_number, ...f }) => client.callers.set(phone_number, caller_number, f));
130
+ T('import_caller_context', 'Load up to 1,000 caller records onto one of your numbers in one go. Every row is validated before any is written.',
131
+ z.object({ phone_number: E164, callers: z.array(z.object({ caller_number: E164, name: z.string().optional(), email: z.string().optional(), phone: z.string().optional(), location: z.string().optional(), reference_id: z.string().optional(), preference: z.string().optional() })).min(1).max(1000) }),
132
+ ({ phone_number, callers }) => client.callers.import(phone_number, callers));
133
+ T('delete_caller_context', 'Erase everything known about a caller on one of your numbers. Requires confirm: true.',
134
+ z.object({ phone_number: E164, caller_number: E164, confirm: confirmArg }), async ({ phone_number, caller_number, confirm }) => confirm ? client.callers.delete(phone_number, caller_number) : preview('caller ' + caller_number + ' on ' + phone_number, async () => (await client.callers.get(phone_number, caller_number)).caller));
135
+
136
+ // ============ sms ============
137
+ T('send_sms', 'Send one text from one of your numbers. SPENDS carrier credit.',
138
+ z.object({ agent_id: z.string(), from_number: E164, to: E164, message: z.string(), context: z.object({reply_context:z.string().optional()}).optional(), ...contactLocation }), (a) => client.sms.send(a));
139
+ T('create_sms_campaign', 'Create a bulk SMS campaign. SPENDS carrier credit when launched. Each recipient: { phone, variables? } - variables fill {{placeholders}} in the message.',
140
+ smsCampaignSchema, args => request('POST', '/sms/campaigns', campaignBody(args)));
141
+ T('launch_sms_campaign', 'Launch a created SMS campaign.', z.object({ campaign_id: z.string() }), ({ campaign_id }) => client.sms.campaigns.launch(campaign_id));
142
+ T('list_sms_campaigns', 'SMS campaigns, newest first; use next_cursor as before for the next page.', smsListSchema, args => request('GET','/sms/campaigns',undefined,args));
143
+ T('get_sms_campaign', 'Campaign, recipients, messages and independent pagination cursors. Sent is distinct from delivered and failed.', smsDetailSchema, ({campaign_id,...query}) => request('GET','/sms/campaigns/'+encodeURIComponent(campaign_id),undefined,query));
144
+
145
+ // ============ webhooks (per number) ============
146
+ T('set_webhook', 'Set the post-call webhook URL on a number (slot 1 or 2). Payloads use the organisation signing secret, independent of API-key rotation.',
147
+ z.object({ phone_number: E164, url: z.string().url(), slot: z.union([z.literal(1), z.literal(2)]).optional() }), ({ phone_number, url, slot }) => client.webhooks.set(phone_number, url, slot || 1));
148
+ T('get_webhook', 'The webhook URL configured on a number.', z.object({ phone_number: E164, slot: z.union([z.literal(1), z.literal(2)]).optional() }), ({ phone_number, slot }) => privateWebhookRead(() => client.webhooks.get(phone_number, slot || 1)));
149
+ T('delete_webhook', 'Remove the webhook URL from a number. Requires confirm: true.',
150
+ z.object({ phone_number: E164, slot: z.union([z.literal(1), z.literal(2)]).optional(), confirm: confirmArg }), async ({ phone_number, slot, confirm }) => confirm ? client.webhooks.delete(phone_number, slot || 1) : preview('webhook slot ' + (slot || 1) + ' on ' + phone_number, () => privateWebhookRead(() => client.webhooks.get(phone_number, slot || 1))));
151
+
152
+ // Organisation tools are part of this one main install.
153
+ registerOrganisationTools(server, organisationRequest(key, baseUrl));
154
+ registerCoreTools(server, request);
155
+ registerC5Tools(server, request);
156
+ registerC6Tools(server, request);
157
+ registerKnowledgeTools(server, knowledgeRequest(key, baseUrl));
158
+ registerK6Tools(server, request);
159
+ registerK7Tools(server, request);
160
+ registerK9Deletes(server, contentDeleteRequest(key, baseUrl));
161
+
162
+ // ---- start ----
163
+ const transport = new StdioServerTransport();
164
+ await server.connect(transport);
165
+ log('ready v' + VERSION + ' source=' + source + ' api=' + baseUrl);
package/k6-private.js ADDED
@@ -0,0 +1,36 @@
1
+ export const calendarCodes=['invalid_return_url','number_not_found','already_connected','booking_provider_conflict',
2
+ 'not_connected','agent_not_assigned','invalid_settings','invalid_timezone','invalid_hours','invalid_slot_minutes',
3
+ 'invalid_calendar_id','invalid_send_invites','calendar_unavailable','expired_link','not_configured','guard_unavailable'];
4
+ export const credentialCodes=['invalid_request','invalid_credentials','number_not_in_account','number_not_found',
5
+ 'carrier_mismatch','account_unavailable','number_operation_pending','number_release_pending','carrier_unavailable',
6
+ 'credential_update_unavailable','carrier_outcome_unknown','credential_save_pending'];
7
+ const common=['unauthorized','invalid_api_key','permission_denied','forbidden','rate_limit_exceeded',
8
+ 'organisation_disabled','organisation_unavailable','account_closed','account_inactive','outcome_unknown','credentials_not_configured'];
9
+ export function privateFeatureError(error,kind,mutation){
10
+ const status=Number.isInteger(error?.status)&&error.status>=0&&error.status<=599?error.status:0;
11
+ const original=error?.code==='outcome_unknown'?error.details?.original_code:error?.code;
12
+ const allowed=[...(kind==='calendar'?calendarCodes:credentialCodes),...common];
13
+ const code=allowed.includes(original)?original:error?.code==='outcome_unknown'?'outcome_unknown':'request_failed';
14
+ const unknown=mutation&&(error?.code==='outcome_unknown'||status===0||status>=500||(status>=300&&status<400));
15
+ const details=unknown?{outcome:'unknown',safe_to_retry:false}:{};
16
+ if(/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(error?.details?.operation_id||''))details.operation_id=error.details.operation_id;
17
+ const type=({400:'invalid_request',422:'invalid_request',401:'authentication_error',403:'permission_denied',
18
+ 404:'not_found',409:'conflict',429:'rate_limit'})[status]||(status>=500?'server_error':unknown?'outcome_unknown':'error');
19
+ let message='Request failed. Check status and code; private details omitted.';
20
+ if(code==='carrier_outcome_unknown')message='Carrier routing is unconfirmed. Contact support before retrying.';
21
+ else if(code==='credential_save_pending')message='Carrier change succeeded; saving is pending. Retry manually with exactly the same private details to finish saving.';
22
+ else if(code==='credentials_not_configured')message='Set the selected carrier pair privately in the MCP process environment. Never paste credentials into chat. Nothing sent.';
23
+ else if(unknown)message+=' Outcome is unconfirmed; check before retrying. No automatic repeat.';
24
+ return {error:{type,code,status,message,details,...(unknown?{outcome:'unknown',safe_to_retry:false}:{})}};
25
+ }
26
+ /** Read only after confirmation; this helper never returns values to the assistant. */
27
+ export function privateCredentialPair(provider,env){
28
+ const fields=provider==='twilio'?['twilio_sid','twilio_token']:['telnyx_api_key','telnyx_connection_id'];
29
+ const names=provider==='twilio'?['NIXFLEX_TWILIO_SID','NIXFLEX_TWILIO_TOKEN']:['NIXFLEX_TELNYX_API_KEY','NIXFLEX_TELNYX_CONNECTION_ID'];
30
+ const values=names.map(k=>env[k]);
31
+ const invalid=()=>Object.assign(Error('Invalid private carrier configuration.'),{status:400,code:'credentials_not_configured'});
32
+ if(values.some(v=>typeof v!=='string'||!v.trim()||v.length>4096||/[\r\n\x00]/.test(v)))throw invalid();
33
+ const body=Object.fromEntries(fields.map((k,i)=>[k,values[i].trim()]));
34
+ if(provider==='twilio'?!/^AC[a-f0-9]{32}$/i.test(body.twilio_sid):body.telnyx_connection_id.length>200)throw invalid();
35
+ return body;
36
+ }
package/k6-schemas.js ADDED
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ export const days=['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
3
+ const clock=z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
4
+ export const hours=z.object(Object.fromEntries(days.map(d=>[d,z.tuple([clock,clock]).refine(v=>v[0]<v[1],'Closing must be after opening.').nullable()]))).strict();
5
+ export const settings={timezone:z.string().max(100).optional(),hours:hours.optional(),
6
+ slot_minutes:z.union([z.literal(15),z.literal(30),z.literal(45),z.literal(60)]).optional(),
7
+ calendar_id:z.string().min(1).max(1024).regex(/^[^\s\x00-\x1f\x7f]+$/).optional(),send_invites:z.boolean().optional()};
8
+ export const phone=z.string().regex(/^\+[1-9]\d{6,14}$/);
9
+ export const confirm=z.boolean().optional().describe('Set true only after the human explicitly approves this exact change. Otherwise zero requests.');
10
+ export const statusOutput=z.object({connected:z.boolean(),account_email:z.string().nullable(),calendar_id:z.string(),
11
+ connected_at:z.string().nullable(),needs_reconnect:z.boolean(),send_invites:z.boolean()});
12
+ export const settingsOutput=z.object({timezone:z.string(),hours,slot_minutes:z.union([z.literal(15),z.literal(30),z.literal(45),z.literal(60)]),calendar_id:z.string(),send_invites:z.boolean()});
13
+ export const disconnectOutput=z.object({ok:z.literal(true),connected:z.literal(false)});
14
+ export const credentialOutput=z.object({phone_number:phone,provider:z.enum(['twilio','telnyx']),updated:z.literal(true)});
15
+ /** Public booking mutation evidence; internal duplicate lookups are not events. */
16
+ export const bookingSchema=z.object({action:z.enum(['created','rescheduled','cancelled']),
17
+ booking_uid:z.string().nullable(),start:z.string().nullable(),end:z.string().nullable(),
18
+ attendee_name:z.string().nullable(),attendee_email:z.string().nullable(),
19
+ service:z.union([z.string(),z.number(),z.null()]),timezone:z.string().nullable()});
20
+ export const callCompletedBookingSchema=z.object({event:z.literal('call.completed'),bookings:z.array(bookingSchema)}).passthrough();
21
+ export const smsBookingSchema=z.object({event:z.literal('sms.booking'),booking:bookingSchema}).passthrough();
22
+ export function connectOutput(value){
23
+ const result=z.object({url:z.string(),expires_at:z.string()}).parse(value),url=new URL(result.url);
24
+ if(url.protocol!=='https:'||url.hostname!=='accounts.google.com'||url.username||url.password||
25
+ ['access_token','refresh_token','id_token','code'].some(k=>url.searchParams.has(k)))throw Error('Invalid consent link.');
26
+ return result;
27
+ }
package/k6-tools.js ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+ import { executeTool } from './safe-tools.js';
3
+ import { settings,phone,confirm,statusOutput,settingsOutput,disconnectOutput,credentialOutput,connectOutput } from './k6-schemas.js';
4
+ import { privateFeatureError,privateCredentialPair } from './k6-private.js';
5
+ const path=n=>'/integrations/google-calendar/number/'+encodeURIComponent(n);
6
+ const text=value=>({content:[{type:'text',text:JSON.stringify(value,null,2)}]});
7
+ export function registerK6Tools(server,request,env=process.env){
8
+ function add(name,title,description,shape,kind,run){
9
+ const read=name==='get_google_calendar';
10
+ server.registerTool(name,{title,description:description+(read?' Use only when the user requests this account information.'
11
+ :" Use only for the user's explicitly requested change. Requires confirm:true; otherwise zero requests. Check uncertain outcomes before retrying."),
12
+ annotations:{title,readOnlyHint:read,destructiveHint:!read,idempotentHint:read,openWorldHint:true},inputSchema:z.object(shape).strict()},async args=>{
13
+ if(!read&&args.confirm!==true)return text({confirmation_required:true,sent:false,hint:'Review the exact number and change with the human, then set confirm:true.'});
14
+ try{return text(await executeTool(name,run,args));}
15
+ catch(error){return {...text(privateFeatureError(error,kind,!read)),isError:true};}
16
+ });
17
+ }
18
+ add('connect_google_calendar','Connect a number to Google Calendar',
19
+ 'Create a ten-minute consent link for the human to open. Never auto-open it. No tokens are returned. A saved connection with needs_reconnect:true permits new consent.',
20
+ {phone_number:phone,return_url:z.string().max(2048),confirm},'calendar',async a=>connectOutput(await request('POST',path(a.phone_number)+'/connect',{return_url:a.return_url})));
21
+ add('get_google_calendar','Read number Google Calendar status',
22
+ 'Read safe status, including send_invites. connected:true with needs_reconnect:true means consent is needed. The engine may refresh/check the existing provider connection.',
23
+ {phone_number:phone},'calendar',async a=>statusOutput.parse(await request('GET',path(a.phone_number))));
24
+ add('disconnect_google_calendar','Disconnect number Google Calendar',
25
+ 'Remove this number’s saved Google access and stop future calendar use. Already dispatched provider operations cannot be recalled; do not claim remote revocation.',
26
+ {phone_number:phone,confirm},'calendar',async a=>disconnectOutput.parse(await request('DELETE',path(a.phone_number))));
27
+ add('update_google_calendar_settings','Update number Google Calendar settings',
28
+ 'Change only supplied settings. hours replaces all seven days; null closes one day. send_invites controls Google invitations; it does not prove inbox delivery.',
29
+ {phone_number:phone,...settings,confirm},'calendar',async a=>{
30
+ const {phone_number,confirm,...body}=a;
31
+ if(!Object.keys(body).length)throw Object.assign(Error('Supply a setting.'),{status:400,code:'invalid_settings'});
32
+ return settingsOutput.parse(await request('PATCH',path(phone_number),body));
33
+ });
34
+ add('update_phone_number_credentials','Update sensitive number carrier credentials',
35
+ 'SENSITIVE WRITE. Use the privately configured local carrier pair; never ask for secrets in chat or tool arguments. Reconfigures carrier routing for this exact owned number while keeping its settings/history. It may require fresh Telnyx verification. No automatic retry and no secret output.',
36
+ {phone_number:phone,provider:z.enum(['twilio','telnyx']),confirm},'credentials',async a=>{
37
+ const body=privateCredentialPair(a.provider,env);
38
+ const result=credentialOutput.parse(await request('POST','/phone-numbers/'+encodeURIComponent(a.phone_number)+'/credentials',body));
39
+ if(result.phone_number!==a.phone_number||result.provider!==a.provider)throw Error('Mismatched update receipt.');
40
+ return result;
41
+ });
42
+ }
package/k7-call.js ADDED
@@ -0,0 +1,34 @@
1
+ import * as z from 'zod/v4';
2
+ import {randomUUID} from 'node:crypto';
3
+ import {createCallBody} from './call-tools.js';
4
+ import {executeTool,errorBody} from './safe-tools.js';
5
+ import {requestId,acceptanceOutput} from './k7-schemas.js';
6
+ import {callRequestError} from './k7-errors.js';
7
+ const text=v=>({content:[{type:'text',text:JSON.stringify(v,null,2)}]});
8
+ const description='Place an outbound phone call now. SPENDS credit. prompt is the purpose of this call in full; variables fill {{placeholders}}.';
9
+ export function registerK7CreateCall(server,{client,request,metadata,E164,contactLocation}){
10
+ const schema=z.object({agent_id:z.string(),to_number:E164,prompt:z.string(),
11
+ from_number:E164.optional().describe('One of your numbers; defaults to an eligible outbound number'),
12
+ variables:z.record(z.string(),z.string()).optional(),...contactLocation,
13
+ request_id:requestId.optional().describe('Saved UUID for exactly this call intent. Never replace it to retry an uncertain call.'),
14
+ safe_retry:z.boolean().optional().describe('Without request_id: prepare a UUID, place no call. Then reuse the returned UUID and identical inputs with confirm:true.'),
15
+ confirm:z.boolean().optional().describe('Required true for the new request_id path. Does not replace the saved UUID or bypass server admission.')});
16
+ server.registerTool('create_call',{...metadata('create_call',description+' Optional safe_retry prepares a UUID locally without dialling. request_id requires confirm:true; reuse unchanged inputs. The legacy path without either option is unchanged.'),inputSchema:schema},
17
+ createCallHandler(client,request));
18
+ }
19
+ export function createCallHandler(client,request){
20
+ return async args=>{
21
+ const {safe_retry,confirm,...input}=args;
22
+ if(safe_retry===true&&input.request_id===undefined)return text({confirmation_required:true,sent:false,
23
+ request_id:randomUUID(),hint:'Save this UUID and the exact call inputs before sending. Call again with that request_id and confirm:true. Never prepare another ID as a retry.'});
24
+ const durable=input.request_id!==undefined;
25
+ if(durable&&confirm!==true)return text({confirmation_required:true,sent:false,request_id:input.request_id,
26
+ hint:'Review this paid call with the human; use the same UUID and unchanged inputs with confirm:true.'});
27
+ try{
28
+ if(!durable)return text(await executeTool('create_call',()=>client.calls.create(createCallBody(input)),{}));
29
+ const body=createCallBody(input);
30
+ requestId.parse(input.request_id);
31
+ return text(acceptanceOutput(await request('POST','/calls/outbound',body),input.request_id));
32
+ }catch(error){return {...text(durable?callRequestError(error,input.request_id,true):errorBody(error)),isError:true};}
33
+ };
34
+ }