Skip to content

feat(mcp): add invoice tool #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@doitintl/doit-mcp-server",
"version": "0.1.27",
"version": "0.1.28",
"description": "DoiT official MCP Server",
"keywords": [
"doit",
Expand Down
51 changes: 50 additions & 1 deletion src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,20 @@ vi.mock("../tools/tickets.js", () => ({
handleListTicketsRequest: vi.fn(),
handleCreateTicketRequest: vi.fn(),
}));
vi.mock("../tools/invoices.ts", () => ({
listInvoicesTool: {
name: "list_invoices",
description:
"List all current and historical invoices for your organization from the DoiT API.",
},
getInvoiceTool: {
name: "get_invoice",
description:
"Retrieve the full details of an invoice specified by the invoice number from the DoiT API.",
},
handleListInvoicesRequest: vi.fn(),
handleGetInvoiceRequest: vi.fn(),
}));
vi.mock("../utils/util.js", async () => {
const actual = await vi.importActual("../utils/util.js");
return {
Expand Down Expand Up @@ -200,6 +214,16 @@ describe("ListToolsRequestSchema Handler", () => {
description:
"Create a new support ticket in DoiT using the support API.",
},
{
name: "list_invoices",
description:
"List all current and historical invoices for your organization from the DoiT API.",
},
{
name: "get_invoice",
description:
"Retrieve the full details of an invoice specified by the invoice number from the DoiT API.",
},
],
});
});
Expand Down Expand Up @@ -442,6 +466,30 @@ describe("CallToolRequestSchema Handler", () => {
);
});

it("should route to the correct tool handler for list_invoices", async () => {
const callToolHandler = setRequestHandlerMock.mock.calls.find(
(call) => call[0] === CallToolRequestSchema
)?.[1];
const args = { pageToken: "next-page-token" };
const request = mockRequest("list_invoices", args);

await callToolHandler(request);

expect(handleListInvoicesRequest).toHaveBeenCalledWith(args, "fake-token");
});

it("should route to the correct tool handler for get_invoice", async () => {
const callToolHandler = setRequestHandlerMock.mock.calls.find(
(call) => call[0] === CallToolRequestSchema
)?.[1];
const args = { id: "invoice-123" };
const request = mockRequest("get_invoice", args);

await callToolHandler(request);

expect(handleGetInvoiceRequest).toHaveBeenCalledWith(args, "fake-token");
});

it("should return Unknown tool error for unknown tool names", async () => {
const callToolHandler = setRequestHandlerMock.mock.calls.find(
(call) => call[0] === CallToolRequestSchema
Expand Down Expand Up @@ -541,4 +589,5 @@ describe("InitializeRequestSchema Handler", () => {
});

const indexModule = await import("../index.js");
const { createServer } = indexModule;
const { createServer, handleListInvoicesRequest, handleGetInvoiceRequest } =
indexModule;
14 changes: 14 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ import {
createTicketTool,
handleCreateTicketRequest,
} from "./tools/tickets.js";
import {
listInvoicesTool,
handleListInvoicesRequest,
getInvoiceTool,
handleGetInvoiceRequest,
} from "./tools/invoices.js";

dotenv.config();

Expand Down Expand Up @@ -87,6 +93,8 @@ function createServer() {
dimensionTool,
listTicketsTool,
createTicketTool,
listInvoicesTool,
getInvoiceTool,
],
};
});
Expand Down Expand Up @@ -172,6 +180,10 @@ function createServer() {
return await handleListTicketsRequest(args, token);
case "create_ticket":
return await handleCreateTicketRequest(args, token);
case "list_invoices":
return await handleListInvoicesRequest(args, token);
case "get_invoice":
return await handleGetInvoiceRequest(args, token);
default:
return createErrorResponse(`Unknown tool: ${name}`);
}
Expand Down Expand Up @@ -240,4 +252,6 @@ export {
createErrorResponse,
formatZodError,
handleGeneralError,
handleListInvoicesRequest,
handleGetInvoiceRequest,
};
168 changes: 168 additions & 0 deletions src/tools/invoices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { z } from "zod";
import {
createErrorResponse,
createSuccessResponse,
handleGeneralError,
makeDoitRequest,
formatDate,
} from "../utils/util.js";

