nixflex-mcp 0.2.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/B57-DELETES.md +52 -0
- package/CALL-REQUESTS.md +73 -0
- package/CHANGELOG.md +120 -0
- package/KIT-EXAMPLES-K6.md +118 -0
- package/KIT-EXAMPLES-K7.md +104 -0
- package/LICENSE +9 -9
- package/METHODS.md +129 -0
- package/NUMBER-FEATURES.md +51 -0
- package/ORGANISATIONS.md +14 -0
- package/README.md +39 -13
- package/agent-reads.js +26 -0
- package/agent-schema.js +24 -0
- package/c5-schemas.js +17 -0
- package/c5-tools.js +31 -0
- package/c6-output.js +32 -0
- package/c6-tools.js +35 -0
- package/call-reads.js +43 -0
- package/call-tools.js +22 -0
- package/campaign-schema.js +38 -0
- package/core-tools.js +36 -0
- package/foundation/connection.mjs +48 -0
- package/foundation/launch.mjs +39 -0
- package/foundation/origin-fence.mjs +21 -0
- package/foundation/origins.mjs +15 -0
- package/foundation/tool-metadata.mjs +44 -0
- package/index.js +80 -74
- package/k6-private.js +36 -0
- package/k6-schemas.js +27 -0
- package/k6-tools.js +42 -0
- package/k7-call.js +34 -0
- package/k7-errors.js +16 -0
- package/k7-schemas.js +34 -0
- package/k7-tools.js +20 -0
- package/k9-deletes.js +90 -0
- package/kit-request.js +24 -0
- package/knowledge-request.js +24 -0
- package/knowledge-tools.js +47 -0
- package/number-reads.js +23 -0
- package/number-schema.js +26 -0
- package/number-usage.js +13 -0
- package/organisation-tools.js +26 -0
- package/package.json +85 -22
- package/safe-tools.js +36 -0
|
@@ -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
|
@@ -2,15 +2,16 @@
|
|
|
2
2
|
// ============================================
|
|
3
3
|
// nixflex-mcp - the Nixflex MCP server (stdio).
|
|
4
4
|
//
|
|
5
|
-
// Claude Desktop
|
|
6
|
-
//
|
|
7
|
-
// { "mcpServers": { "nixflex": { "command": "npx", "args": ["-y", "nixflex-mcp"] } } }
|
|
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.
|
|
8
7
|
//
|
|
9
|
-
//
|
|
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
10
|
// and the docs use, so a tool can never do something the API does not. Coverage mirrors
|
|
11
11
|
// the CLI 1:1; tests/tools.test.mjs pins the tool count.
|
|
12
12
|
// STDIO RULE: never write to stdout. stdout IS the protocol. All logging goes to stderr.
|
|
13
|
-
// SAFETY:
|
|
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.
|
|
14
15
|
// There is no delete-all tool. Spending tools (create_call, create_campaign, send_sms,
|
|
15
16
|
// create_sms_campaign) say so in their description and need every field spelled out.
|
|
16
17
|
// GENERIC FIELDS: update/create tools take a `fields` object passed straight to the API,
|
|
@@ -21,51 +22,65 @@
|
|
|
21
22
|
import { McpServer } from '@modelcontextprotocol/server';
|
|
22
23
|
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
|
23
24
|
import * as z from 'zod/v4';
|
|
24
|
-
import Nixflex
|
|
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';
|
|
25
46
|
import { readFileSync } from 'node:fs';
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
47
|
+
import { resolveConnection } from './foundation/connection.mjs';
|
|
48
|
+
import { installOriginFence } from './foundation/origin-fence.mjs';
|
|
49
|
+
import { toolMetadata } from './foundation/tool-metadata.mjs';
|
|
28
50
|
|
|
29
|
-
const VERSION = '
|
|
51
|
+
const VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
|
|
30
52
|
const log = (...a) => process.stderr.write('[nixflex-mcp] ' + a.join(' ') + '\n');
|
|
31
53
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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.');
|
|
54
|
+
let connection;
|
|
55
|
+
try { connection = resolveConnection(); }
|
|
56
|
+
catch (error) {
|
|
57
|
+
await new Promise(resolve => process.stderr.write('[nixflex-mcp] ' + error.message + '\n', resolve));
|
|
40
58
|
process.exit(2);
|
|
41
59
|
}
|
|
42
|
-
const
|
|
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);
|
|
43
67
|
|
|
44
68
|
// ---- helpers ----
|
|
45
69
|
const text = (data) => ({ content: [{ type: 'text', text: typeof data === 'string' ? data : JSON.stringify(data, null, 2) }] });
|
|
46
70
|
const fail = (e) => {
|
|
47
|
-
const body = e
|
|
48
|
-
? { error: { code: e.code, status: e.status, message: e.message, doc_url: e.docUrl } }
|
|
49
|
-
: { error: { message: String((e && e.message) || e) } };
|
|
71
|
+
const body = errorBody(e);
|
|
50
72
|
return { content: [{ type: 'text', text: JSON.stringify(body, null, 2) }], isError: true };
|
|
51
73
|
};
|
|
52
|
-
const run = (fn) => async (args) => { try { return text(await
|
|
74
|
+
const run = (name, fn) => async (args) => { try { return text(await executeTool(name, fn, args)); } catch (e) { return fail(e); } };
|
|
53
75
|
const E164 = z.string().regex(/^\+[1-9]\d{6,14}$/, 'E.164 number, e.g. +447700900123');
|
|
54
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.');
|
|
55
77
|
const confirmArg = z.boolean().optional().describe('Required true to actually do it. Without it the tool returns a preview and changes nothing.');
|
|
56
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.' }; };
|
|
57
|
-
const summariseCall =
|
|
79
|
+
const summariseCall = callSummary;
|
|
58
80
|
|
|
59
81
|
const server = new McpServer({ name: 'nixflex', version: VERSION });
|
|
60
|
-
//
|
|
61
|
-
|
|
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));
|
|
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));
|
|
69
84
|
|
|
70
85
|
// ============ account ============
|
|
71
86
|
T('get_usage', 'Usage and balance for this account.', z.object({}), () => client.usage.get());
|
|
@@ -74,43 +89,35 @@ T('rotate_api_key', 'Replace the API secret. The current secret stops working im
|
|
|
74
89
|
|
|
75
90
|
// ============ agents ============
|
|
76
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.',
|
|
77
|
-
|
|
92
|
+
agentListSchema, readAgents);
|
|
78
93
|
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.
|
|
80
|
-
z.object({ name: z.string(), system_prompt: z.string(), fields:
|
|
81
|
-
T('update_agent', 'Update an agent. Only
|
|
82
|
-
z.object({ agent_id: z.string(), fields }), ({ agent_id, fields: f }) => client.agents.update(agent_id, f));
|
|
83
|
-
T('delete_agent', '
|
|
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.',
|
|
84
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)));
|
|
85
100
|
|
|
86
101
|
// ============ calls ============
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
T('
|
|
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))));
|
|
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);
|
|
96
106
|
|
|
97
107
|
// ============ campaigns (voice batch) ============
|
|
98
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.',
|
|
99
|
-
|
|
100
|
-
({ fields: f, ...rest }) => client.campaigns.create({ ...rest, ...(f || {}) }));
|
|
109
|
+
voiceCampaignSchema, args => client.campaigns.create(campaignBody(args)));
|
|
101
110
|
T('launch_campaign', 'Launch a created campaign (starts dialling).', z.object({ campaign_id: z.string() }), ({ campaign_id }) => client.campaigns.launch(campaign_id));
|
|
102
111
|
|
|
103
112
|
// ============ phone numbers ============
|
|
104
|
-
T('list_phone_numbers', '
|
|
105
|
-
|
|
106
|
-
T('import_phone_number', 'Attach a number you own at Twilio or Telnyx to an agent. Needs carrier credentials in fields (
|
|
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).',
|
|
107
116
|
z.object({ phone_number: E164, agent_id: z.string(), fields }), ({ fields: f, ...rest }) => client.phoneNumbers.import({ ...rest, ...f }));
|
|
108
|
-
T('update_phone_number', 'Update
|
|
109
|
-
z.object({ phone_number: E164, fields }), ({ phone_number, fields: f }) => client.phoneNumbers.update(phone_number, 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));
|
|
110
119
|
T('delete_phone_number', 'Disconnect a number from Nixflex (the carrier keeps it and keeps billing it). Requires confirm: true.',
|
|
111
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.' });
|
|
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
121
|
T('set_number_web_calls', 'Turn browser (web) calls on or off for a number.',
|
|
115
122
|
z.object({ phone_number: E164, enabled: z.boolean() }), ({ phone_number, enabled }) => client.phoneNumbers.setWebCalls(phone_number, enabled));
|
|
116
123
|
|
|
@@ -128,32 +135,31 @@ T('delete_caller_context', 'Erase everything known about a caller on one of your
|
|
|
128
135
|
|
|
129
136
|
// ============ sms ============
|
|
130
137
|
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().
|
|
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));
|
|
132
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.',
|
|
133
|
-
|
|
134
|
-
({ fields: f, ...rest }) => client.sms.campaigns.create({ ...rest, ...(f || {}) }));
|
|
140
|
+
smsCampaignSchema, args => request('POST', '/sms/campaigns', campaignBody(args)));
|
|
135
141
|
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
|
|
137
|
-
T('get_sms_campaign', '
|
|
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)));
|
|
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));
|
|
140
144
|
|
|
141
145
|
// ============ webhooks (per number) ============
|
|
142
|
-
T('set_webhook', 'Set the post-call webhook URL on a number (slot 1 or 2). Payloads
|
|
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.',
|
|
143
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));
|
|
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));
|
|
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)));
|
|
145
149
|
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)));
|
|
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))));
|
|
147
151
|
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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));
|
|
155
161
|
|
|
156
162
|
// ---- start ----
|
|
157
163
|
const transport = new StdioServerTransport();
|
|
158
164
|
await server.connect(transport);
|
|
159
|
-
log('ready v' + VERSION + '
|
|
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
|
+
}
|
package/k7-errors.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Protocol errors contain bounded codes/status and the non-secret request UUID.
|
|
2
|
+
// Never echo raw server messages, headers, URLs, request bodies or booking content.
|
|
3
|
+
export function callRequestError(value,id,mutation){
|
|
4
|
+
const e=value||{},raw=e.details||{},status=Number.isInteger(e.status)&&e.status>=0&&e.status<=599?e.status:0;
|
|
5
|
+
const original=e.code==='outcome_unknown'?raw.original_code:e.code;
|
|
6
|
+
const code=typeof original==='string'&&/^[a-z][a-z0-9_]{0,79}$/.test(original)&&!['unknown_error','invalid_response'].includes(original)
|
|
7
|
+
? original : mutation?'outbound_request_unknown':'invalid_response';
|
|
8
|
+
const details=id?{request_id:id}:{};
|
|
9
|
+
if(['pending','accepted','rejected','unknown'].includes(raw.state))details.state=raw.state;
|
|
10
|
+
if(mutation){details.safe_to_retry=false;if(!details.state&&(status===0||code==='outbound_request_unknown'))details.state='unknown';}
|
|
11
|
+
const type=({400:'invalid_request',422:'invalid_request',401:'authentication_error',402:'payment_required',403:'permission_denied',
|
|
12
|
+
404:'not_found',409:'conflict',429:'rate_limit'})[status]||(status>=500?'server_error':status===0&&mutation?'outcome_unknown':'error');
|
|
13
|
+
return {error:{type,code,status,request_id:id||null,details,
|
|
14
|
+
message:mutation?'Call request not confirmed. Keep this request_id; check its status and Call History before any manual retry. No automatic repeat.'
|
|
15
|
+
:'Call result could not be read. No booking or call outcome was inferred.'}};
|
|
16
|
+
}
|
package/k7-schemas.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import * as z from 'zod/v4';
|
|
2
|
+
export const requestId = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
|
|
3
|
+
export const callId = z.string().min(1).max(200).regex(/^(?!\.{1,2}$)[^\u0000-\u001f]+$/);
|
|
4
|
+
const nullable = z.string().nullable();
|
|
5
|
+
const appointment = {booking_uid:z.string().min(1),start:nullable,end:nullable,
|
|
6
|
+
attendee_name:nullable,attendee_email:nullable,service:z.union([z.string(),z.number(),z.null()]),timezone:nullable};
|
|
7
|
+
export const callBookingResult = z.object({event:z.literal('call.bookings'),call_id:callId,agent_id:nullable,
|
|
8
|
+
from:nullable,to:nullable,number:nullable,ended_at:nullable,
|
|
9
|
+
timeline:z.array(z.object({action:z.enum(['created','rescheduled','cancelled']),...appointment,at:z.string()})).min(1),
|
|
10
|
+
final:z.array(z.object({...appointment,status:z.enum(['active','cancelled'])})).min(1)});
|
|
11
|
+
export const callBookings = z.discriminatedUnion('state',[
|
|
12
|
+
z.object({call_id:callId,state:z.literal('ready'),result:callBookingResult}),
|
|
13
|
+
...['none','processing','deleted','unavailable'].map(state=>z.object({call_id:callId,state:z.literal(state),result:z.null()}))
|
|
14
|
+
]);
|
|
15
|
+
export const outboundRequest = z.object({request_id:requestId,state:z.enum(['pending','accepted','rejected','unknown']),
|
|
16
|
+
call_id:nullable,reason:nullable});
|
|
17
|
+
export const acceptance = z.object({call_id:callId.regex(/^[^\u0000-\u0020]+$/),request_id:requestId,
|
|
18
|
+
status:z.literal('initiated'),replayed:z.literal(true).optional(),request_status:z.literal('unconfirmed').optional(),
|
|
19
|
+
safe_to_retry:z.literal(false).optional()}).passthrough();
|
|
20
|
+
export function bookingOutput(value,id){
|
|
21
|
+
const result=callBookings.parse(value);
|
|
22
|
+
if(result.call_id!==id||result.state==='ready'&&result.result.call_id!==id)throw Error('Invalid call result identity.');
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
export function requestOutput(value,id){
|
|
26
|
+
const result=outboundRequest.parse(value);
|
|
27
|
+
if(result.request_id.toLowerCase()!==id.toLowerCase()||result.state==='accepted'&&!result.call_id)throw Error('Invalid call request identity.');
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
export function acceptanceOutput(value,id){
|
|
31
|
+
const result=acceptance.parse(value);
|
|
32
|
+
if(result.request_id.toLowerCase()!==id.toLowerCase()||result.request_status==='unconfirmed'&&result.safe_to_retry!==false)throw Error('Invalid acceptance receipt.');
|
|
33
|
+
return result;
|
|
34
|
+
}
|
package/k7-tools.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import * as z from 'zod/v4';
|
|
2
|
+
import {executeTool} from './safe-tools.js';
|
|
3
|
+
import {requestId,callId,bookingOutput,requestOutput} from './k7-schemas.js';
|
|
4
|
+
import {callRequestError} from './k7-errors.js';
|
|
5
|
+
const text=v=>({content:[{type:'text',text:JSON.stringify(v,null,2)}]});
|
|
6
|
+
export function registerK7Tools(server,request){
|
|
7
|
+
function add(name,title,description,shape,run){
|
|
8
|
+
server.registerTool(name,{title,description:description+' Read only. Use only when the user requests this account information.',
|
|
9
|
+
annotations:{title,readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:true},inputSchema:z.object(shape).strict()},async args=>{
|
|
10
|
+
try{return text(await executeTool(name,run,args));}
|
|
11
|
+
catch(error){return {...text(callRequestError(error,args.request_id,false)),isError:true};}
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
add('get_call_bookings','Read a call’s booking result',
|
|
15
|
+
'Read retained result: ready, none, processing, deleted or unavailable. Only ready has content. This is this call’s result, not current calendar inventory. Unavailable/deleted is never no bookings.',
|
|
16
|
+
{call_id:callId},async a=>bookingOutput(await request('GET','/calls/'+encodeURIComponent(a.call_id)+'/bookings'),a.call_id));
|
|
17
|
+
add('get_outbound_call_request','Read an outbound call request',
|
|
18
|
+
'Read pending, accepted, rejected or unknown for the saved UUID. No call is placed. Unknown is not failure or permission to allocate a new UUID. Accepted does not mean connected or completed.',
|
|
19
|
+
{request_id:requestId},async a=>requestOutput(await request('GET','/calls/outbound/requests/'+encodeURIComponent(a.request_id)),a.request_id));
|
|
20
|
+
}
|
package/k9-deletes.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// B57 adapters use the existing one-attempt transport and origin fence, not a future SDK.
|
|
2
|
+
import * as z from 'zod/v4';
|
|
3
|
+
import { NixflexError } from 'nixflex';
|
|
4
|
+
import { errorBody } from './safe-tools.js';
|
|
5
|
+
import { kitRequest } from './kit-request.js';
|
|
6
|
+
|
|
7
|
+
/** Keep the shared transport untouched; only B57 deletes require a full receipt. */
|
|
8
|
+
export function contentDeleteRequest(key, baseUrl, fetcher = fetch) {
|
|
9
|
+
return async (method, path) => {
|
|
10
|
+
let status = 0, requestId;
|
|
11
|
+
const request = kitRequest(key, baseUrl, async (...args) => {
|
|
12
|
+
const response = await fetcher(...args);
|
|
13
|
+
status = response.status;
|
|
14
|
+
requestId = response.headers.get('x-request-id') || response.headers.get('x-railway-request-id') || undefined;
|
|
15
|
+
return response;
|
|
16
|
+
});
|
|
17
|
+
const invalid = () => new NixflexError(status, {error:{type:'connection_error',
|
|
18
|
+
code:'invalid_response',message:'Deletion receipt could not be confirmed.'}}, requestId);
|
|
19
|
+
let receipt;
|
|
20
|
+
try { receipt = await request(method, path); }
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error instanceof NixflexError && error.code === 'invalid_response') throw invalid();
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
const call = path.startsWith('/calls/') && !path.startsWith('/calls/batch/');
|
|
26
|
+
const id = decodeURIComponent(path.slice(path.lastIndexOf('/') + 1));
|
|
27
|
+
const valid = receipt?.deleted === true && (call
|
|
28
|
+
? receipt.call_id === id && typeof receipt.recording_deleted === 'boolean' &&
|
|
29
|
+
['carrier_best_effort','queued'].includes(receipt.recording_cleanup)
|
|
30
|
+
: receipt.campaign_id === id && typeof receipt.message === 'string');
|
|
31
|
+
if (!valid) throw invalid();
|
|
32
|
+
return receipt;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const confirm = z.boolean().optional().describe('Required true to actually do it. Without it the tool returns a preview and changes nothing.');
|
|
37
|
+
export const contentDeletes = [
|
|
38
|
+
{ name:'delete_call', id:'call_id', prefix:'/calls/', noun:'call',
|
|
39
|
+
description:'End a running call and delete its content. recording_cleanup is carrier_best_effort or queued, not proof every copy is erased. 503 hangup_pending with retry_pending:true means queued, not deleted. Requires confirm: true; preview makes zero requests. Never automatically retries.' },
|
|
40
|
+
{ name:'delete_sms_campaign', id:'campaign_id', prefix:'/sms/campaigns/', noun:'SMS campaign',
|
|
41
|
+
description:'Cancel waiting work and hide an SMS campaign. History and used charges remain; no refund or recall of sent messages. Owner/Admin only; missing/foreign is 404. 503 hangup_pending with retry_pending:true means queued, not deleted. Requires confirm: true; preview makes zero requests. Never automatically retries.' },
|
|
42
|
+
{ name:'delete_campaign', id:'campaign_id', prefix:'/calls/batch/', noun:'voice campaign',
|
|
43
|
+
description:'Cancel waiting work, end running calls and hide a voice campaign. History and used charges remain; no refund. Owner/Admin only; missing/foreign is 404. 503 hangup_pending with retry_pending:true means queued, not deleted. Requires confirm: true; preview makes zero requests. Never automatically retries.' },
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
function deletionError(error) {
|
|
47
|
+
const proof = error?.details;
|
|
48
|
+
const queued = error instanceof NixflexError && error.status === 503 &&
|
|
49
|
+
error.code === 'hangup_pending' && error.type === 'server_error' && typeof error.message === 'string' &&
|
|
50
|
+
proof?.deleted === false && proof.retry_pending === true;
|
|
51
|
+
const notSent = proof?.outcome === 'not_sent' && proof.sent === false &&
|
|
52
|
+
proof.charged === false && proof.safe_to_retry === true;
|
|
53
|
+
if (queued || notSent) return error;
|
|
54
|
+
if (error instanceof NixflexError && error.status >= 400 && error.status < 500) return error;
|
|
55
|
+
const unknown = new NixflexError(error?.status || 0, {error:{
|
|
56
|
+
type:'outcome_unknown', code:'outcome_unknown',
|
|
57
|
+
message:'Outcome unknown - check before retrying. The change may already have happened; it was not automatically repeated.',
|
|
58
|
+
doc_url:error?.docUrl,
|
|
59
|
+
details:{...proof,original_code:error?.code,outcome:'unknown',safe_to_retry:false},
|
|
60
|
+
}},error?.requestId);
|
|
61
|
+
unknown.outcome='unknown';unknown.safe_to_retry=false;
|
|
62
|
+
return unknown;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function registerK9Deletes(server, request) {
|
|
66
|
+
for (const row of contentDeletes) {
|
|
67
|
+
const title = row.name === 'delete_call' ? 'Delete one call and recording' :
|
|
68
|
+
row.name === 'delete_sms_campaign' ? 'Delete an SMS campaign' : 'Delete a voice campaign';
|
|
69
|
+
server.registerTool(row.name, {
|
|
70
|
+
title, description:row.description+' Use only for the user\'s explicitly requested change. Check uncertain outcomes before retrying.',
|
|
71
|
+
annotations:{title,readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true},
|
|
72
|
+
inputSchema:z.object({[row.id]:z.string(),confirm}),
|
|
73
|
+
}, async args => {
|
|
74
|
+
const reply = data => ({content:[{type:'text',text:JSON.stringify(data,null,2)}]});
|
|
75
|
+
if (args.confirm !== true) return reply({
|
|
76
|
+
would_delete:row.noun+' '+args[row.id],
|
|
77
|
+
warning:row.noun==='call' ? 'The running call will be ended; recording cleanup may remain queued.' :
|
|
78
|
+
'Waiting work will be cancelled and running calls ended. History and used charges remain; no refund.',
|
|
79
|
+
hint:'Call again with confirm: true. This preview made no requests.',
|
|
80
|
+
});
|
|
81
|
+
try {
|
|
82
|
+
const id=args[row.id];
|
|
83
|
+
if(typeof id!=='string'||!id.length||id.length>200||id==='.'||id==='..'||/[\x00-\x1f\x7f]/.test(id))
|
|
84
|
+
throw new NixflexError(400,{error:{type:'invalid_request',code:'invalid_delete',message:'Choose a valid call or campaign identifier. Nothing was sent.',details:{}}});
|
|
85
|
+
return reply(await request('DELETE',row.prefix+encodeURIComponent(id)));
|
|
86
|
+
}
|
|
87
|
+
catch (error) { return {...reply(errorBody(deletionError(error))),isError:true}; }
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|