@burdenoff/mcp-libs 2026.1031.2 → 2026.1031.3
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/dist/modules/auth/index.cjs +1 -1
- package/dist/modules/auth/index.cjs.map +1 -1
- package/dist/modules/auth/index.js +1 -1
- package/dist/modules/auth/index.js.map +1 -1
- package/dist/modules/auth/operations.d.ts +2 -2
- package/dist/modules/billing/index.cjs +45 -19
- package/dist/modules/billing/index.cjs.map +1 -1
- package/dist/modules/billing/index.js +45 -19
- package/dist/modules/billing/index.js.map +1 -1
- package/dist/modules/billing/operations.d.ts +4 -4
- package/dist/modules/channels/index.cjs +0 -35
- package/dist/modules/channels/index.cjs.map +1 -1
- package/dist/modules/channels/index.js +0 -35
- package/dist/modules/channels/index.js.map +1 -1
- package/dist/modules/channels/operations.d.ts +0 -1
- package/dist/modules/conversations/index.cjs +6 -6
- package/dist/modules/conversations/index.cjs.map +1 -1
- package/dist/modules/conversations/index.js +6 -6
- package/dist/modules/conversations/index.js.map +1 -1
- package/dist/modules/conversations/operations.d.ts +1 -1
- package/dist/modules/files/index.cjs +421 -101
- package/dist/modules/files/index.cjs.map +1 -1
- package/dist/modules/files/index.js +412 -97
- package/dist/modules/files/index.js.map +1 -1
- package/dist/modules/files/operations.d.ts +9 -8
- package/dist/modules/files/tools.d.ts +2 -0
- package/dist/modules/products/index.cjs +1 -1
- package/dist/modules/products/index.cjs.map +1 -1
- package/dist/modules/products/index.js +1 -1
- package/dist/modules/products/index.js.map +1 -1
- package/dist/modules/products/operations.d.ts +1 -1
- package/dist/modules/rbac/index.cjs +0 -64
- package/dist/modules/rbac/index.cjs.map +1 -1
- package/dist/modules/rbac/index.js +0 -64
- package/dist/modules/rbac/index.js.map +1 -1
- package/dist/modules/rbac/operations.d.ts +0 -2
- package/dist/modules/scheduler/index.cjs +4 -4
- package/dist/modules/scheduler/index.cjs.map +1 -1
- package/dist/modules/scheduler/index.js +4 -4
- package/dist/modules/scheduler/index.js.map +1 -1
- package/dist/modules/scheduler/operations.d.ts +3 -3
- package/dist/modules/tags/index.cjs +454 -48
- package/dist/modules/tags/index.cjs.map +1 -1
- package/dist/modules/tags/index.js +443 -42
- package/dist/modules/tags/index.js.map +1 -1
- package/dist/modules/tags/operations.d.ts +10 -6
- package/dist/modules/tags/tools.d.ts +1 -1
- package/dist/modules/vibecontrols/index.cjs +8 -8
- package/dist/modules/vibecontrols/index.cjs.map +1 -1
- package/dist/modules/vibecontrols/index.js +8 -8
- package/dist/modules/vibecontrols/index.js.map +1 -1
- package/dist/modules/workspaces/index.cjs +235 -5
- package/dist/modules/workspaces/index.cjs.map +1 -1
- package/dist/modules/workspaces/index.js +224 -6
- package/dist/modules/workspaces/index.js.map +1 -1
- package/dist/modules/workspaces/operations.d.ts +2 -2
- package/dist/modules/workspaces/prompts.d.ts +3 -0
- package/dist/modules/workspaces/resources.d.ts +4 -0
- package/package.json +1 -1
|
@@ -118,10 +118,11 @@ var GET_PAGINATED_INVOICES = `
|
|
|
118
118
|
}
|
|
119
119
|
`;
|
|
120
120
|
var GET_INVOICE = `
|
|
121
|
-
query GetInvoice($id: ID!) {
|
|
122
|
-
getInvoice(id: $id) {
|
|
123
|
-
id invoiceNumber status subtotal tax total
|
|
124
|
-
|
|
121
|
+
query GetInvoice($billingAccountId: ID!, $id: ID!) {
|
|
122
|
+
getInvoice(billingAccountId: $billingAccountId, id: $id) {
|
|
123
|
+
id invoiceNumber status currency subtotal tax total amountPaid dueDate paidAt
|
|
124
|
+
pdfUrl invoiceUrl
|
|
125
|
+
items { description quantity unitPrice amount }
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
128
|
`;
|
|
@@ -133,15 +134,15 @@ var GET_PAYMENT_METHODS = `
|
|
|
133
134
|
}
|
|
134
135
|
`;
|
|
135
136
|
var ADD_PAYMENT_METHOD = `
|
|
136
|
-
mutation AddPaymentMethod($input:
|
|
137
|
+
mutation AddPaymentMethod($input: CreatePaymentMethodInput!) {
|
|
137
138
|
addPaymentMethod(input: $input) {
|
|
138
139
|
id type isDefault isVerified
|
|
139
140
|
}
|
|
140
141
|
}
|
|
141
142
|
`;
|
|
142
143
|
var DELETE_PAYMENT_METHOD = `
|
|
143
|
-
mutation DeletePaymentMethod($id: ID!) {
|
|
144
|
-
deletePaymentMethod(id: $id)
|
|
144
|
+
mutation DeletePaymentMethod($billingAccountId: ID!, $id: ID!) {
|
|
145
|
+
deletePaymentMethod(billingAccountId: $billingAccountId, id: $id)
|
|
145
146
|
}
|
|
146
147
|
`;
|
|
147
148
|
var GRANT_CREDITS = `
|
|
@@ -154,7 +155,7 @@ var GRANT_CREDITS = `
|
|
|
154
155
|
var REQUEST_CREDIT_WITHDRAWAL = `
|
|
155
156
|
mutation RequestCreditWithdrawal($input: RequestCreditWithdrawalInput!) {
|
|
156
157
|
requestCreditWithdrawal(input: $input) {
|
|
157
|
-
id status
|
|
158
|
+
id status requestedAmount currency createdAt
|
|
158
159
|
}
|
|
159
160
|
}
|
|
160
161
|
`;
|
|
@@ -396,12 +397,17 @@ function registerBillingTools(server, ctx, track) {
|
|
|
396
397
|
track(mcpToolName(ctx.productName, "billing_invoices_get")),
|
|
397
398
|
{
|
|
398
399
|
title: "Get Invoice",
|
|
399
|
-
description: "Get an invoice by ID.",
|
|
400
|
-
inputSchema: {
|
|
400
|
+
description: "Get an invoice by ID (on the given or default billing account).",
|
|
401
|
+
inputSchema: {
|
|
402
|
+
id: zod.z.string().describe("Invoice ID"),
|
|
403
|
+
account: zod.z.string().optional().describe("Billing account ID (defaults to current)")
|
|
404
|
+
}
|
|
401
405
|
},
|
|
402
|
-
async ({ id }) => {
|
|
406
|
+
async ({ id, account }) => {
|
|
403
407
|
try {
|
|
408
|
+
const billingAccountId = await resolveBillingAccountId(ctx, account);
|
|
404
409
|
const data = await ctx.gql.global.request(GET_INVOICE, {
|
|
410
|
+
billingAccountId,
|
|
405
411
|
id
|
|
406
412
|
});
|
|
407
413
|
if (!data.getInvoice) return errorResult(`Invoice ${id} not found`);
|
|
@@ -419,11 +425,16 @@ function registerBillingTools(server, ctx, track) {
|
|
|
419
425
|
{
|
|
420
426
|
title: "Get Invoice PDF URL",
|
|
421
427
|
description: "Return the invoice PDF download URL. The actual PDF must be opened in a browser by the user.",
|
|
422
|
-
inputSchema: {
|
|
428
|
+
inputSchema: {
|
|
429
|
+
id: zod.z.string().describe("Invoice ID"),
|
|
430
|
+
account: zod.z.string().optional().describe("Billing account ID (defaults to current)")
|
|
431
|
+
}
|
|
423
432
|
},
|
|
424
|
-
async ({ id }) => {
|
|
433
|
+
async ({ id, account }) => {
|
|
425
434
|
try {
|
|
435
|
+
const billingAccountId = await resolveBillingAccountId(ctx, account);
|
|
426
436
|
const data = await ctx.gql.global.request(GET_INVOICE, {
|
|
437
|
+
billingAccountId,
|
|
427
438
|
id
|
|
428
439
|
});
|
|
429
440
|
if (!data.getInvoice?.pdfUrl) return errorResult(`Invoice ${id} has no pdfUrl`);
|
|
@@ -467,7 +478,15 @@ function registerBillingTools(server, ctx, track) {
|
|
|
467
478
|
title: "Add Payment Method",
|
|
468
479
|
description: "Add a payment method (card metadata only \u2014 provider handles secrets). Use the provider checkout URL elsewhere for full card capture.",
|
|
469
480
|
inputSchema: {
|
|
470
|
-
type: zod.z.enum([
|
|
481
|
+
type: zod.z.enum([
|
|
482
|
+
"CREDIT_CARD",
|
|
483
|
+
"DEBIT_CARD",
|
|
484
|
+
"BANK_TRANSFER",
|
|
485
|
+
"NETBANKING",
|
|
486
|
+
"WALLET",
|
|
487
|
+
"PAYPAL",
|
|
488
|
+
"CRYPTO"
|
|
489
|
+
]).describe("Payment method type"),
|
|
471
490
|
last4: zod.z.string().describe("Last 4 digits / identifier"),
|
|
472
491
|
brand: zod.z.string().optional().describe("Brand (Visa, MasterCard, etc.)"),
|
|
473
492
|
expiryMonth: zod.z.number().optional().describe("Expiry month (1-12)"),
|
|
@@ -505,15 +524,22 @@ function registerBillingTools(server, ctx, track) {
|
|
|
505
524
|
track(mcpToolName(ctx.productName, "billing_payment_methods_remove")),
|
|
506
525
|
{
|
|
507
526
|
title: "Remove Payment Method",
|
|
508
|
-
description: "Delete a payment method by ID.",
|
|
509
|
-
inputSchema: {
|
|
527
|
+
description: "Delete a payment method by ID (on the given or default billing account).",
|
|
528
|
+
inputSchema: {
|
|
529
|
+
id: zod.z.string().describe("Payment method ID"),
|
|
530
|
+
account: zod.z.string().optional().describe("Billing account ID (defaults to current)")
|
|
531
|
+
}
|
|
510
532
|
},
|
|
511
|
-
async ({ id }) => {
|
|
533
|
+
async ({ id, account }) => {
|
|
512
534
|
try {
|
|
513
|
-
await ctx
|
|
535
|
+
const billingAccountId = await resolveBillingAccountId(ctx, account);
|
|
536
|
+
const data = await ctx.gql.global.request(
|
|
514
537
|
DELETE_PAYMENT_METHOD,
|
|
515
|
-
{ id }
|
|
538
|
+
{ billingAccountId, id }
|
|
516
539
|
);
|
|
540
|
+
if (!data.deletePaymentMethod) {
|
|
541
|
+
return errorResult(`Payment method ${id} was not removed`);
|
|
542
|
+
}
|
|
517
543
|
return jsonResult({ status: "success", message: "Payment method removed", id });
|
|
518
544
|
} catch (error) {
|
|
519
545
|
ctx.logger.error("billing_payment_methods_remove failed", { error: String(error) });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/errors.ts","../../../src/core/tool-name.ts","../../../src/core/result.ts","../../../src/modules/billing/operations.ts","../../../src/modules/billing/tools.ts","../../../src/modules/billing/index.ts"],"names":["z"],"mappings":";;;;;;;;;;;;AA8BO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EACjB,KAAA;AAAA,EAEzB,WAAA,CAAY,SAAiB,KAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AACF,CAAA;;;AC1BA,IAAM,oBAAA,GA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,IAAA,GAAO,MAAM,GAAA,CAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAE/B,iBAAA,EAAmB,EAAE,gBAAA,EAAkB,SAAA,EAAW,cAAA,EAAgB,CAAA;AACrE,QAAA,OAAO,UAAA,CAAW,KAAK,iBAAiB,CAAA;AAAA,MAC1C,SAAS,KAAA,EAAO;AACd,QAAA,GAAA,CAAI,MAAA,CAAO,MAAM,2BAAA,EAA6B,EAAE,OAAO,MAAA,CAAO,KAAK,GAAG,CAAA;AACtE,QAAA,OAAO,WAAA;AAAA,UACL,0BAA0B,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,SAClF;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF;;;ACjlBA,IAAM,aAAA,GAA2B;AAAA,EAC/B,EAAA,EAAI,SAAA;AAAA,EACJ,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EAAa,SAAA;AAAA,EACb,SAAA,EAAW,CAAC,MAAM,CAAA;AAAA,EAClB,YAAA,EAAc,EAAE,KAAA,EAAO,EAAC,EAAE;AAAA,EAE1B,QAAA,CAAS,QAAmB,GAAA,EAAqC;AAC/D,IAAA,MAAM,QAAkB,EAAC;AACzB,IAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAsB;AACnC,MAAA,KAAA,CAAM,KAAK,CAAC,CAAA;AACZ,MAAA,OAAO,CAAA;AAAA,IACT,CAAA;AAEA,IAAA,oBAAA,CAAqB,MAAA,EAAQ,KAAK,KAAK,CAAA;AAEvC,IAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,EAAC,EAAG,OAAA,EAAS,EAAC,EAAE;AAAA,EAC7C;AACF,CAAA;AAEA,IAAO,eAAA,GAAQ","file":"index.cjs","sourcesContent":["/**\n * Error classes for MCP SDK.\n *\n * Modules MUST throw these instead of throwing raw Errors. The registerTool\n * wrapper in result.ts catches and maps them to MCP-protocol-compliant\n * `{ isError: true, content: [...] }` responses.\n *\n * Throwing past the wrapper to the protocol surfaces as JSON-RPC -32603 to\n * the client and is a protocol bug.\n */\n\nexport class McpUserError extends Error {\n public readonly hint: string | undefined;\n\n constructor(message: string, opts?: { hint?: string }) {\n super(message);\n this.name = 'McpUserError';\n this.hint = opts?.hint;\n }\n}\n\nexport class McpAuthError extends McpUserError {\n constructor(message: string, opts?: { hint?: string }) {\n super(message, {\n hint: opts?.hint ?? 'Run the auth_login tool to authenticate.',\n });\n this.name = 'McpAuthError';\n }\n}\n\nexport class McpInternalError extends Error {\n public override readonly cause: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'McpInternalError';\n this.cause = cause;\n }\n}\n","/**\n * Tool / resource / prompt naming helpers.\n *\n * Mandatory product prefix avoids collisions when Claude Desktop runs\n * multiple MCP servers concurrently (typical setup is ~6).\n *\n * Tool names are capped at 63 characters — Claude Desktop pre-1.x\n * truncated at 64 in some versions.\n */\n\nimport { McpInternalError } from './errors.js';\n\nconst MAX_TOOL_NAME_LENGTH = 63;\n\nfunction assertSafeName(name: string, kind: 'tool' | 'resource' | 'prompt'): string {\n if (kind === 'tool' && name.length > MAX_TOOL_NAME_LENGTH) {\n throw new McpInternalError(\n `Tool name '${name}' exceeds ${MAX_TOOL_NAME_LENGTH} characters (some MCP clients truncate at 64).`,\n );\n }\n return name;\n}\n\n/**\n * Build a tool name. Format: `<productName>_<...parts>` (snake_case).\n * Example: mcpToolName('vibecontrols', 'vibes', 'list') -> 'vibecontrols_vibes_list'\n */\nexport function mcpToolName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpToolName: productName is required');\n }\n const name = [productName, ...parts].filter(Boolean).join('_');\n return assertSafeName(name, 'tool');\n}\n\n/**\n * Build a resource URI. Format: `<productName>://<...parts>`.\n * Example: mcpResourceUri('vibecontrols', 'schema') -> 'vibecontrols://schema'\n */\nexport function mcpResourceUri(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpResourceUri: productName is required');\n }\n return `${productName}://${parts.filter(Boolean).join('/')}`;\n}\n\n/**\n * Build a prompt name. Format: `<productName>-<...parts>` (kebab-case).\n * Example: mcpPromptName('vibecontrols', 'setup') -> 'vibecontrols-setup'\n */\nexport function mcpPromptName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpPromptName: productName is required');\n }\n return [productName, ...parts].filter(Boolean).join('-');\n}\n\nexport const TOOL_NAME_LIMIT = MAX_TOOL_NAME_LENGTH;\n\n/**\n * Name-based hint heuristics for MCP `annotations` (readOnlyHint /\n * destructiveHint). Used by tool-governance.ts to auto-fill annotations for\n * the fleet of product modules that call `server.registerTool` directly\n * (bypassing the `registerTool()` core helper) and so never set them\n * explicitly today (BOFF-3903). Deliberately conservative — matched against\n * whole `_`-delimited segments so e.g. `timeentries_delete` and\n * `pomodoro_delete_goal` match, but a hypothetical `undeletable_check`\n * would not.\n *\n * The destructive verb set covers more than `delete`: stopping, killing or\n * terminating a running process, revoking or rotating a credential/share,\n * resetting settings and removing/purging/uninstalling are all actions an\n * MCP client must not auto-run without the user's intent (VC/FG parity G57 —\n * e.g. `vibecontrols_sessions_kill`, `vibecontrols_tunnels_rotate_credentials`\n * were previously reported as non-destructive).\n *\n * A module can always override the inference by passing an explicit\n * `annotations` object to `registerTool()` / `server.registerTool()` — do\n * that for the rare verb match that is harmless (e.g. a typing indicator's\n * `typing_stop`).\n */\nexport const DESTRUCTIVE_NAME_VERBS = [\n 'delete',\n 'destroy',\n 'erase',\n 'kill',\n 'purge',\n 'remove',\n 'reset',\n 'revoke',\n 'rotate',\n 'stop',\n 'terminate',\n 'uninstall',\n 'wipe',\n] as const;\nconst DESTRUCTIVE_NAME_SEGMENT = new RegExp(\n `(?:^|_)(?:${DESTRUCTIVE_NAME_VERBS.join('|')})(?:_|$)`,\n 'i',\n);\nconst READ_ONLY_NAME_SEGMENT = /(?:^|_)(?:list|get|search|check|read|count|stats|by_date)(?:_|$)/i;\n\n/** True when a tool name looks destructive (irreversibly deletes data) by naming convention. */\nexport function inferDestructiveHint(toolName: string): boolean {\n return DESTRUCTIVE_NAME_SEGMENT.test(toolName);\n}\n\n/**\n * True when a tool name looks read-only by naming convention. Never true for\n * a name that also looks destructive (a tool can't be both).\n */\nexport function inferReadOnlyHint(toolName: string): boolean {\n return !inferDestructiveHint(toolName) && READ_ONLY_NAME_SEGMENT.test(toolName);\n}\n","/**\n * MCP tool result helpers + central handler.\n *\n * Modules NEVER call server.registerTool directly — they use registerTool()\n * from this module so the central try/catch wraps the handler and:\n * - maps thrown McpUserError / McpAuthError / McpInternalError to\n * MCP-protocol-compliant `{ isError: true, content: [...] }` shapes\n * - threads `_meta.progressToken` into ctx.progress for long ops\n * - emits a structured log line on every error\n * - never leaks `cause` from McpInternalError to the client\n *\n * This is the analog of cli-sdk's createProgram() central error handler.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ZodRawShape } from 'zod';\nimport type { McpContext } from './context.js';\nimport { McpAuthError, McpInternalError, McpUserError } from './errors.js';\nimport type { ToolAnnotations } from './tool-governance.js';\n\nexport interface ToolTextContent {\n type: 'text';\n text: string;\n [k: string]: unknown;\n}\n\nexport interface ToolResult {\n content: ToolTextContent[];\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ToolMeta {\n progressToken?: string | number;\n}\n\n/**\n * Build a successful tool result with JSON content (pretty-printed).\n */\nexport function jsonResult(data: unknown, structured?: Record<string, unknown>): ToolResult {\n const result: ToolResult = {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n };\n if (structured !== undefined) {\n result.structuredContent = structured;\n }\n return result;\n}\n\n/**\n * Build a successful tool result with plain text content.\n */\nexport function textResult(text: string): ToolResult {\n return { content: [{ type: 'text', text }] };\n}\n\n/**\n * Build an error tool result. Honors MCP's `{ isError: true, content }` shape.\n * Optional hint is appended on a new line so the LLM can react.\n */\nexport function errorResult(message: string, hint?: string): ToolResult {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return { content: [{ type: 'text', text }], isError: true };\n}\n\nexport interface ToolMetadata {\n title: string;\n description: string;\n inputSchema?: ZodRawShape;\n /**\n * Explicit MCP annotations (readOnlyHint / destructiveHint / ...). Optional\n * — when omitted, `wrapServerWithToolGovernance` (applied centrally in\n * `createMcpServer`) infers them from the tool name. Set this to override\n * the inference for a tool whose name doesn't match the naming convention.\n */\n annotations?: ToolAnnotations;\n}\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n ctx: McpContext,\n meta: ToolMeta,\n) => Promise<unknown>;\n\n/**\n * Register a tool with the central error wrapper.\n *\n * The handler returns a plain value or void. The wrapper:\n * - wraps non-undefined returns in jsonResult()\n * - if the value already looks like a ToolResult (has `content`), passes through\n * - catches McpAuthError / McpUserError / McpInternalError / generic Error\n * - logs every error via ctx.logger.error\n */\nexport function registerTool<TArgs extends Record<string, unknown>>(\n server: McpServer,\n ctx: McpContext,\n name: string,\n metadata: ToolMetadata,\n handler: ToolHandler<TArgs>,\n): void {\n const sdkConfig = {\n title: metadata.title,\n description: metadata.description,\n ...(metadata.inputSchema ? { inputSchema: metadata.inputSchema } : {}),\n ...(metadata.annotations ? { annotations: metadata.annotations } : {}),\n };\n\n // The MCP SDK's registerTool signature is `(name, config, handler)`. The\n // handler arity depends on whether inputSchema is present (1-arg without,\n // 2-arg with). We accept a unified handler shape and dispatch at runtime.\n // The SDK's typing is strict and conditional on the inputSchema generic;\n // bypass with a cast since runtime acceptance is unconditional.\n const wrapped = async (...callbackArgs: unknown[]): Promise<ToolResult> => {\n const hasArgs = callbackArgs.length === 2;\n const args = (hasArgs ? callbackArgs[0] : {}) as TArgs;\n const extra = (hasArgs ? callbackArgs[1] : callbackArgs[0]) as\n { _meta?: { progressToken?: string | number } } | undefined;\n\n const progressToken = extra?._meta?.progressToken;\n const meta: ToolMeta = progressToken !== undefined ? { progressToken } : {};\n\n try {\n const result = await handler(args, ctx, meta);\n if (isToolResult(result)) return result;\n if (result === undefined) return textResult('OK');\n return jsonResult(result);\n } catch (error) {\n return mapErrorToResult(error, ctx, name);\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (server as any).registerTool(name, sdkConfig, wrapped);\n}\n\nfunction isToolResult(value: unknown): value is ToolResult {\n return (\n !!value &&\n typeof value === 'object' &&\n 'content' in value &&\n Array.isArray((value as ToolResult).content)\n );\n}\n\nfunction mapErrorToResult(error: unknown, ctx: McpContext, toolName: string): ToolResult {\n if (error instanceof McpAuthError) {\n ctx.logger.warn(`${toolName}: auth required`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpUserError) {\n ctx.logger.info(`${toolName}: user error`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpInternalError) {\n ctx.logger.error(`${toolName}: internal error`, {\n message: error.message,\n cause: stringifyCause(error.cause),\n });\n return errorResult(`Internal error in ${toolName}.`);\n }\n const message = error instanceof Error ? error.message : String(error);\n ctx.logger.error(`${toolName}: unhandled error`, { message });\n return errorResult(`${toolName}: ${message}`);\n}\n\nfunction stringifyCause(cause: unknown): string | undefined {\n if (cause === undefined || cause === null) return undefined;\n if (cause instanceof Error) return cause.message;\n try {\n return JSON.stringify(cause);\n } catch {\n return String(cause);\n }\n}\n","export const GET_DEFAULT_BILLING_ACCOUNT = `\n query GetDefaultBillingAccount {\n getDefaultBillingAccount {\n id creditAmount currency\n }\n }\n`;\n\nexport const GET_ACTIVE_SUBSCRIPTIONS = `\n query GetActiveSubscriptions($billingAccountId: ID!) {\n getActiveSubscriptions(billingAccountId: $billingAccountId) {\n id status seatCount nextBillingDate\n plan { name price currency }\n }\n }\n`;\n\nexport const GET_SUBSCRIPTION = `\n query GetSubscription($billingAccountId: ID!, $id: ID!) {\n getSubscription(billingAccountId: $billingAccountId, id: $id) {\n id status startDate endDate seatCount billingAccountId\n }\n }\n`;\n\nexport const UPDATE_SUBSCRIPTION_SEATS = `\n mutation UpdateSubscriptionSeats($input: UpdateSubscriptionSeatsInput!) {\n updateSubscriptionSeats(input: $input) {\n id seatCount lastSeatChangeAt\n }\n }\n`;\n\nexport const CANCEL_SUBSCRIPTION = `\n mutation CancelSubscription($input: CancelSubscriptionInput!) {\n cancelSubscription(input: $input) {\n id status canceledAt cancellationReason\n }\n }\n`;\n\n// BOFF-8183: the live supergraph exposes `PlansFilter` (no \"Input\" suffix);\n// `PlanFilterInput` is an mcp-libs artifact that the gateway rejects with\n// `Unknown type \"PlanFilterInput\"`. The filter is optional — we forward\n// it only when the caller actually provides one.\nexport const GET_ALL_PLANS = `\n query GetAllPlans($filter: PlansFilter) {\n getAllPlans(filter: $filter) {\n id name price currency duration pricingModel\n }\n }\n`;\n\nexport const GET_PLAN = `\n query GetPlan($id: ID!) {\n getPlan(id: $id) {\n id name price pricePerSeat minSeats maxSeats isActive\n }\n }\n`;\n\n// BOFF-8183 follow-up: same family as the plan filter — the live type is\n// `AddonsFilter` (no \"Input\" suffix). The `$limit` arg is supported and\n// forwarded as a connection-style cap.\nexport const GET_ALL_ADDONS = `\n query GetAllAddOns($filter: AddonsFilter, $limit: Int) {\n getAllAddOns(filter: $filter, limit: $limit) {\n id name price currency duration isActive\n }\n }\n`;\n\nexport const GET_PAGINATED_INVOICES = `\n query GetPaginatedInvoices($billingAccountId: ID!, $page: Int, $pageSize: Int) {\n getPaginatedInvoices(billingAccountId: $billingAccountId, page: $page, pageSize: $pageSize) {\n invoices { id invoiceNumber status total currency paidAt pdfUrl }\n totalCount hasMore\n }\n }\n`;\n\nexport const GET_INVOICE = `\n query GetInvoice($id: ID!) {\n getInvoice(id: $id) {\n id invoiceNumber status subtotal tax total\n items { description amount }\n }\n }\n`;\n\nexport const GET_PAYMENT_METHODS = `\n query GetPaymentMethods($billingAccountId: ID!) {\n getPaymentMethods(billingAccountId: $billingAccountId) {\n id type last4 expiryYear brand isDefault isVerified\n }\n }\n`;\n\nexport const ADD_PAYMENT_METHOD = `\n mutation AddPaymentMethod($input: AddPaymentMethodInput!) {\n addPaymentMethod(input: $input) {\n id type isDefault isVerified\n }\n }\n`;\n\nexport const DELETE_PAYMENT_METHOD = `\n mutation DeletePaymentMethod($id: ID!) {\n deletePaymentMethod(id: $id) { success }\n }\n`;\n\nexport const GRANT_CREDITS = `\n mutation GrantCredits($input: GrantCreditsInput!) {\n grantCredits(input: $input) {\n id amount status type\n }\n }\n`;\n\nexport const REQUEST_CREDIT_WITHDRAWAL = `\n mutation RequestCreditWithdrawal($input: RequestCreditWithdrawalInput!) {\n requestCreditWithdrawal(input: $input) {\n id status amount\n }\n }\n`;\n\nexport const GET_PENDING_REFUNDS = `\n query GetPendingRefunds($page: Int, $pageSize: Int) {\n getPendingRefunds(page: $page, pageSize: $pageSize) {\n records { id amount status source createdAt }\n totalCount\n }\n }\n`;\n\n// Live alpha requires BOTH `billingAccountId` and `subscriptionId` for\n// `getAllQuotasOfSub`; passing only `subscriptionId` returned\n// \"Field getAllQuotasOfSub argument billingAccountId of type ID! is\n// required\". The MCP tool already takes `billingAccountId` as a required\n// arg — we just need to forward it.\nexport const GET_QUOTAS_OF_SUB = `\n query GetQuotas($billingAccountId: ID!, $subscriptionId: ID!) {\n getAllQuotasOfSub(billingAccountId: $billingAccountId, subscriptionId: $subscriptionId) {\n id name limits currentUsageSum reusable\n }\n }\n`;\n","/**\n * Billing module tools — subscriptions, plans, addons, invoices,\n * payment-methods, credits, refunds, quotas.\n *\n * Backend: ~/products/global/billing/global-billing-svc/.\n * Ported from cli-sdk/src/modules/billing/. The CLI's stdin/options become\n * MCP tool arguments. Browser-redirect commands (Stripe checkout) are not\n * present in the source; the closest analogue (`invoices download`) returns a\n * URL — exposed here as `billing_invoices_get_pdf_url`.\n */\n\nimport { z } from 'zod';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { jsonResult, errorResult, mcpToolName, type McpContext } from '../../core/index.js';\nimport {\n GET_DEFAULT_BILLING_ACCOUNT,\n GET_ACTIVE_SUBSCRIPTIONS,\n GET_SUBSCRIPTION,\n UPDATE_SUBSCRIPTION_SEATS,\n CANCEL_SUBSCRIPTION,\n GET_ALL_PLANS,\n GET_PLAN,\n GET_ALL_ADDONS,\n GET_PAGINATED_INVOICES,\n GET_INVOICE,\n GET_PAYMENT_METHODS,\n ADD_PAYMENT_METHOD,\n DELETE_PAYMENT_METHOD,\n GRANT_CREDITS,\n REQUEST_CREDIT_WITHDRAWAL,\n GET_PENDING_REFUNDS,\n GET_QUOTAS_OF_SUB,\n} from './operations.js';\n\ninterface SubRow {\n id: string;\n status?: string;\n seatCount?: number;\n nextBillingDate?: string;\n plan?: { name: string; price?: number; currency?: string };\n}\n\ninterface PlanRow {\n id: string;\n name: string;\n price?: number;\n currency?: string;\n duration?: string;\n pricingModel?: string;\n isActive?: boolean;\n}\n\ninterface InvoiceRow {\n id: string;\n invoiceNumber?: string;\n status?: string;\n total?: number;\n currency?: string;\n paidAt?: string;\n pdfUrl?: string;\n}\n\ninterface PaymentMethodRow {\n id: string;\n type: string;\n last4?: string;\n brand?: string;\n isDefault?: boolean;\n isVerified?: boolean;\n}\n\ninterface BillingAccountRow {\n id: string;\n creditAmount?: number;\n currency?: string;\n}\n\nasync function resolveBillingAccountId(\n ctx: McpContext,\n override: string | undefined,\n): Promise<string> {\n if (override !== undefined && override !== '') return override;\n const data = await ctx.gql.global.request<{\n getDefaultBillingAccount: BillingAccountRow | null;\n }>(GET_DEFAULT_BILLING_ACCOUNT);\n if (!data.getDefaultBillingAccount?.id) {\n throw new Error('No default billing account on file. Pass account explicitly.');\n }\n return data.getDefaultBillingAccount.id;\n}\n\nexport function registerBillingTools(\n server: McpServer,\n ctx: McpContext,\n track: (n: string) => string,\n): void {\n // ── Subscriptions ──────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_list')),\n {\n title: 'List Subscriptions',\n description: 'List active subscriptions on a billing account (defaults to current).',\n inputSchema: {\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ getActiveSubscriptions: SubRow[] }>(\n GET_ACTIVE_SUBSCRIPTIONS,\n { billingAccountId },\n );\n return jsonResult(data.getActiveSubscriptions);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_list failed', { error: String(error) });\n return errorResult(\n `Failed to list subscriptions: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_get')),\n {\n title: 'Get Subscription',\n description:\n 'Get a subscription by ID. Live alpha requires BOTH `billingAccountId` and `id`; the missing `billingAccountId` was rejected with \"argument billingAccountId of type ID! is required\". The MCP tool forwards the default billing account id when the caller omits one.',\n inputSchema: {\n id: z.string().describe('Subscription ID'),\n billingAccountId: z\n .string()\n .optional()\n .describe(\n \"Billing account ID (defaults to the caller's default billing account when omitted)\",\n ),\n },\n },\n async ({ id, billingAccountId }) => {\n try {\n const accountId =\n billingAccountId ?? (await resolveBillingAccountId(ctx, billingAccountId));\n if (!accountId) {\n return errorResult(\n 'No billing account id; pass `billingAccountId` or ensure `getDefaultBillingAccount` is callable for the caller.',\n );\n }\n const data = await ctx.gql.global.request<{ getSubscription: SubRow | null }>(\n GET_SUBSCRIPTION,\n { billingAccountId: accountId, id },\n );\n if (!data.getSubscription) return errorResult(`Subscription ${id} not found`);\n return jsonResult(data.getSubscription);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_get failed', { error: String(error) });\n return errorResult(\n `Failed to get subscription: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_upgrade')),\n {\n title: 'Update Subscription Seats',\n description: 'Change the seat count on a subscription.',\n inputSchema: {\n id: z.string().describe('Subscription ID'),\n seats: z.number().describe('Target seat count'),\n },\n },\n async ({ id, seats }) => {\n try {\n const input: Record<string, unknown> = { subscriptionId: id, seatCount: seats };\n const data = await ctx.gql.global.request<{ updateSubscriptionSeats: SubRow }>(\n UPDATE_SUBSCRIPTION_SEATS,\n { input },\n );\n return jsonResult(data.updateSubscriptionSeats);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_upgrade failed', { error: String(error) });\n return errorResult(\n `Failed to update seats: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_cancel')),\n {\n title: 'Cancel Subscription',\n description: 'Cancel a subscription with an optional reason.',\n inputSchema: {\n id: z.string().describe('Subscription ID'),\n reason: z.string().optional().describe('Cancellation reason'),\n },\n },\n async ({ id, reason }) => {\n try {\n const input: Record<string, unknown> = { subscriptionId: id };\n if (reason !== undefined) input.reason = reason;\n const data = await ctx.gql.global.request<{ cancelSubscription: SubRow }>(\n CANCEL_SUBSCRIPTION,\n { input },\n );\n return jsonResult(data.cancelSubscription);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_cancel failed', { error: String(error) });\n return errorResult(\n `Failed to cancel subscription: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Plans ──────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_plans_list')),\n {\n title: 'List Plans',\n description: 'List available plans, optionally filtered by product.',\n inputSchema: {\n product: z.string().optional().describe('Product ID filter'),\n },\n },\n async ({ product }) => {\n try {\n const filter: Record<string, unknown> = {};\n if (product !== undefined) filter.productId = product;\n const data = await ctx.gql.global.request<{ getAllPlans: PlanRow[] }>(GET_ALL_PLANS, {\n filter: Object.keys(filter).length ? filter : undefined,\n });\n return jsonResult(data.getAllPlans);\n } catch (error) {\n ctx.logger.error('billing_plans_list failed', { error: String(error) });\n return errorResult(\n `Failed to list plans: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_plans_get')),\n {\n title: 'Get Plan',\n description: 'Get a plan by ID.',\n inputSchema: { id: z.string().describe('Plan ID') },\n },\n async ({ id }) => {\n try {\n const data = await ctx.gql.global.request<{ getPlan: PlanRow | null }>(GET_PLAN, { id });\n if (!data.getPlan) return errorResult(`Plan ${id} not found`);\n return jsonResult(data.getPlan);\n } catch (error) {\n ctx.logger.error('billing_plans_get failed', { error: String(error) });\n return errorResult(\n `Failed to get plan: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Addons ─────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_addons_list')),\n {\n title: 'List Addons',\n description: 'List addons, optionally filtered by product.',\n inputSchema: {\n product: z.string().optional().describe('Product ID filter'),\n limit: z.number().optional().describe('Page size (default 50)'),\n },\n },\n async ({ product, limit }) => {\n try {\n const filter: Record<string, unknown> = {};\n if (product !== undefined) filter.productId = product;\n const data = await ctx.gql.global.request<{ getAllAddOns: PlanRow[] }>(GET_ALL_ADDONS, {\n filter: Object.keys(filter).length ? filter : undefined,\n limit,\n });\n return jsonResult(data.getAllAddOns);\n } catch (error) {\n ctx.logger.error('billing_addons_list failed', { error: String(error) });\n return errorResult(\n `Failed to list addons: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Invoices ───────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_invoices_list')),\n {\n title: 'List Invoices',\n description: 'Paginated list of invoices on a billing account.',\n inputSchema: {\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n page: z.number().optional().describe('Page number (default 1)'),\n pageSize: z.number().optional().describe('Page size (default 20)'),\n },\n },\n async ({ account, page, pageSize }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{\n getPaginatedInvoices: { invoices: InvoiceRow[]; totalCount: number };\n }>(GET_PAGINATED_INVOICES, { billingAccountId, page, pageSize });\n return jsonResult(data.getPaginatedInvoices);\n } catch (error) {\n ctx.logger.error('billing_invoices_list failed', { error: String(error) });\n return errorResult(\n `Failed to list invoices: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_invoices_get')),\n {\n title: 'Get Invoice',\n description: 'Get an invoice by ID.',\n inputSchema: { id: z.string().describe('Invoice ID') },\n },\n async ({ id }) => {\n try {\n const data = await ctx.gql.global.request<{ getInvoice: InvoiceRow | null }>(GET_INVOICE, {\n id,\n });\n if (!data.getInvoice) return errorResult(`Invoice ${id} not found`);\n return jsonResult(data.getInvoice);\n } catch (error) {\n ctx.logger.error('billing_invoices_get failed', { error: String(error) });\n return errorResult(\n `Failed to get invoice: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // Browser-redirect analogue: returns the PDF URL for the LLM to share.\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_invoices_get_pdf_url')),\n {\n title: 'Get Invoice PDF URL',\n description:\n 'Return the invoice PDF download URL. The actual PDF must be opened in a browser by the user.',\n inputSchema: { id: z.string().describe('Invoice ID') },\n },\n async ({ id }) => {\n try {\n const data = await ctx.gql.global.request<{ getInvoice: InvoiceRow | null }>(GET_INVOICE, {\n id,\n });\n if (!data.getInvoice?.pdfUrl) return errorResult(`Invoice ${id} has no pdfUrl`);\n return jsonResult({ url: data.getInvoice.pdfUrl });\n } catch (error) {\n ctx.logger.error('billing_invoices_get_pdf_url failed', { error: String(error) });\n return errorResult(\n `Failed to fetch invoice URL: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Payment methods ────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_payment_methods_list')),\n {\n title: 'List Payment Methods',\n description: 'List payment methods on a billing account.',\n inputSchema: {\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ getPaymentMethods: PaymentMethodRow[] }>(\n GET_PAYMENT_METHODS,\n { billingAccountId },\n );\n return jsonResult(data.getPaymentMethods);\n } catch (error) {\n ctx.logger.error('billing_payment_methods_list failed', { error: String(error) });\n return errorResult(\n `Failed to list payment methods: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_payment_methods_add')),\n {\n title: 'Add Payment Method',\n description:\n 'Add a payment method (card metadata only — provider handles secrets). Use the provider checkout URL elsewhere for full card capture.',\n inputSchema: {\n type: z.enum(['CREDIT_CARD', 'BANK', 'UPI']).describe('Payment method type'),\n last4: z.string().describe('Last 4 digits / identifier'),\n brand: z.string().optional().describe('Brand (Visa, MasterCard, etc.)'),\n expiryMonth: z.number().optional().describe('Expiry month (1-12)'),\n expiryYear: z.number().optional().describe('Expiry year (4 digits)'),\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n isDefault: z.boolean().optional().describe('Make it the default'),\n },\n },\n async ({ type, last4, brand, expiryMonth, expiryYear, account, isDefault }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const input: Record<string, unknown> = {\n billingAccountId,\n type,\n last4,\n isDefault: isDefault === true,\n };\n if (brand !== undefined) input.brand = brand;\n if (expiryMonth !== undefined) input.expiryMonth = expiryMonth;\n if (expiryYear !== undefined) input.expiryYear = expiryYear;\n\n const data = await ctx.gql.global.request<{ addPaymentMethod: PaymentMethodRow }>(\n ADD_PAYMENT_METHOD,\n { input },\n );\n return jsonResult(data.addPaymentMethod);\n } catch (error) {\n ctx.logger.error('billing_payment_methods_add failed', { error: String(error) });\n return errorResult(\n `Failed to add payment method: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_payment_methods_remove')),\n {\n title: 'Remove Payment Method',\n description: 'Delete a payment method by ID.',\n inputSchema: { id: z.string().describe('Payment method ID') },\n },\n async ({ id }) => {\n try {\n await ctx.gql.global.request<{ deletePaymentMethod: { success: boolean } }>(\n DELETE_PAYMENT_METHOD,\n { id },\n );\n return jsonResult({ status: 'success', message: 'Payment method removed', id });\n } catch (error) {\n ctx.logger.error('billing_payment_methods_remove failed', { error: String(error) });\n return errorResult(\n `Failed to remove payment method: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Credits ────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_credits_balance')),\n {\n title: 'Credit Balance',\n description: 'Show current credit balance on the default billing account.',\n inputSchema: {},\n },\n async () => {\n try {\n const data = await ctx.gql.global.request<{\n getDefaultBillingAccount: BillingAccountRow | null;\n }>(GET_DEFAULT_BILLING_ACCOUNT);\n return jsonResult(data.getDefaultBillingAccount);\n } catch (error) {\n ctx.logger.error('billing_credits_balance failed', { error: String(error) });\n return errorResult(\n `Failed to read balance: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_credits_grant')),\n {\n title: 'Grant Credits',\n description: 'Grant credits to a billing account (admin only).',\n inputSchema: {\n account: z.string().describe('Billing account ID'),\n amount: z.number().describe('Amount to grant'),\n reason: z.string().optional().describe('Reason for grant'),\n },\n },\n async ({ account, amount, reason }) => {\n try {\n const input: Record<string, unknown> = {\n billingAccountId: account,\n amount,\n reason: reason ?? 'mcp-grant',\n };\n await ctx.gql.global.request(GRANT_CREDITS, { input });\n return jsonResult({ status: 'success', message: 'Credits granted', amount, account });\n } catch (error) {\n ctx.logger.error('billing_credits_grant failed', { error: String(error) });\n return errorResult(\n `Failed to grant credits: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_credits_withdraw')),\n {\n title: 'Withdraw Credits',\n description: 'Request a credit withdrawal to a payout account.',\n inputSchema: {\n account: z.string().describe('Billing account ID'),\n amount: z.number().describe('Amount to withdraw'),\n payout: z.string().describe('Payout account ID'),\n },\n },\n async ({ account, amount, payout }) => {\n try {\n const input: Record<string, unknown> = {\n billingAccountId: account,\n creditAmount: amount,\n payoutAccountId: payout,\n };\n await ctx.gql.global.request(REQUEST_CREDIT_WITHDRAWAL, { input });\n return jsonResult({ status: 'success', message: 'Withdrawal requested', amount, account });\n } catch (error) {\n ctx.logger.error('billing_credits_withdraw failed', { error: String(error) });\n return errorResult(\n `Failed to request withdrawal: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Refunds ────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_refunds_list')),\n {\n title: 'List Pending Refunds',\n description: 'List pending refund records (paginated).',\n inputSchema: {\n page: z.number().optional().describe('Page number (default 0)'),\n pageSize: z.number().optional().describe('Page size (default 20)'),\n },\n },\n async ({ page, pageSize }) => {\n try {\n const data = await ctx.gql.global.request<{\n getPendingRefunds: { records: Array<Record<string, unknown>>; totalCount: number };\n }>(GET_PENDING_REFUNDS, { page, pageSize });\n return jsonResult(data.getPendingRefunds);\n } catch (error) {\n ctx.logger.error('billing_refunds_list failed', { error: String(error) });\n return errorResult(\n `Failed to list refunds: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Quota ──────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_quota_list')),\n {\n title: 'List Subscription Quotas',\n description:\n 'Get all quotas for a subscription. Live alpha requires BOTH `billingAccountId` and `subscriptionId`; the missing `billingAccountId` was rejected with \"argument billingAccountId of type ID! is required\". The MCP tool falls back to the caller\\'s default billing account when the caller omits one.',\n inputSchema: {\n subscriptionId: z.string().describe('Subscription ID'),\n billingAccountId: z\n .string()\n .optional()\n .describe(\n \"Billing account ID (defaults to the caller's default billing account when omitted)\",\n ),\n },\n },\n async ({ subscriptionId, billingAccountId }) => {\n try {\n const accountId = await resolveBillingAccountId(ctx, billingAccountId);\n const data = await ctx.gql.global.request<{\n getAllQuotasOfSub: Array<Record<string, unknown>>;\n }>(GET_QUOTAS_OF_SUB, { billingAccountId: accountId, subscriptionId });\n return jsonResult(data.getAllQuotasOfSub);\n } catch (error) {\n ctx.logger.error('billing_quota_list failed', { error: String(error) });\n return errorResult(\n `Failed to list quotas: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n}\n","/**\n * Billing module — subscriptions, plans, addons, invoices, payment-methods,\n * credits, refunds, quotas. Backend: ~/products/global/billing/global-billing-svc/.\n * Ported from cli-sdk/src/modules/billing/.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { McpContext, McpModule, ModuleRegistration } from '../../core/index.js';\nimport { registerBillingTools } from './tools.js';\n\nconst billingModule: McpModule = {\n id: 'billing',\n version: '0.0.1',\n displayName: 'Billing',\n dependsOn: ['auth'],\n capabilities: { tools: {} },\n\n register(server: McpServer, ctx: McpContext): ModuleRegistration {\n const tools: string[] = [];\n const track = (n: string): string => {\n tools.push(n);\n return n;\n };\n\n registerBillingTools(server, ctx, track);\n\n return { tools, resources: [], prompts: [] };\n },\n};\n\nexport default billingModule;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/errors.ts","../../../src/core/tool-name.ts","../../../src/core/result.ts","../../../src/modules/billing/operations.ts","../../../src/modules/billing/tools.ts","../../../src/modules/billing/index.ts"],"names":["z"],"mappings":";;;;;;;;;;;;AA8BO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EACjB,KAAA;AAAA,EAEzB,WAAA,CAAY,SAAiB,KAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AACF,CAAA;;;AC1BA,IAAM,oBAAA,GAAuB,EAAA;AAE7B,SAAS,cAAA,CAAe,MAAc,IAAA,EAA8C;AAClF,EAAA,IAAuB,IAAA,CAAK,MAAA,GA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2B;AAAA,EAC/B,EAAA,EAAI,SAAA;AAAA,EACJ,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EAAa,SAAA;AAAA,EACb,SAAA,EAAW,CAAC,MAAM,CAAA;AAAA,EAClB,YAAA,EAAc,EAAE,KAAA,EAAO,EAAC,EAAE;AAAA,EAE1B,QAAA,CAAS,QAAmB,GAAA,EAAqC;AAC/D,IAAA,MAAM,QAAkB,EAAC;AACzB,IAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAsB;AACnC,MAAA,KAAA,CAAM,KAAK,CAAC,CAAA;AACZ,MAAA,OAAO,CAAA;AAAA,IACT,CAAA;AAEA,IAAA,oBAAA,CAAqB,MAAA,EAAQ,KAAK,KAAK,CAAA;AAEvC,IAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,EAAC,EAAG,OAAA,EAAS,EAAC,EAAE;AAAA,EAC7C;AACF,CAAA;AAEA,IAAO,eAAA,GAAQ","file":"index.cjs","sourcesContent":["/**\n * Error classes for MCP SDK.\n *\n * Modules MUST throw these instead of throwing raw Errors. The registerTool\n * wrapper in result.ts catches and maps them to MCP-protocol-compliant\n * `{ isError: true, content: [...] }` responses.\n *\n * Throwing past the wrapper to the protocol surfaces as JSON-RPC -32603 to\n * the client and is a protocol bug.\n */\n\nexport class McpUserError extends Error {\n public readonly hint: string | undefined;\n\n constructor(message: string, opts?: { hint?: string }) {\n super(message);\n this.name = 'McpUserError';\n this.hint = opts?.hint;\n }\n}\n\nexport class McpAuthError extends McpUserError {\n constructor(message: string, opts?: { hint?: string }) {\n super(message, {\n hint: opts?.hint ?? 'Run the auth_login tool to authenticate.',\n });\n this.name = 'McpAuthError';\n }\n}\n\nexport class McpInternalError extends Error {\n public override readonly cause: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'McpInternalError';\n this.cause = cause;\n }\n}\n","/**\n * Tool / resource / prompt naming helpers.\n *\n * Mandatory product prefix avoids collisions when Claude Desktop runs\n * multiple MCP servers concurrently (typical setup is ~6).\n *\n * Tool names are capped at 63 characters — Claude Desktop pre-1.x\n * truncated at 64 in some versions.\n */\n\nimport { McpInternalError } from './errors.js';\n\nconst MAX_TOOL_NAME_LENGTH = 63;\n\nfunction assertSafeName(name: string, kind: 'tool' | 'resource' | 'prompt'): string {\n if (kind === 'tool' && name.length > MAX_TOOL_NAME_LENGTH) {\n throw new McpInternalError(\n `Tool name '${name}' exceeds ${MAX_TOOL_NAME_LENGTH} characters (some MCP clients truncate at 64).`,\n );\n }\n return name;\n}\n\n/**\n * Build a tool name. Format: `<productName>_<...parts>` (snake_case).\n * Example: mcpToolName('vibecontrols', 'vibes', 'list') -> 'vibecontrols_vibes_list'\n */\nexport function mcpToolName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpToolName: productName is required');\n }\n const name = [productName, ...parts].filter(Boolean).join('_');\n return assertSafeName(name, 'tool');\n}\n\n/**\n * Build a resource URI. Format: `<productName>://<...parts>`.\n * Example: mcpResourceUri('vibecontrols', 'schema') -> 'vibecontrols://schema'\n */\nexport function mcpResourceUri(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpResourceUri: productName is required');\n }\n return `${productName}://${parts.filter(Boolean).join('/')}`;\n}\n\n/**\n * Build a prompt name. Format: `<productName>-<...parts>` (kebab-case).\n * Example: mcpPromptName('vibecontrols', 'setup') -> 'vibecontrols-setup'\n */\nexport function mcpPromptName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpPromptName: productName is required');\n }\n return [productName, ...parts].filter(Boolean).join('-');\n}\n\nexport const TOOL_NAME_LIMIT = MAX_TOOL_NAME_LENGTH;\n\n/**\n * Name-based hint heuristics for MCP `annotations` (readOnlyHint /\n * destructiveHint). Used by tool-governance.ts to auto-fill annotations for\n * the fleet of product modules that call `server.registerTool` directly\n * (bypassing the `registerTool()` core helper) and so never set them\n * explicitly today (BOFF-3903). Deliberately conservative — matched against\n * whole `_`-delimited segments so e.g. `timeentries_delete` and\n * `pomodoro_delete_goal` match, but a hypothetical `undeletable_check`\n * would not.\n *\n * The destructive verb set covers more than `delete`: stopping, killing or\n * terminating a running process, revoking or rotating a credential/share,\n * resetting settings and removing/purging/uninstalling are all actions an\n * MCP client must not auto-run without the user's intent (VC/FG parity G57 —\n * e.g. `vibecontrols_sessions_kill`, `vibecontrols_tunnels_rotate_credentials`\n * were previously reported as non-destructive).\n *\n * A module can always override the inference by passing an explicit\n * `annotations` object to `registerTool()` / `server.registerTool()` — do\n * that for the rare verb match that is harmless (e.g. a typing indicator's\n * `typing_stop`).\n */\nexport const DESTRUCTIVE_NAME_VERBS = [\n 'delete',\n 'destroy',\n 'erase',\n 'kill',\n 'purge',\n 'remove',\n 'reset',\n 'revoke',\n 'rotate',\n 'stop',\n 'terminate',\n 'uninstall',\n 'wipe',\n] as const;\nconst DESTRUCTIVE_NAME_SEGMENT = new RegExp(\n `(?:^|_)(?:${DESTRUCTIVE_NAME_VERBS.join('|')})(?:_|$)`,\n 'i',\n);\nconst READ_ONLY_NAME_SEGMENT = /(?:^|_)(?:list|get|search|check|read|count|stats|by_date)(?:_|$)/i;\n\n/** True when a tool name looks destructive (irreversibly deletes data) by naming convention. */\nexport function inferDestructiveHint(toolName: string): boolean {\n return DESTRUCTIVE_NAME_SEGMENT.test(toolName);\n}\n\n/**\n * True when a tool name looks read-only by naming convention. Never true for\n * a name that also looks destructive (a tool can't be both).\n */\nexport function inferReadOnlyHint(toolName: string): boolean {\n return !inferDestructiveHint(toolName) && READ_ONLY_NAME_SEGMENT.test(toolName);\n}\n","/**\n * MCP tool result helpers + central handler.\n *\n * Modules NEVER call server.registerTool directly — they use registerTool()\n * from this module so the central try/catch wraps the handler and:\n * - maps thrown McpUserError / McpAuthError / McpInternalError to\n * MCP-protocol-compliant `{ isError: true, content: [...] }` shapes\n * - threads `_meta.progressToken` into ctx.progress for long ops\n * - emits a structured log line on every error\n * - never leaks `cause` from McpInternalError to the client\n *\n * This is the analog of cli-sdk's createProgram() central error handler.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ZodRawShape } from 'zod';\nimport type { McpContext } from './context.js';\nimport { McpAuthError, McpInternalError, McpUserError } from './errors.js';\nimport type { ToolAnnotations } from './tool-governance.js';\n\nexport interface ToolTextContent {\n type: 'text';\n text: string;\n [k: string]: unknown;\n}\n\nexport interface ToolResult {\n content: ToolTextContent[];\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ToolMeta {\n progressToken?: string | number;\n}\n\n/**\n * Build a successful tool result with JSON content (pretty-printed).\n */\nexport function jsonResult(data: unknown, structured?: Record<string, unknown>): ToolResult {\n const result: ToolResult = {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n };\n if (structured !== undefined) {\n result.structuredContent = structured;\n }\n return result;\n}\n\n/**\n * Build a successful tool result with plain text content.\n */\nexport function textResult(text: string): ToolResult {\n return { content: [{ type: 'text', text }] };\n}\n\n/**\n * Build an error tool result. Honors MCP's `{ isError: true, content }` shape.\n * Optional hint is appended on a new line so the LLM can react.\n */\nexport function errorResult(message: string, hint?: string): ToolResult {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return { content: [{ type: 'text', text }], isError: true };\n}\n\nexport interface ToolMetadata {\n title: string;\n description: string;\n inputSchema?: ZodRawShape;\n /**\n * Explicit MCP annotations (readOnlyHint / destructiveHint / ...). Optional\n * — when omitted, `wrapServerWithToolGovernance` (applied centrally in\n * `createMcpServer`) infers them from the tool name. Set this to override\n * the inference for a tool whose name doesn't match the naming convention.\n */\n annotations?: ToolAnnotations;\n}\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n ctx: McpContext,\n meta: ToolMeta,\n) => Promise<unknown>;\n\n/**\n * Register a tool with the central error wrapper.\n *\n * The handler returns a plain value or void. The wrapper:\n * - wraps non-undefined returns in jsonResult()\n * - if the value already looks like a ToolResult (has `content`), passes through\n * - catches McpAuthError / McpUserError / McpInternalError / generic Error\n * - logs every error via ctx.logger.error\n */\nexport function registerTool<TArgs extends Record<string, unknown>>(\n server: McpServer,\n ctx: McpContext,\n name: string,\n metadata: ToolMetadata,\n handler: ToolHandler<TArgs>,\n): void {\n const sdkConfig = {\n title: metadata.title,\n description: metadata.description,\n ...(metadata.inputSchema ? { inputSchema: metadata.inputSchema } : {}),\n ...(metadata.annotations ? { annotations: metadata.annotations } : {}),\n };\n\n // The MCP SDK's registerTool signature is `(name, config, handler)`. The\n // handler arity depends on whether inputSchema is present (1-arg without,\n // 2-arg with). We accept a unified handler shape and dispatch at runtime.\n // The SDK's typing is strict and conditional on the inputSchema generic;\n // bypass with a cast since runtime acceptance is unconditional.\n const wrapped = async (...callbackArgs: unknown[]): Promise<ToolResult> => {\n const hasArgs = callbackArgs.length === 2;\n const args = (hasArgs ? callbackArgs[0] : {}) as TArgs;\n const extra = (hasArgs ? callbackArgs[1] : callbackArgs[0]) as\n { _meta?: { progressToken?: string | number } } | undefined;\n\n const progressToken = extra?._meta?.progressToken;\n const meta: ToolMeta = progressToken !== undefined ? { progressToken } : {};\n\n try {\n const result = await handler(args, ctx, meta);\n if (isToolResult(result)) return result;\n if (result === undefined) return textResult('OK');\n return jsonResult(result);\n } catch (error) {\n return mapErrorToResult(error, ctx, name);\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (server as any).registerTool(name, sdkConfig, wrapped);\n}\n\nfunction isToolResult(value: unknown): value is ToolResult {\n return (\n !!value &&\n typeof value === 'object' &&\n 'content' in value &&\n Array.isArray((value as ToolResult).content)\n );\n}\n\nfunction mapErrorToResult(error: unknown, ctx: McpContext, toolName: string): ToolResult {\n if (error instanceof McpAuthError) {\n ctx.logger.warn(`${toolName}: auth required`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpUserError) {\n ctx.logger.info(`${toolName}: user error`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpInternalError) {\n ctx.logger.error(`${toolName}: internal error`, {\n message: error.message,\n cause: stringifyCause(error.cause),\n });\n return errorResult(`Internal error in ${toolName}.`);\n }\n const message = error instanceof Error ? error.message : String(error);\n ctx.logger.error(`${toolName}: unhandled error`, { message });\n return errorResult(`${toolName}: ${message}`);\n}\n\nfunction stringifyCause(cause: unknown): string | undefined {\n if (cause === undefined || cause === null) return undefined;\n if (cause instanceof Error) return cause.message;\n try {\n return JSON.stringify(cause);\n } catch {\n return String(cause);\n }\n}\n","export const GET_DEFAULT_BILLING_ACCOUNT = `\n query GetDefaultBillingAccount {\n getDefaultBillingAccount {\n id creditAmount currency\n }\n }\n`;\n\nexport const GET_ACTIVE_SUBSCRIPTIONS = `\n query GetActiveSubscriptions($billingAccountId: ID!) {\n getActiveSubscriptions(billingAccountId: $billingAccountId) {\n id status seatCount nextBillingDate\n plan { name price currency }\n }\n }\n`;\n\nexport const GET_SUBSCRIPTION = `\n query GetSubscription($billingAccountId: ID!, $id: ID!) {\n getSubscription(billingAccountId: $billingAccountId, id: $id) {\n id status startDate endDate seatCount billingAccountId\n }\n }\n`;\n\nexport const UPDATE_SUBSCRIPTION_SEATS = `\n mutation UpdateSubscriptionSeats($input: UpdateSubscriptionSeatsInput!) {\n updateSubscriptionSeats(input: $input) {\n id seatCount lastSeatChangeAt\n }\n }\n`;\n\nexport const CANCEL_SUBSCRIPTION = `\n mutation CancelSubscription($input: CancelSubscriptionInput!) {\n cancelSubscription(input: $input) {\n id status canceledAt cancellationReason\n }\n }\n`;\n\n// BOFF-8183: the live supergraph exposes `PlansFilter` (no \"Input\" suffix);\n// `PlanFilterInput` is an mcp-libs artifact that the gateway rejects with\n// `Unknown type \"PlanFilterInput\"`. The filter is optional — we forward\n// it only when the caller actually provides one.\nexport const GET_ALL_PLANS = `\n query GetAllPlans($filter: PlansFilter) {\n getAllPlans(filter: $filter) {\n id name price currency duration pricingModel\n }\n }\n`;\n\nexport const GET_PLAN = `\n query GetPlan($id: ID!) {\n getPlan(id: $id) {\n id name price pricePerSeat minSeats maxSeats isActive\n }\n }\n`;\n\n// BOFF-8183 follow-up: same family as the plan filter — the live type is\n// `AddonsFilter` (no \"Input\" suffix). The `$limit` arg is supported and\n// forwarded as a connection-style cap.\nexport const GET_ALL_ADDONS = `\n query GetAllAddOns($filter: AddonsFilter, $limit: Int) {\n getAllAddOns(filter: $filter, limit: $limit) {\n id name price currency duration isActive\n }\n }\n`;\n\nexport const GET_PAGINATED_INVOICES = `\n query GetPaginatedInvoices($billingAccountId: ID!, $page: Int, $pageSize: Int) {\n getPaginatedInvoices(billingAccountId: $billingAccountId, page: $page, pageSize: $pageSize) {\n invoices { id invoiceNumber status total currency paidAt pdfUrl }\n totalCount hasMore\n }\n }\n`;\n\n// getInvoice, deletePaymentMethod and addPaymentMethod are all scoped to a\n// billing account on global-billing-svc, and deletePaymentMethod returns a\n// bare Boolean (BOFF-4413 supergraph contract).\nexport const GET_INVOICE = `\n query GetInvoice($billingAccountId: ID!, $id: ID!) {\n getInvoice(billingAccountId: $billingAccountId, id: $id) {\n id invoiceNumber status currency subtotal tax total amountPaid dueDate paidAt\n pdfUrl invoiceUrl\n items { description quantity unitPrice amount }\n }\n }\n`;\n\nexport const GET_PAYMENT_METHODS = `\n query GetPaymentMethods($billingAccountId: ID!) {\n getPaymentMethods(billingAccountId: $billingAccountId) {\n id type last4 expiryYear brand isDefault isVerified\n }\n }\n`;\n\nexport const ADD_PAYMENT_METHOD = `\n mutation AddPaymentMethod($input: CreatePaymentMethodInput!) {\n addPaymentMethod(input: $input) {\n id type isDefault isVerified\n }\n }\n`;\n\nexport const DELETE_PAYMENT_METHOD = `\n mutation DeletePaymentMethod($billingAccountId: ID!, $id: ID!) {\n deletePaymentMethod(billingAccountId: $billingAccountId, id: $id)\n }\n`;\n\nexport const GRANT_CREDITS = `\n mutation GrantCredits($input: GrantCreditsInput!) {\n grantCredits(input: $input) {\n id amount status type\n }\n }\n`;\n\nexport const REQUEST_CREDIT_WITHDRAWAL = `\n mutation RequestCreditWithdrawal($input: RequestCreditWithdrawalInput!) {\n requestCreditWithdrawal(input: $input) {\n id status requestedAmount currency createdAt\n }\n }\n`;\n\nexport const GET_PENDING_REFUNDS = `\n query GetPendingRefunds($page: Int, $pageSize: Int) {\n getPendingRefunds(page: $page, pageSize: $pageSize) {\n records { id amount status source createdAt }\n totalCount\n }\n }\n`;\n\n// Live alpha requires BOTH `billingAccountId` and `subscriptionId` for\n// `getAllQuotasOfSub`; passing only `subscriptionId` returned\n// \"Field getAllQuotasOfSub argument billingAccountId of type ID! is\n// required\". The MCP tool already takes `billingAccountId` as a required\n// arg — we just need to forward it.\nexport const GET_QUOTAS_OF_SUB = `\n query GetQuotas($billingAccountId: ID!, $subscriptionId: ID!) {\n getAllQuotasOfSub(billingAccountId: $billingAccountId, subscriptionId: $subscriptionId) {\n id name limits currentUsageSum reusable\n }\n }\n`;\n","/**\n * Billing module tools — subscriptions, plans, addons, invoices,\n * payment-methods, credits, refunds, quotas.\n *\n * Backend: ~/products/global/billing/global-billing-svc/.\n * Ported from cli-sdk/src/modules/billing/. The CLI's stdin/options become\n * MCP tool arguments. Browser-redirect commands (Stripe checkout) are not\n * present in the source; the closest analogue (`invoices download`) returns a\n * URL — exposed here as `billing_invoices_get_pdf_url`.\n */\n\nimport { z } from 'zod';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { jsonResult, errorResult, mcpToolName, type McpContext } from '../../core/index.js';\nimport {\n GET_DEFAULT_BILLING_ACCOUNT,\n GET_ACTIVE_SUBSCRIPTIONS,\n GET_SUBSCRIPTION,\n UPDATE_SUBSCRIPTION_SEATS,\n CANCEL_SUBSCRIPTION,\n GET_ALL_PLANS,\n GET_PLAN,\n GET_ALL_ADDONS,\n GET_PAGINATED_INVOICES,\n GET_INVOICE,\n GET_PAYMENT_METHODS,\n ADD_PAYMENT_METHOD,\n DELETE_PAYMENT_METHOD,\n GRANT_CREDITS,\n REQUEST_CREDIT_WITHDRAWAL,\n GET_PENDING_REFUNDS,\n GET_QUOTAS_OF_SUB,\n} from './operations.js';\n\ninterface SubRow {\n id: string;\n status?: string;\n seatCount?: number;\n nextBillingDate?: string;\n plan?: { name: string; price?: number; currency?: string };\n}\n\ninterface PlanRow {\n id: string;\n name: string;\n price?: number;\n currency?: string;\n duration?: string;\n pricingModel?: string;\n isActive?: boolean;\n}\n\ninterface InvoiceRow {\n id: string;\n invoiceNumber?: string;\n status?: string;\n total?: number;\n currency?: string;\n paidAt?: string;\n pdfUrl?: string;\n}\n\ninterface PaymentMethodRow {\n id: string;\n type: string;\n last4?: string;\n brand?: string;\n isDefault?: boolean;\n isVerified?: boolean;\n}\n\ninterface BillingAccountRow {\n id: string;\n creditAmount?: number;\n currency?: string;\n}\n\nasync function resolveBillingAccountId(\n ctx: McpContext,\n override: string | undefined,\n): Promise<string> {\n if (override !== undefined && override !== '') return override;\n const data = await ctx.gql.global.request<{\n getDefaultBillingAccount: BillingAccountRow | null;\n }>(GET_DEFAULT_BILLING_ACCOUNT);\n if (!data.getDefaultBillingAccount?.id) {\n throw new Error('No default billing account on file. Pass account explicitly.');\n }\n return data.getDefaultBillingAccount.id;\n}\n\nexport function registerBillingTools(\n server: McpServer,\n ctx: McpContext,\n track: (n: string) => string,\n): void {\n // ── Subscriptions ──────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_list')),\n {\n title: 'List Subscriptions',\n description: 'List active subscriptions on a billing account (defaults to current).',\n inputSchema: {\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ getActiveSubscriptions: SubRow[] }>(\n GET_ACTIVE_SUBSCRIPTIONS,\n { billingAccountId },\n );\n return jsonResult(data.getActiveSubscriptions);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_list failed', { error: String(error) });\n return errorResult(\n `Failed to list subscriptions: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_get')),\n {\n title: 'Get Subscription',\n description:\n 'Get a subscription by ID. Live alpha requires BOTH `billingAccountId` and `id`; the missing `billingAccountId` was rejected with \"argument billingAccountId of type ID! is required\". The MCP tool forwards the default billing account id when the caller omits one.',\n inputSchema: {\n id: z.string().describe('Subscription ID'),\n billingAccountId: z\n .string()\n .optional()\n .describe(\n \"Billing account ID (defaults to the caller's default billing account when omitted)\",\n ),\n },\n },\n async ({ id, billingAccountId }) => {\n try {\n const accountId =\n billingAccountId ?? (await resolveBillingAccountId(ctx, billingAccountId));\n if (!accountId) {\n return errorResult(\n 'No billing account id; pass `billingAccountId` or ensure `getDefaultBillingAccount` is callable for the caller.',\n );\n }\n const data = await ctx.gql.global.request<{ getSubscription: SubRow | null }>(\n GET_SUBSCRIPTION,\n { billingAccountId: accountId, id },\n );\n if (!data.getSubscription) return errorResult(`Subscription ${id} not found`);\n return jsonResult(data.getSubscription);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_get failed', { error: String(error) });\n return errorResult(\n `Failed to get subscription: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_upgrade')),\n {\n title: 'Update Subscription Seats',\n description: 'Change the seat count on a subscription.',\n inputSchema: {\n id: z.string().describe('Subscription ID'),\n seats: z.number().describe('Target seat count'),\n },\n },\n async ({ id, seats }) => {\n try {\n const input: Record<string, unknown> = { subscriptionId: id, seatCount: seats };\n const data = await ctx.gql.global.request<{ updateSubscriptionSeats: SubRow }>(\n UPDATE_SUBSCRIPTION_SEATS,\n { input },\n );\n return jsonResult(data.updateSubscriptionSeats);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_upgrade failed', { error: String(error) });\n return errorResult(\n `Failed to update seats: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_subscriptions_cancel')),\n {\n title: 'Cancel Subscription',\n description: 'Cancel a subscription with an optional reason.',\n inputSchema: {\n id: z.string().describe('Subscription ID'),\n reason: z.string().optional().describe('Cancellation reason'),\n },\n },\n async ({ id, reason }) => {\n try {\n const input: Record<string, unknown> = { subscriptionId: id };\n if (reason !== undefined) input.reason = reason;\n const data = await ctx.gql.global.request<{ cancelSubscription: SubRow }>(\n CANCEL_SUBSCRIPTION,\n { input },\n );\n return jsonResult(data.cancelSubscription);\n } catch (error) {\n ctx.logger.error('billing_subscriptions_cancel failed', { error: String(error) });\n return errorResult(\n `Failed to cancel subscription: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Plans ──────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_plans_list')),\n {\n title: 'List Plans',\n description: 'List available plans, optionally filtered by product.',\n inputSchema: {\n product: z.string().optional().describe('Product ID filter'),\n },\n },\n async ({ product }) => {\n try {\n const filter: Record<string, unknown> = {};\n if (product !== undefined) filter.productId = product;\n const data = await ctx.gql.global.request<{ getAllPlans: PlanRow[] }>(GET_ALL_PLANS, {\n filter: Object.keys(filter).length ? filter : undefined,\n });\n return jsonResult(data.getAllPlans);\n } catch (error) {\n ctx.logger.error('billing_plans_list failed', { error: String(error) });\n return errorResult(\n `Failed to list plans: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_plans_get')),\n {\n title: 'Get Plan',\n description: 'Get a plan by ID.',\n inputSchema: { id: z.string().describe('Plan ID') },\n },\n async ({ id }) => {\n try {\n const data = await ctx.gql.global.request<{ getPlan: PlanRow | null }>(GET_PLAN, { id });\n if (!data.getPlan) return errorResult(`Plan ${id} not found`);\n return jsonResult(data.getPlan);\n } catch (error) {\n ctx.logger.error('billing_plans_get failed', { error: String(error) });\n return errorResult(\n `Failed to get plan: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Addons ─────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_addons_list')),\n {\n title: 'List Addons',\n description: 'List addons, optionally filtered by product.',\n inputSchema: {\n product: z.string().optional().describe('Product ID filter'),\n limit: z.number().optional().describe('Page size (default 50)'),\n },\n },\n async ({ product, limit }) => {\n try {\n const filter: Record<string, unknown> = {};\n if (product !== undefined) filter.productId = product;\n const data = await ctx.gql.global.request<{ getAllAddOns: PlanRow[] }>(GET_ALL_ADDONS, {\n filter: Object.keys(filter).length ? filter : undefined,\n limit,\n });\n return jsonResult(data.getAllAddOns);\n } catch (error) {\n ctx.logger.error('billing_addons_list failed', { error: String(error) });\n return errorResult(\n `Failed to list addons: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Invoices ───────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_invoices_list')),\n {\n title: 'List Invoices',\n description: 'Paginated list of invoices on a billing account.',\n inputSchema: {\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n page: z.number().optional().describe('Page number (default 1)'),\n pageSize: z.number().optional().describe('Page size (default 20)'),\n },\n },\n async ({ account, page, pageSize }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{\n getPaginatedInvoices: { invoices: InvoiceRow[]; totalCount: number };\n }>(GET_PAGINATED_INVOICES, { billingAccountId, page, pageSize });\n return jsonResult(data.getPaginatedInvoices);\n } catch (error) {\n ctx.logger.error('billing_invoices_list failed', { error: String(error) });\n return errorResult(\n `Failed to list invoices: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_invoices_get')),\n {\n title: 'Get Invoice',\n description: 'Get an invoice by ID (on the given or default billing account).',\n inputSchema: {\n id: z.string().describe('Invoice ID'),\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ id, account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ getInvoice: InvoiceRow | null }>(GET_INVOICE, {\n billingAccountId,\n id,\n });\n if (!data.getInvoice) return errorResult(`Invoice ${id} not found`);\n return jsonResult(data.getInvoice);\n } catch (error) {\n ctx.logger.error('billing_invoices_get failed', { error: String(error) });\n return errorResult(\n `Failed to get invoice: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // Browser-redirect analogue: returns the PDF URL for the LLM to share.\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_invoices_get_pdf_url')),\n {\n title: 'Get Invoice PDF URL',\n description:\n 'Return the invoice PDF download URL. The actual PDF must be opened in a browser by the user.',\n inputSchema: {\n id: z.string().describe('Invoice ID'),\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ id, account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ getInvoice: InvoiceRow | null }>(GET_INVOICE, {\n billingAccountId,\n id,\n });\n if (!data.getInvoice?.pdfUrl) return errorResult(`Invoice ${id} has no pdfUrl`);\n return jsonResult({ url: data.getInvoice.pdfUrl });\n } catch (error) {\n ctx.logger.error('billing_invoices_get_pdf_url failed', { error: String(error) });\n return errorResult(\n `Failed to fetch invoice URL: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Payment methods ────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_payment_methods_list')),\n {\n title: 'List Payment Methods',\n description: 'List payment methods on a billing account.',\n inputSchema: {\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ getPaymentMethods: PaymentMethodRow[] }>(\n GET_PAYMENT_METHODS,\n { billingAccountId },\n );\n return jsonResult(data.getPaymentMethods);\n } catch (error) {\n ctx.logger.error('billing_payment_methods_list failed', { error: String(error) });\n return errorResult(\n `Failed to list payment methods: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_payment_methods_add')),\n {\n title: 'Add Payment Method',\n description:\n 'Add a payment method (card metadata only — provider handles secrets). Use the provider checkout URL elsewhere for full card capture.',\n inputSchema: {\n type: z\n .enum([\n 'CREDIT_CARD',\n 'DEBIT_CARD',\n 'BANK_TRANSFER',\n 'NETBANKING',\n 'WALLET',\n 'PAYPAL',\n 'CRYPTO',\n ])\n .describe('Payment method type'),\n last4: z.string().describe('Last 4 digits / identifier'),\n brand: z.string().optional().describe('Brand (Visa, MasterCard, etc.)'),\n expiryMonth: z.number().optional().describe('Expiry month (1-12)'),\n expiryYear: z.number().optional().describe('Expiry year (4 digits)'),\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n isDefault: z.boolean().optional().describe('Make it the default'),\n },\n },\n async ({ type, last4, brand, expiryMonth, expiryYear, account, isDefault }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const input: Record<string, unknown> = {\n billingAccountId,\n type,\n last4,\n isDefault: isDefault === true,\n };\n if (brand !== undefined) input.brand = brand;\n if (expiryMonth !== undefined) input.expiryMonth = expiryMonth;\n if (expiryYear !== undefined) input.expiryYear = expiryYear;\n\n const data = await ctx.gql.global.request<{ addPaymentMethod: PaymentMethodRow }>(\n ADD_PAYMENT_METHOD,\n { input },\n );\n return jsonResult(data.addPaymentMethod);\n } catch (error) {\n ctx.logger.error('billing_payment_methods_add failed', { error: String(error) });\n return errorResult(\n `Failed to add payment method: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_payment_methods_remove')),\n {\n title: 'Remove Payment Method',\n description: 'Delete a payment method by ID (on the given or default billing account).',\n inputSchema: {\n id: z.string().describe('Payment method ID'),\n account: z.string().optional().describe('Billing account ID (defaults to current)'),\n },\n },\n async ({ id, account }) => {\n try {\n const billingAccountId = await resolveBillingAccountId(ctx, account);\n const data = await ctx.gql.global.request<{ deletePaymentMethod: boolean }>(\n DELETE_PAYMENT_METHOD,\n { billingAccountId, id },\n );\n if (!data.deletePaymentMethod) {\n return errorResult(`Payment method ${id} was not removed`);\n }\n return jsonResult({ status: 'success', message: 'Payment method removed', id });\n } catch (error) {\n ctx.logger.error('billing_payment_methods_remove failed', { error: String(error) });\n return errorResult(\n `Failed to remove payment method: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Credits ────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_credits_balance')),\n {\n title: 'Credit Balance',\n description: 'Show current credit balance on the default billing account.',\n inputSchema: {},\n },\n async () => {\n try {\n const data = await ctx.gql.global.request<{\n getDefaultBillingAccount: BillingAccountRow | null;\n }>(GET_DEFAULT_BILLING_ACCOUNT);\n return jsonResult(data.getDefaultBillingAccount);\n } catch (error) {\n ctx.logger.error('billing_credits_balance failed', { error: String(error) });\n return errorResult(\n `Failed to read balance: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_credits_grant')),\n {\n title: 'Grant Credits',\n description: 'Grant credits to a billing account (admin only).',\n inputSchema: {\n account: z.string().describe('Billing account ID'),\n amount: z.number().describe('Amount to grant'),\n reason: z.string().optional().describe('Reason for grant'),\n },\n },\n async ({ account, amount, reason }) => {\n try {\n const input: Record<string, unknown> = {\n billingAccountId: account,\n amount,\n reason: reason ?? 'mcp-grant',\n };\n await ctx.gql.global.request(GRANT_CREDITS, { input });\n return jsonResult({ status: 'success', message: 'Credits granted', amount, account });\n } catch (error) {\n ctx.logger.error('billing_credits_grant failed', { error: String(error) });\n return errorResult(\n `Failed to grant credits: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_credits_withdraw')),\n {\n title: 'Withdraw Credits',\n description: 'Request a credit withdrawal to a payout account.',\n inputSchema: {\n account: z.string().describe('Billing account ID'),\n amount: z.number().describe('Amount to withdraw'),\n payout: z.string().describe('Payout account ID'),\n },\n },\n async ({ account, amount, payout }) => {\n try {\n const input: Record<string, unknown> = {\n billingAccountId: account,\n creditAmount: amount,\n payoutAccountId: payout,\n };\n await ctx.gql.global.request(REQUEST_CREDIT_WITHDRAWAL, { input });\n return jsonResult({ status: 'success', message: 'Withdrawal requested', amount, account });\n } catch (error) {\n ctx.logger.error('billing_credits_withdraw failed', { error: String(error) });\n return errorResult(\n `Failed to request withdrawal: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Refunds ────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_refunds_list')),\n {\n title: 'List Pending Refunds',\n description: 'List pending refund records (paginated).',\n inputSchema: {\n page: z.number().optional().describe('Page number (default 0)'),\n pageSize: z.number().optional().describe('Page size (default 20)'),\n },\n },\n async ({ page, pageSize }) => {\n try {\n const data = await ctx.gql.global.request<{\n getPendingRefunds: { records: Array<Record<string, unknown>>; totalCount: number };\n }>(GET_PENDING_REFUNDS, { page, pageSize });\n return jsonResult(data.getPendingRefunds);\n } catch (error) {\n ctx.logger.error('billing_refunds_list failed', { error: String(error) });\n return errorResult(\n `Failed to list refunds: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n\n // ── Quota ──────────────────────────────────────────────────────────────\n server.registerTool(\n track(mcpToolName(ctx.productName, 'billing_quota_list')),\n {\n title: 'List Subscription Quotas',\n description:\n 'Get all quotas for a subscription. Live alpha requires BOTH `billingAccountId` and `subscriptionId`; the missing `billingAccountId` was rejected with \"argument billingAccountId of type ID! is required\". The MCP tool falls back to the caller\\'s default billing account when the caller omits one.',\n inputSchema: {\n subscriptionId: z.string().describe('Subscription ID'),\n billingAccountId: z\n .string()\n .optional()\n .describe(\n \"Billing account ID (defaults to the caller's default billing account when omitted)\",\n ),\n },\n },\n async ({ subscriptionId, billingAccountId }) => {\n try {\n const accountId = await resolveBillingAccountId(ctx, billingAccountId);\n const data = await ctx.gql.global.request<{\n getAllQuotasOfSub: Array<Record<string, unknown>>;\n }>(GET_QUOTAS_OF_SUB, { billingAccountId: accountId, subscriptionId });\n return jsonResult(data.getAllQuotasOfSub);\n } catch (error) {\n ctx.logger.error('billing_quota_list failed', { error: String(error) });\n return errorResult(\n `Failed to list quotas: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n );\n}\n","/**\n * Billing module — subscriptions, plans, addons, invoices, payment-methods,\n * credits, refunds, quotas. Backend: ~/products/global/billing/global-billing-svc/.\n * Ported from cli-sdk/src/modules/billing/.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { McpContext, McpModule, ModuleRegistration } from '../../core/index.js';\nimport { registerBillingTools } from './tools.js';\n\nconst billingModule: McpModule = {\n id: 'billing',\n version: '0.0.1',\n displayName: 'Billing',\n dependsOn: ['auth'],\n capabilities: { tools: {} },\n\n register(server: McpServer, ctx: McpContext): ModuleRegistration {\n const tools: string[] = [];\n const track = (n: string): string => {\n tools.push(n);\n return n;\n };\n\n registerBillingTools(server, ctx, track);\n\n return { tools, resources: [], prompts: [] };\n },\n};\n\nexport default billingModule;\n"]}
|
|
@@ -68,10 +68,11 @@ var GET_PAGINATED_INVOICES = `
|
|
|
68
68
|
}
|
|
69
69
|
`;
|
|
70
70
|
var GET_INVOICE = `
|
|
71
|
-
query GetInvoice($id: ID!) {
|
|
72
|
-
getInvoice(id: $id) {
|
|
73
|
-
id invoiceNumber status subtotal tax total
|
|
74
|
-
|
|
71
|
+
query GetInvoice($billingAccountId: ID!, $id: ID!) {
|
|
72
|
+
getInvoice(billingAccountId: $billingAccountId, id: $id) {
|
|
73
|
+
id invoiceNumber status currency subtotal tax total amountPaid dueDate paidAt
|
|
74
|
+
pdfUrl invoiceUrl
|
|
75
|
+
items { description quantity unitPrice amount }
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
78
|
`;
|
|
@@ -83,15 +84,15 @@ var GET_PAYMENT_METHODS = `
|
|
|
83
84
|
}
|
|
84
85
|
`;
|
|
85
86
|
var ADD_PAYMENT_METHOD = `
|
|
86
|
-
mutation AddPaymentMethod($input:
|
|
87
|
+
mutation AddPaymentMethod($input: CreatePaymentMethodInput!) {
|
|
87
88
|
addPaymentMethod(input: $input) {
|
|
88
89
|
id type isDefault isVerified
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
`;
|
|
92
93
|
var DELETE_PAYMENT_METHOD = `
|
|
93
|
-
mutation DeletePaymentMethod($id: ID!) {
|
|
94
|
-
deletePaymentMethod(id: $id)
|
|
94
|
+
mutation DeletePaymentMethod($billingAccountId: ID!, $id: ID!) {
|
|
95
|
+
deletePaymentMethod(billingAccountId: $billingAccountId, id: $id)
|
|
95
96
|
}
|
|
96
97
|
`;
|
|
97
98
|
var GRANT_CREDITS = `
|
|
@@ -104,7 +105,7 @@ var GRANT_CREDITS = `
|
|
|
104
105
|
var REQUEST_CREDIT_WITHDRAWAL = `
|
|
105
106
|
mutation RequestCreditWithdrawal($input: RequestCreditWithdrawalInput!) {
|
|
106
107
|
requestCreditWithdrawal(input: $input) {
|
|
107
|
-
id status
|
|
108
|
+
id status requestedAmount currency createdAt
|
|
108
109
|
}
|
|
109
110
|
}
|
|
110
111
|
`;
|
|
@@ -346,12 +347,17 @@ function registerBillingTools(server, ctx, track) {
|
|
|
346
347
|
track(mcpToolName(ctx.productName, "billing_invoices_get")),
|
|
347
348
|
{
|
|
348
349
|
title: "Get Invoice",
|
|
349
|
-
description: "Get an invoice by ID.",
|
|
350
|
-
inputSchema: {
|
|
350
|
+
description: "Get an invoice by ID (on the given or default billing account).",
|
|
351
|
+
inputSchema: {
|
|
352
|
+
id: z.string().describe("Invoice ID"),
|
|
353
|
+
account: z.string().optional().describe("Billing account ID (defaults to current)")
|
|
354
|
+
}
|
|
351
355
|
},
|
|
352
|
-
async ({ id }) => {
|
|
356
|
+
async ({ id, account }) => {
|
|
353
357
|
try {
|
|
358
|
+
const billingAccountId = await resolveBillingAccountId(ctx, account);
|
|
354
359
|
const data = await ctx.gql.global.request(GET_INVOICE, {
|
|
360
|
+
billingAccountId,
|
|
355
361
|
id
|
|
356
362
|
});
|
|
357
363
|
if (!data.getInvoice) return errorResult(`Invoice ${id} not found`);
|
|
@@ -369,11 +375,16 @@ function registerBillingTools(server, ctx, track) {
|
|
|
369
375
|
{
|
|
370
376
|
title: "Get Invoice PDF URL",
|
|
371
377
|
description: "Return the invoice PDF download URL. The actual PDF must be opened in a browser by the user.",
|
|
372
|
-
inputSchema: {
|
|
378
|
+
inputSchema: {
|
|
379
|
+
id: z.string().describe("Invoice ID"),
|
|
380
|
+
account: z.string().optional().describe("Billing account ID (defaults to current)")
|
|
381
|
+
}
|
|
373
382
|
},
|
|
374
|
-
async ({ id }) => {
|
|
383
|
+
async ({ id, account }) => {
|
|
375
384
|
try {
|
|
385
|
+
const billingAccountId = await resolveBillingAccountId(ctx, account);
|
|
376
386
|
const data = await ctx.gql.global.request(GET_INVOICE, {
|
|
387
|
+
billingAccountId,
|
|
377
388
|
id
|
|
378
389
|
});
|
|
379
390
|
if (!data.getInvoice?.pdfUrl) return errorResult(`Invoice ${id} has no pdfUrl`);
|
|
@@ -417,7 +428,15 @@ function registerBillingTools(server, ctx, track) {
|
|
|
417
428
|
title: "Add Payment Method",
|
|
418
429
|
description: "Add a payment method (card metadata only \u2014 provider handles secrets). Use the provider checkout URL elsewhere for full card capture.",
|
|
419
430
|
inputSchema: {
|
|
420
|
-
type: z.enum([
|
|
431
|
+
type: z.enum([
|
|
432
|
+
"CREDIT_CARD",
|
|
433
|
+
"DEBIT_CARD",
|
|
434
|
+
"BANK_TRANSFER",
|
|
435
|
+
"NETBANKING",
|
|
436
|
+
"WALLET",
|
|
437
|
+
"PAYPAL",
|
|
438
|
+
"CRYPTO"
|
|
439
|
+
]).describe("Payment method type"),
|
|
421
440
|
last4: z.string().describe("Last 4 digits / identifier"),
|
|
422
441
|
brand: z.string().optional().describe("Brand (Visa, MasterCard, etc.)"),
|
|
423
442
|
expiryMonth: z.number().optional().describe("Expiry month (1-12)"),
|
|
@@ -455,15 +474,22 @@ function registerBillingTools(server, ctx, track) {
|
|
|
455
474
|
track(mcpToolName(ctx.productName, "billing_payment_methods_remove")),
|
|
456
475
|
{
|
|
457
476
|
title: "Remove Payment Method",
|
|
458
|
-
description: "Delete a payment method by ID.",
|
|
459
|
-
inputSchema: {
|
|
477
|
+
description: "Delete a payment method by ID (on the given or default billing account).",
|
|
478
|
+
inputSchema: {
|
|
479
|
+
id: z.string().describe("Payment method ID"),
|
|
480
|
+
account: z.string().optional().describe("Billing account ID (defaults to current)")
|
|
481
|
+
}
|
|
460
482
|
},
|
|
461
|
-
async ({ id }) => {
|
|
483
|
+
async ({ id, account }) => {
|
|
462
484
|
try {
|
|
463
|
-
await ctx
|
|
485
|
+
const billingAccountId = await resolveBillingAccountId(ctx, account);
|
|
486
|
+
const data = await ctx.gql.global.request(
|
|
464
487
|
DELETE_PAYMENT_METHOD,
|
|
465
|
-
{ id }
|
|
488
|
+
{ billingAccountId, id }
|
|
466
489
|
);
|
|
490
|
+
if (!data.deletePaymentMethod) {
|
|
491
|
+
return errorResult(`Payment method ${id} was not removed`);
|
|
492
|
+
}
|
|
467
493
|
return jsonResult({ status: "success", message: "Payment method removed", id });
|
|
468
494
|
} catch (error) {
|
|
469
495
|
ctx.logger.error("billing_payment_methods_remove failed", { error: String(error) });
|