Production-ready Python and TypeScript examples for the AI2Fin Finance MCP server: expense tracking, tax-deduction analysis, bill automation, spending insights, and connecting ChatGPT, Claude or custom AI agents to your financial data.
Production-ready code examples for integrating with the AI2Fin Finance MCP server. Learn how to connect ChatGPT, Claude, or your own AI agents to your financial data for expense tracking, tax-deduction analysis, bill management, and financial reporting — in Python and TypeScript.
Quick Navigation
Tax & Deductions
Tax deduction analysis examples
Expense Tracking
Spending analysis and tracking
Bill Management
Recurring bill automation
Receipt Processing
Automated receipt handling
ChatGPT Integration
Connect ChatGPT to finances
Custom AI Agents
Build financial AI assistants
Example 1: Tax Deduction Analysis
Use Case: Get comprehensive tax deduction report for financial yearUser Intent: “I need to know what expenses are tax deductible for my business tax return”
Python - Using MCP Protocol
import requests# Your AI2Fin JWT token or API keyTOKEN = "eyJhbGciOiJIUzI1NiIs..." # JWT token# ORAPI_KEY = "mcp_a1b2c3d4e5f6..." # API key for /mcp/inspectorBASE_URL = "https://api.ai2fin.com"def get_tax_summary(start_date: str, end_date: str, use_api_key: bool = False): """Get tax deductible expenses summary using MCP""" endpoint = "/mcp/inspector" if use_api_key else "/mcp" auth_header = "X-API-Key" if use_api_key else "Authorization" auth_value = API_KEY if use_api_key else f"Bearer {TOKEN}" response = requests.post( f"{BASE_URL}{endpoint}", headers={ auth_header: auth_value, "Content-Type": "application/json" }, json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "get_tax_summary", "arguments": { "startDate": start_date, "endDate": end_date } } } ) result = response.json() if "result" in result and "content" in result["result"]: return result["result"]["content"][0]["json"]["data"] return result# Usage - Get FY tax deductions (Australian financial year: Jul-Jun)tax_summary = get_tax_summary("2024-07-01", "2025-06-30")# Tip: pass {"period": "last_fy"} instead of dates and the server works out the FY boundsprint(f"Total tax deductible: ${tax_summary['totalAmount']:,.2f}")print(f"Categories: {len(tax_summary['byCategory'])}")# Output: Total tax deductible: $12,450.67# Categories: 8
Use Case: Automate bill tracking and payment remindersUser Intent: “I need to track my recurring bills and get reminders when they’re due”
Python - Bill Payment Automation
def check_overdue_bills(): """Check for overdue bills and send reminders""" response = requests.post( f"{BASE_URL}/mcp", headers={ "Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json" }, json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "query_bills", "arguments": {"view": "overdue"} } } ) result = response.json() overdue_bills = result["result"]["content"][0]["json"]["data"]["occurrences"] if overdue_bills: total = sum(bill["amount"] for bill in overdue_bills) print(f"⚠️ You have {len(overdue_bills)} overdue bills totaling ${total:,.2f}") for bill in overdue_bills: print(f" - {bill['billPattern']['merchantName']}: ${bill['amount']:.2f} (Due: {bill['dueDate']})") else: print("✅ No overdue bills!") return overdue_bills# Usageoverdue = check_overdue_bills()
TypeScript - Bill Payment Workflow
async function markBillAsPaid(occurrenceId: string, transactionId?: string) { // First call - get confirmation token. (Clients other than Meta Muse get this // two-step flow; Muse asks the user itself and calls once.) const preview = await fetch('https://api.ai2fin.com/mcp', { method: 'POST', headers: { 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'manage_bill_payment', arguments: { action: 'pay', occurrenceId, transactionId // optional: link an existing transaction instead of creating one } } }) }); const previewResult = await preview.json(); if (previewResult.result.content[0].json.needsConfirmation) { const confirmToken = previewResult.result.content[0].json.confirmToken; // Second call - confirm and execute const confirm = await fetch('https://api.ai2fin.com/mcp', { method: 'POST', headers: { 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'manage_bill_payment', arguments: { action: 'pay', occurrenceId, transactionId, confirmToken } } }) }); return await confirm.json(); } return previewResult;}
Example 4: Receipt Processing Automation
Use Case: Automatically process receipts from email or uploadsUser Intent: “I need to automatically extract data from receipts and create expenses”Maintain conversation history across multiple requests.
class AI2FinChat { private token: string; private conversationId: string | null = null; constructor(token: string) { this.token = token; } async chat(message: string): Promise<string> { const response = await fetch('https://app.ai2fin.com/api/chat/message', { method: 'POST', headers: { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ message, conversationId: this.conversationId }) }); const data = await response.json(); // Save conversation ID for history this.conversationId = data.data.conversationId; return data.data.message.content; } async getHistory(): Promise<Message[]> { if (!this.conversationId) return []; const response = await fetch( `https://app.ai2fin.com/api/chat/conversations/${this.conversationId}`, { headers: { 'Authorization': `Bearer ${this.token}` } } ); const data = await response.json(); return data.data; }}// Usageconst chat = new AI2FinChat('YOUR_TOKEN');// First messageawait chat.chat("Show my transactions");// AI: "You have 47 transactions..."// Second message (AI remembers context!)await chat.chat("Which ones are tax deductible?");// AI: "Of those 47, 23 are tax deductible..."// Get full historyconst history = await chat.getHistory();console.log(history); // All messages retained
Python - Smart Receipt Processor
def process_receipt(receipt_url: str): """One-call receipt processing workflow""" response = requests.post( f"{BASE_URL}/mcp", headers={ "Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json" }, json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "process_receipt", "arguments": { "mode": "smart", "assetUrl": receipt_url, "mimeType": "image/jpeg", "size": 245123, "autoLinkToBill": True } } } ) result = response.json() return result["result"]["content"][0]["json"]["data"]# Usagereceipt_data = process_receipt("https://example.com/receipt.jpg")print(f"✅ Created transaction: ${receipt_data['transaction']['amount']:.2f}")print(f" Merchant: {receipt_data['merchant']}")# GST is detected and filled in for you automatically.# Files over the 256 KB request limit: call get_receipt_upload_url first, PUT the# bytes to its uploadUrl, then pass the assetUrl it returns to process_receipt.
Example 5: ChatGPT Integration
Use Case: Connect ChatGPT to your financial data via OAuthUser Intent: “I want ChatGPT to answer questions about my finances”Build a command-line interface for AI2Fin.
$ python ai2fin_cli.pyEnter your AI2Fin token: eyJhbGciOiJIUzI1NiIs...AI2Fin Assistant (type 'exit' to quit)You: Show my billsAI: You have 12 recurring bills totaling $445.50 monthly...You: What's due this week?AI: You have 3 bills due this week:- Netflix ($15.99) - Due Nov 5- Spotify ($11.99) - Due Nov 8- Adobe CC ($54.99) - Due Nov 10You: exit
OAuth Configuration
{ "name": "AI2Fin Finance Assistant", "description": "Connect your AI assistant to your AI2Fin financial data", "authentication": { "type": "oauth", "authorization_url": "https://api.ai2fin.com/api/auth/oauth/authorize", "token_url": "https://api.ai2fin.com/api/auth/oauth/token", "scopes": ["read:transactions", "read:bills", "write:transactions", "write:bills"] }, "mcp_endpoint": "https://api.ai2fin.com/mcp"}
User Experience:
User connects AI assistant to AI2Fin via OAuth
AI assistant can now answer: “What are my tax deductible expenses?”
AI assistant calls get_tax_summary via MCP
Returns formatted financial insights
Example 6: Custom Financial AI Agent
Use Case: Build a custom financial AI assistantUser Intent: “I want a custom AI agent that understands my business finances”
const { App } = require('@slack/bolt');const { AI2FinMCP } = require('ai2fin-mcp-sdk');const app = new App({ token: process.env.SLACK_BOT_TOKEN, signingSecret: process.env.SLACK_SIGNING_SECRET});// Map Slack users to AI2Fin tokens (securely!)const userTokens = new Map();app.message(async ({ message, say }) => { const userId = message.user; const ai2finToken = userTokens.get(userId); if (!ai2finToken) { await say("Please authenticate with AI2Fin first: /ai2fin-login"); return; } // Send to AI2Fin MCP const mcp = new AI2FinMCP(ai2finToken); const response = await mcp.chat(message.text); await say(response.data.message.content);});app.start(3000);
# 1. Get overdue billsoverdue = call_mcp_tool("query_bills", {"view": "overdue"})# 2. Get upcoming billsupcoming = call_mcp_tool("query_bills", {"view": "upcoming", "days": 7})# 3. Mark bills as paid (with confirmation — clients other than Meta Muse)for occurrence in overdue["occurrences"]: # First call - get confirmation preview = call_mcp_tool("manage_bill_payment", { "action": "pay", "occurrenceId": occurrence["id"] }) if preview["needsConfirmation"]: # Second call - confirm result = call_mcp_tool("manage_bill_payment", { "action": "pay", "occurrenceId": occurrence["id"], "confirmToken": preview["confirmToken"] })
Frequently Asked Questions
How do I integrate MCP with my financial data?
Connect your AI assistant to the AI2Fin Finance MCP server using either an API key (best for automation) or an OAuth access token (best for user-specific integrations). Once connected, your assistant can call finance tools like get_tax_summary, analyze_spending and query_bills to answer questions in natural language. The Python and TypeScript examples above show the exact request format.
Can I connect ChatGPT or Claude to my AI2Fin data?
Yes. The AI2Fin Finance MCP server works with any MCP-compatible assistant, including ChatGPT, Claude, and Cursor. See Example 5: ChatGPT Integration for the OAuth setup, and the Cursor integration guide for a step-by-step walkthrough.
Which programming languages are supported?
The MCP server speaks the standard JSON-RPC MCP protocol over HTTPS, so you can call it from any language that can make HTTP requests. The examples here use Python and TypeScript, but the same request format works in Go, Ruby, C#, and more.
What can the finance tools actually do?
You can analyse tax deductions, break spending down by category and merchant, compare time periods, track recurring bills, detect duplicate payments, and generate financial-year summaries. See the Transaction Tools, Bill Tools, and Subscription Tools references for the full list.
SDK Libraries
Official SDKs (Coming Soon)
# Pythonpip install ai2fin-mcp-sdk# JavaScript/TypeScriptnpm install @ai2fin/mcp-sdk# Gogo get github.com/ai2fin/mcp-sdk-go