nixflex-mcp 0.5.0 → 0.5.2

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/k6-private.js CHANGED
@@ -1,36 +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
- }
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 CHANGED
@@ -1,27 +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
- }
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 CHANGED
@@ -1,42 +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
- }
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 CHANGED
@@ -1,34 +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
- }
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 CHANGED
@@ -1,16 +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
- }
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 CHANGED
@@ -1,34 +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
- }
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 CHANGED
@@ -1,20 +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
- }
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
+ }