// Invoice interface matching the API response
export interface Invoice {
id: string;
invoiceDate: number;
platform: string;
dueDate: number;
status: string;
totalAmount: number;
balanceAmount: number;
currency: string;
url: string;
}

export interface InvoicesResponse {
invoices: Invoice[];
pageToken?: string;
rowCount: number;
}

// Arguments schema for listing invoices
export const ListInvoicesArgumentsSchema = z.object({
pageToken: z
.string()
.optional()
.describe(
"Token for pagination. Use this to get the next page of results."
),
});

// Tool definition
export const listInvoicesTool = {
name: "list_invoices",
description:
"List all current and historical invoices for your organization from the DoiT API.",
inputSchema: {
type: "object",
properties: {
pageToken: {
type: "string",
description:
"Token for pagination. Use this to get the next page of results.",
},
},
},
outputSchema: z.object({
invoices: z.array(
z.object({
id: z.string(),
invoiceDate: z.number(),
platform: z.string(),
dueDate: z.number(),
status: z.string(),
totalAmount: z.number(),
balanceAmount: z.number(),
currency: z.string(),
url: z.string(),
})
),
pageToken: z.string().optional(),
rowCount: z.number(),
}),
};

// Handler for the tool
export async function handleListInvoicesRequest(args: any, token: string) {
try {
const params = new URLSearchParams();
if (args.pageToken) params.append("pageToken", args.pageToken);
const url = `https://api.doit.com/billing/v1/invoices${
params.toString() ? `?${params.toString()}` : ""
}`;
const data = await makeDoitRequest<InvoicesResponse>(url, token);
if (!data) {
return createErrorResponse("Failed to fetch invoices: No data returned");
}
// Format invoiceDate and dueDate for each invoice
const formattedData = {
...data,
invoices: data.invoices.map((inv) => ({
...inv,
invoiceDateFormatted: formatDate(inv.invoiceDate),
dueDateFormatted: formatDate(inv.dueDate),
})),
};
return createSuccessResponse(JSON.stringify(formattedData));
} catch (error) {
return handleGeneralError(error, "listing invoices");
}
}

// Arguments schema for getting a single invoice
export const GetInvoiceArgumentsSchema = z.object({
id: z.string().describe("The ID of the invoice to retrieve"),
});

// Tool definition for getting a single invoice
export const getInvoiceTool = {
name: "get_invoice",
description:
"Retrieve the full details of an invoice specified by the invoice number from the DoiT API.",
inputSchema: {
type: "object",
properties: {
id: {
type: "string",
description: "The ID of the invoice to retrieve.",
},
},
required: ["id"],
},
outputSchema: z.object({
id: z.string(),
invoiceDate: z.number(),
platform: z.string(),
dueDate: z.number(),
status: z.string(),
totalAmount: z.number(),
balanceAmount: z.number(),
currency: z.string(),
url: z.string(),
lineItems: z.array(
z.object({
currency: z.string(),
description: z.string(),
details: z.string(),
price: z.number(),
qty: z.number(),
type: z.string(),
})
),
}),
};

// Handler for the tool
export async function handleGetInvoiceRequest(args: any, token: string) {
try {
if (!args.id) {
return createErrorResponse("Invoice ID is required");
}
const url = `https://api.doit.com/billing/v1/invoices/${encodeURIComponent(
args.id
)}`;
const data: Invoice | null = await makeDoitRequest<Invoice>(url, token, {
appendParams: true,
});
if (!data) {
return createErrorResponse("Failed to fetch invoice: No data returned");
}
// Format invoiceDate and dueDate
const formattedData = {
...data,
invoiceDateFormatted: formatDate(data.invoiceDate),
dueDateFormatted: formatDate(data.dueDate),
};
return createSuccessResponse(JSON.stringify(formattedData));
} catch (error) {
return handleGeneralError(error, "retrieving invoice");
}
}
10 changes: 10 additions & 0 deletions src/utils/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,13 @@ export async function makeDoitRequest<T>(
return null;
}
}

/**
* Formats a timestamp (number) as a human-readable date string
* @param timestamp The timestamp in milliseconds
* @returns Formatted date string (e.g., '2024-04-27')
*/
export function formatDate(timestamp: number): string {
if (!timestamp) return "";
return new Date(timestamp).toISOString().split("T")[0];
}