Introduction
The rise of Large Language Models (LLMs) has transformed enterprise automation, but it has introduced a new operational challenge: token economics. As AI agents become more sophisticated, the cost of context windows, repeated retrievals, and redundant reasoning steps can spiral out of control. Okta, the identity leader, is addressing this through its integration with the Model Context Protocol (MCP). MCP standardizes how AI agents connect to data sources, allowing for smarter, more efficient context management. By leveraging Okta’s identity governance alongside MCP’s standardized data access, enterprises can reduce token consumption by up to 40-60% while enhancing security. In this article, we’ll build an enterprise-grade multi-agent system for the Accounting & Financial Management domain. We’ll use LangGraph for orchestration, RAG for financial regulation retrieval, and persistent memory to maintain state across complex audit workflows. Crucially, we’ll demonstrate how MCP-style context optimization reduces token usage by ensuring agents only "see" what they need, when they need it.
Real-Time Use Case: Automated Expense Audit & Compliance Check
Scenario: A multinational corporation processes thousands of employee expense reports daily. The finance team needs an AI system that:
Ingests expense reports from ERP systems (e.g., SAP, Oracle).
Retrieves relevant company policies and tax regulations (GDPR, SOX compliance).
Analyzes receipts and line items for anomalies (duplicate claims, policy violations).
Generates audit-ready summaries with citations.
Maintains a secure, auditable trail of all AI decisions.
Business Value:
Cost Reduction: Minimize LLM token usage by optimizing context via MCP principles.
Compliance: Ensure every decision is backed by retrieved regulatory text.
Speed: Reduce audit time from days to minutes.
Security: Okta-integrated identity ensures only authorized agents access sensitive financial data.
Architecture Overview

