Skip to main content
Glama

get_all_card_expenses

Retrieve paginated corporate card expense records from Brex with filtering options for status, date ranges, amounts, and merchant names to manage financial tracking and reporting.

Instructions

LIST: Paginated card expenses (no expense_type needed). Returns complete card expense objects. Example: {"page_size":5,"max_items":5,"window_days":7,"min_amount":100}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
end_dateNoFilter card expenses created on or before this date (ISO format)
expandNoFields to expand (e.g., merchant, receipts)
max_amountNoClient-side maximum purchased_amount.amount filter
max_itemsNoMaximum total number of items to retrieve across all pages
merchant_nameNoFilter card expenses by merchant name (partial match)
min_amountNoClient-side minimum purchased_amount.amount filter
page_sizeNoNumber of items per page (default: 50, max: 100)
payment_statusNoFilter card expenses by payment status
start_dateNoFilter card expenses created on or after this date (ISO format)
statusNoFilter card expenses by status
window_daysNoOptional batching window in days to split large date ranges

Implementation Reference

  • The primary handler function registered for 'get_all_card_expenses'. It validates input parameters, fetches paginated card expenses from Brex API, applies client-side filters (merchant, amount), and returns a JSON response with expenses and metadata.
    registerToolHandler("get_all_card_expenses", async (request: ToolCallRequest) => { try { // Validate parameters const params = validateParams(request.params.arguments); logDebug(`Getting all card expenses with params: ${JSON.stringify(params)}`); // Get Brex client const brexClient = getBrexClient(); try { // Fetch all card expenses with pagination const allCardExpenses = await fetchAllCardExpenses(brexClient, params); logDebug(`Successfully fetched ${allCardExpenses.length} total card expenses`); // Return raw results with pagination metadata const result = { card_expenses: allCardExpenses, meta: { total_count: allCardExpenses.length, requested_parameters: params } }; return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }; } catch (apiError) { logError(`Error calling Brex API: ${apiError instanceof Error ? apiError.message : String(apiError)}`); throw new Error(`Failed to get card expenses: ${apiError instanceof Error ? apiError.message : String(apiError)}`); } } catch (error) { logError(`Error in get_all_card_expenses tool: ${error instanceof Error ? error.message : String(error)}`); throw error; } });
  • Input schema definition for the get_all_card_expenses tool, registered in the list tools handler. Defines all parameters with types, descriptions, and enums matching the implementation.
    { name: "get_all_card_expenses", description: "LIST: Paginated card expenses (no expense_type needed). Returns complete card expense objects. Example: {\"page_size\":5,\"max_items\":5,\"window_days\":7,\"min_amount\":100}", inputSchema: { type: "object", properties: { page_size: { type: "number", description: "Number of items per page (default: 50, max: 100)" }, max_items: { type: "number", description: "Maximum total number of items to retrieve across all pages" }, status: { type: "array", items: { type: "string", enum: Object.values(ExpenseStatus) }, description: "Filter card expenses by status" }, payment_status: { type: "array", items: { type: "string", enum: Object.values(ExpensePaymentStatus) }, description: "Filter card expenses by payment status" }, start_date: { type: "string", description: "Filter card expenses created on or after this date (ISO format)" }, end_date: { type: "string", description: "Filter card expenses created on or before this date (ISO format)" }, merchant_name: { type: "string", description: "Filter card expenses by merchant name (partial match)" }, window_days: { type: "number", description: "Optional batching window in days to split large date ranges" }, min_amount: { type: "number", description: "Client-side minimum purchased_amount.amount filter" }, max_amount: { type: "number", description: "Client-side maximum purchased_amount.amount filter" }, expand: { type: "array", items: { type: "string" }, description: "Fields to expand (e.g., merchant, receipts)" } } } }
  • The registration function specific to get_all_card_expenses tool. It registers the handler using the shared registerToolHandler utility.
    export function registerGetAllCardExpenses(_server: Server): void { registerToolHandler("get_all_card_expenses", async (request: ToolCallRequest) => { try { // Validate parameters const params = validateParams(request.params.arguments); logDebug(`Getting all card expenses with params: ${JSON.stringify(params)}`); // Get Brex client const brexClient = getBrexClient(); try { // Fetch all card expenses with pagination const allCardExpenses = await fetchAllCardExpenses(brexClient, params); logDebug(`Successfully fetched ${allCardExpenses.length} total card expenses`); // Return raw results with pagination metadata const result = { card_expenses: allCardExpenses, meta: { total_count: allCardExpenses.length, requested_parameters: params } }; return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }; } catch (apiError) { logError(`Error calling Brex API: ${apiError instanceof Error ? apiError.message : String(apiError)}`); throw new Error(`Failed to get card expenses: ${apiError instanceof Error ? apiError.message : String(apiError)}`); } } catch (error) { logError(`Error in get_all_card_expenses tool: ${error instanceof Error ? error.message : String(error)}`); throw error; } }); }
  • Top-level registration call within registerTools function that invokes the tool-specific registration for get_all_card_expenses.
    registerGetAllCardExpenses(server);
  • Core helper function that implements pagination, date windowing, API fetching via BrexClient.getCardExpenses, and client-side filtering for the tool.
    async function fetchAllCardExpenses(client: BrexClient, params: GetAllCardExpensesParams): Promise<unknown[]> { const pageSize = params.page_size || 50; const maxItems = params.max_items || Infinity; let allExpenses: unknown[] = []; const start = params.start_date ? new Date(params.start_date) : undefined; const end = params.end_date ? new Date(params.end_date) : undefined; const windowDays = params.window_days && start && end ? params.window_days : undefined; const windows: Array<{ start?: string; end?: string }> = []; if (windowDays && start && end) { const cursorStart = new Date(start); while (cursorStart <= end && allExpenses.length < maxItems) { const cursorEnd = new Date(cursorStart); cursorEnd.setUTCDate(cursorEnd.getUTCDate() + windowDays); if (cursorEnd > end) cursorEnd.setTime(end.getTime()); windows.push({ start: cursorStart.toISOString(), end: cursorEnd.toISOString() }); cursorStart.setUTCDate(cursorStart.getUTCDate() + windowDays); } } else { windows.push({ start: params.start_date, end: params.end_date }); } for (const w of windows) { let cursor: string | undefined = undefined; let hasMore = true; while (hasMore && allExpenses.length < maxItems) { try { const limit = Math.min(pageSize, maxItems - allExpenses.length); const requestParams: ListExpensesParams = { limit, cursor, expense_type: [ExpenseType.CARD], expand: params.expand || [] // Use provided expand array or default to empty }; if (params.status) requestParams.status = params.status; if (params.payment_status) requestParams.payment_status = params.payment_status; if (w.start) requestParams.updated_at_start = w.start; if (w.end) requestParams.updated_at_end = w.end; logDebug(`Fetching card expenses page (window ${w.start || 'none'}..${w.end || 'none'}) cursor: ${cursor || 'initial'}`); const response = await client.getCardExpenses(requestParams); let validExpenses = response.items.filter(isExpense); if (params.merchant_name) { const merchantNameLower = params.merchant_name.toLowerCase(); validExpenses = validExpenses.filter(expense => (expense.merchant?.raw_descriptor || '').toLowerCase().includes(merchantNameLower)); } if (params.min_amount !== undefined) { validExpenses = validExpenses.filter(e => typeof e.purchased_amount?.amount === 'number' && e.purchased_amount.amount >= (params.min_amount as number)); } if (params.max_amount !== undefined) { validExpenses = validExpenses.filter(e => typeof e.purchased_amount?.amount === 'number' && e.purchased_amount.amount <= (params.max_amount as number)); } allExpenses = allExpenses.concat(validExpenses); logDebug(`Retrieved ${validExpenses.length} card expenses (total: ${allExpenses.length})`); cursor = response.nextCursor; hasMore = !!cursor; } catch (error) { logError(`Error fetching card expenses page: ${error instanceof Error ? error.message : String(error)}`); throw error; } } if (allExpenses.length >= maxItems) break; } return allExpenses; }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/crazyrabbitLTC/mcp-brex-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server