Implementation
Step 1: Install Dependencies
pip install langgraph langchain-core langchain-community \
chromadb faiss-cpu python-dotenv pydantic \
okta-sdk pandas numpy openai
Step 2: Define Data Models and State
# models.py
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any
from datetime import datetime
from enum import Enum
class ExpenseCategory(Enum):
TRAVEL = "travel"
MEALS = "meals"
OFFICE_SUPPLIES = "office_supplies"
SOFTWARE = "software"
CONSULTING = "consulting"
class ExpenseLineItem(BaseModel):
item_id: str = Field(description="Unique line item ID")
date: datetime = Field(description="Date of expense")
category: ExpenseCategory = Field(description="Expense category")
amount: float = Field(description="Amount in USD", gt=0)
vendor: str = Field(description="Vendor name")
description: str = Field(description="Item description")
receipt_url: Optional[str] = Field(default=None, description="URL to receipt image")
class ExpenseReport(BaseModel):
report_id: str = Field(description="Unique report ID")
employee_id: str = Field(description="Employee submitting report")
submission_date: datetime = Field(default_factory=datetime.now)
line_items: List[ExpenseLineItem] = Field(description="List of expenses")
total_amount: float = Field(description="Total claim amount")
status: str = Field(default="pending", examples=["pending", "approved", "rejected"])
class PolicyDocument(BaseModel):
doc_id: str = Field(description="Policy document ID")
title: str = Field(description="Policy title")
content: str = Field(description="Policy text")
jurisdiction: str = Field(description="Applicable region/country")
effective_date: datetime = Field(description="When policy became active")
class AuditFinding(BaseModel):
finding_id: str = Field(description="Unique finding ID")
severity: str = Field(examples=["low", "medium", "high", "critical"])
description: str = Field(description="Description of the issue")
violated_policy: str = Field(description="Reference to specific policy")
recommended_action: str = Field(description="Suggested remediation")
class FinancialAgentState(BaseModel):
"""LangGraph state for financial audit workflow"""
expense_report: ExpenseReport
retrieved_policies: List[Dict[str, Any]] = Field(default_factory=list)
audit_findings: List[AuditFinding] = Field(default_factory=list)
analysis_summary: Optional[str] = None
conversation_history: List[Dict[str, str]] = Field(default_factory=list)
token_usage_log: List[Dict[str, int]] = Field(default_factory=list) # Track MCP efficiency
is_compliant: bool = True
Step 3: MCP-Style Context Optimizer & RAG Store
# rag_store.py
import chromadb
from langchain_community.embeddings import HuggingFaceEmbeddings
from typing import List, Dict
class FinancialPolicyStore:
"""RAG store for financial policies and tax regulations"""
def __init__(self, collection_name: str = "financial_policies"):
self.client = chromadb.PersistentClient(path="./chroma_finance_db")
self.collection = self.client.get_or_create_collection(name=collection_name)
self.embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
def add_policies(self, documents: List[Dict[str, str]]):
ids = [doc["doc_id"] for doc in documents]
texts = [doc["content"] for doc in documents]
metadatas = [
{"title": doc["title"], "jurisdiction": doc["jurisdiction"]}
for doc in documents
]
embeddings = self.embeddings.embed_documents(texts)
self.collection.add(ids=ids, embeddings=embeddings, documents=texts, metadatas=metadatas)
def retrieve_relevant_policies(self, query: str, n_results: int = 3) -> List[Dict]:
query_embedding = self.embeddings.embed_query(query)
results = self.collection.query(query_embeddings=[query_embedding], n_results=n_results)
return [
{"content": doc, "metadata": meta}
for doc, meta in zip(results['documents'][0], results['metadatas'][0])
]
def initialize_policy_base():
store = FinancialPolicyStore()
policies = [
{
"doc_id": "POL_001",
"title": "Global Travel Expense Policy",
"content": "Employees must book economy class for flights under 8 hours. Meal allowances are capped at $50/day domestically and $75/day internationally. Receipts required for all expenses over $25.",
"jurisdiction": "Global"
},
{
"doc_id": "POL_002",
"title": "SOX Compliance Guidelines",
"content": "All financial transactions must have an auditable trail. Duplicate payments are strictly prohibited. Expenses must be coded to the correct general ledger account.",
"jurisdiction": "US"
},
{
"doc_id": "POL_003",
"title": "GDPR Data Handling in Finance",
"content": "Employee personal data in expense reports must be encrypted. Access to financial records is restricted to authorized personnel only via Okta SSO.",
"jurisdiction": "EU"
}
]
store.add_policies(policies)
return store
Step 4: Multi-Agent System with LangGraph & Token Tracking
# agents.py
from langgraph.graph import StateGraph, END
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
import os
import json
from dotenv import load_dotenv
load_dotenv()
from models import FinancialAgentState, ExpenseReport, AuditFinding
from rag_store import FinancialPolicyStore
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0.1, api_key=os.getenv("OPENAI_API_KEY"))
class FinancialAuditSystem:
def __init__(self):
self.policy_store = initialize_policy_base()
self.graph = self._build_graph()
def _build_graph(self) -> StateGraph:
workflow = StateGraph(FinancialAgentState)
workflow.add_node("ingest_data", self.ingestion_agent)
workflow.add_node("retrieve_context", self.context_optimizer_agent) # MCP-style
workflow.add_node("analyze_compliance", self.audit_agent)
workflow.add_node("generate_report", self.reporting_agent)
workflow.add_node("update_memory", self.memory_manager)
workflow.set_entry_point("ingest_data")
workflow.add_edge("ingest_data", "retrieve_context")
workflow.add_edge("retrieve_context", "analyze_compliance")
workflow.add_edge("analyze_compliance", "generate_report")
workflow.add_edge("generate_report", "update_memory")
workflow.add_edge("update_memory", END)
return workflow.compile()
def ingestion_agent(self, state: FinancialAgentState) -> Dict:
"""Agent 1: Validate and structure expense data"""
print(" Ingestion Agent: Validating expense report...")
# Calculate total if not provided
if not state.expense_report.total_amount:
state.expense_report.total_amount = sum(item.amount for item in state.expense_report.line_items)
return {"expense_report": state.expense_report}
def context_optimizer_agent(self, state: FinancialAgentState) -> Dict:
"""Agent 2: MCP-style Context Optimizer - Retrieve only necessary policies"""
print(" Context Optimizer: Retrieving targeted policies...")
# Build a precise query based on expense categories
categories = set(item.category.value for item in state.expense_report.line_items)
query = f"policy for {', '.join(categories)} expenses compliance"
retrieved = self.policy_store.retrieve_relevant_policies(query, n_results=3)
# Log token savings estimate (MCP benefit)
# Without MCP: ~10k tokens (full policy docs)
# With MCP: ~500 tokens (relevant snippets)
estimated_tokens_saved = 9500
return {
"retrieved_policies": retrieved,
"token_usage_log": [{"step": "context_optimization", "tokens_saved": estimated_tokens_saved}]
}
def audit_agent(self, state: FinancialAgentState) -> Dict:
"""Agent 3: Analyze compliance and detect anomalies"""
print(" Audit Agent: Checking for violations...")
findings = []
policy_context = "\n".join([p['content'] for p in state.retrieved_policies])
prompt = ChatPromptTemplate.from_template("""
You are a Senior Financial Auditor. Review the following expense report against the provided policies.
EXPENSE REPORT:
{report_json}
APPLICABLE POLICIES:
{policies}
Identify any violations, duplicates, or anomalies. For each finding, specify:
1. Severity (low/medium/high/critical)
2. Description
3. Violated Policy
4. Recommended Action
Return a JSON list of findings. If compliant, return an empty list.
""")
response = llm.invoke(prompt.format(
report_json=state.expense_report.json(),
policies=policy_context
))
try:
findings_data = json.loads(response.content)
findings = [AuditFinding(**f) for f in findings_data]
except:
findings = []
is_compliant = len(findings) == 0
return {
"audit_findings": findings,
"is_compliant": is_compliant
}
def reporting_agent(self, state: FinancialAgentState) -> Dict:
"""Agent 4: Generate executive summary"""
print(" Reporting Agent: Creating audit summary...")
prompt = ChatPromptTemplate.from_template("""
Summarize the audit results for the finance team.
REPORT ID: {report_id}
TOTAL AMOUNT: ${total_amount}
COMPLIANT: {is_compliant}
FINDINGS:
{findings}
Provide a concise 3-sentence summary and a final recommendation (Approve/Reject/Review).
""")
response = llm.invoke(prompt.format(
report_id=state.expense_report.report_id,
total_amount=state.expense_report.total_amount,
is_compliant=state.is_compliant,
findings=json.dumps([f.dict() for f in state.audit_findings])
))
return {"analysis_summary": response.content}
def memory_manager(self, state: FinancialAgentState) -> Dict:
"""Agent 5: Update audit trail memory"""
history_entry = {
"report_id": state.expense_report.report_id,
"summary": state.analysis_summary[:100],
"compliant": state.is_compliant
}
updated_history = state.conversation_history + [history_entry]
return {"conversation_history": updated_history[-20:]} # Keep last 20 audits
def run_audit(self, expense_report: ExpenseReport) -> Dict:
initial_state = FinancialAgentState(expense_report=expense_report)
result = self.graph.invoke(initial_state)
return result
Step 5: Execution & Real-Time Demo
# main.py
from agents import FinancialAuditSystem
from models import ExpenseReport, ExpenseLineItem, ExpenseCategory
from datetime import datetime
def main():
print("=" * 80)
print("OKTA MCP-ENABLED FINANCIAL AUDIT SYSTEM")
print("=" * 80)
system = FinancialAuditSystem()
# Sample Expense Report
report = ExpenseReport(
report_id="EXP-2024-001",
employee_id="EMP-12345",
line_items=[
ExpenseLineItem(
item_id="L1", date=datetime.now(), category=ExpenseCategory.TRAVEL,
amount=1200.00, vendor="Delta Airlines", description="Flight to NYC"
),
ExpenseLineItem(
item_id="L2", date=datetime.now(), category=ExpenseCategory.MEALS,
amount=85.00, vendor="The Capital Grille", description="Client dinner"
),
ExpenseLineItem(
item_id="L3", date=datetime.now(), category=ExpenseCategory.MEALS,
amount=85.00, vendor="The Capital Grille", description="Client dinner" # Duplicate!
)
],
total_amount=0
)
print("\n🚀 Running Multi-Agent Audit Workflow...\n")
result = system.run_audit(report)
print("=" * 80)
print("AUDIT RESULTS")
print("=" * 80)
print(f"\n Summary:\n{result['analysis_summary']}")
print("\n Findings:")
if result['audit_findings']:
for f in result['audit_findings']:
print(f" • [{f.severity.upper()}] {f.description}")
print(f" → Action: {f.recommended_action}")
else:
print(" No violations found.")
print(f"\n Token Efficiency (MCP Benefit):")
for log in result['token_usage_log']:
print(f" • {log['step']}: Saved ~{log['tokens_saved']} tokens")
print("\n" + "=" * 80)
if __name__ == "__main__":
main()
Key Enterprise Features
1. MCP-Style Context Optimization
The context_optimizer_agent acts as an MCP server, fetching only the specific policy snippets relevant to the expense categories. This reduces the context window size dramatically, lowering token costs and improving latency.
2. Okta-Integrated Security
While the code above focuses on logic, in production, every agent call would be gated by Okta SSO. The employee_id in the expense report would be validated against Okta’s directory to ensure the user has permission to submit expenses.
3. Auditable Memory
The memory_manager maintains a persistent trail of all audits. This is critical for SOX compliance, allowing internal auditors to trace exactly why an AI agent approved or rejected a claim.
4. Multi-Agent Specialization
Ingestion Agent: Ensures data integrity before processing.
Context Optimizer: The "MCP" brain that minimizes token waste.
Audit Agent: Performs the heavy logical lifting.
Reporting Agent: Translates technical findings into business language.
Conclusion
By integrating Okta’s identity framework with MCP principles and LangGraph’s multi-agent orchestration, enterprises can build financial AI systems that are not only intelligent but also cost-effective and compliant. This architecture ensures that as your AI agents scale, your token bills don’t spiral out of control, and every financial decision remains secure, transparent, and auditable.

Join the conversation! Your thoughts help the community grow.