File size: 17,158 Bytes
1c67453 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 |
```markdown
# MCP Server Implementation Guide
## Overview
RewardPilot implements a multi-agent MCP (Model Context Protocol) architecture with 4 independent microservices that work together to provide intelligent credit card recommendations.
## Architecture Diagram
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User Interface β
β (Gradio 6.0 App) β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Orchestrator Agent β
β (Claude 3.5 Sonnet) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Phase 1: Planning β β
β β - Analyze transaction context β β
β β - Determine required MCP servers β β
β β - Create execution strategy β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
βΌ βΌ βΌ
βββββββββββββββββ ββββββββββββ ββββββββββββββ
β Smart Wallet β β RAG β β Forecast β
β MCP Server β β MCP β β MCP Server β
βββββββββ¬ββββββββ ββββββ¬ββββββ βββββββ¬βββββββ
β β β
βΌ βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββ
β Gemini 2.0 Flash β
β (Reasoning & Synthesis) β
ββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββ
β Final Responseβ
βββββββββββββββββ
```
---
## MCP Server 1: Orchestrator
### Purpose
Coordinates all MCP servers and manages the agent workflow.
### Deployment
- **URL:** https://mcp-1st-birthday-rewardpilot-orchestrator.hf.space
- **Stack:** FastAPI + Claude 3.5 Sonnet
- **Hosting:** Hugging Face Spaces
### API Endpoints
#### POST `/recommend`
Get card recommendation for a transaction.
**Request:**
```json
{
"user_id": "u_alice",
"merchant": "Whole Foods",
"mcc": "5411",
"amount_usd": 127.50,
"category": "Groceries"
}
```
**Response:**
```json
{
"recommended_card": {
"card_id": "c_amex_gold",
"card_name": "American Express Gold",
"issuer": "American Express"
},
"rewards": {
"points_earned": 510,
"cash_value": 5.10,
"earn_rate": "4x points"
},
"reasoning": "Amex Gold offers 4x points on U.S. supermarkets...",
"confidence": 0.95,
"alternatives": [
{
"card_name": "Citi Custom Cash",
"rewards": 3.82,
"reason": "5% but monthly cap already hit"
}
],
"warnings": [
"You're at $450/$1500 monthly cap. 3 more grocery trips available."
]
}
```
### Implementation
```python
# orchestrator_server.py
from fastapi import FastAPI, HTTPException
from anthropic import Anthropic
import httpx
import asyncio
app = FastAPI(title="RewardPilot Orchestrator")
anthropic = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
@app.post("/recommend")
async def recommend_card(request: TransactionRequest):
# Phase 1: Planning with Claude
plan = await create_execution_plan(request)
# Phase 2: Parallel MCP calls
mcp_results = await execute_mcp_calls(plan)
# Phase 3: Reasoning with Gemini
explanation = await synthesize_reasoning(request, mcp_results)
# Phase 4: Format response
return format_recommendation(mcp_results, explanation)
async def create_execution_plan(request: TransactionRequest):
"""Claude analyzes transaction and plans MCP calls"""
prompt = f"""
Analyze this transaction and determine which MCP servers to call:
Transaction:
- Merchant: {request.merchant}
- Category: {request.category}
- Amount: ${request.amount_usd}
Available MCP servers:
1. smart_wallet - Card recommendations and reward calculations
2. rewards_rag - Semantic search of card benefits
3. spend_forecast - Spending predictions and cap warnings
Return a JSON plan with:
- strategy: optimization approach
- mcp_calls: list of servers to call (priority order)
- confidence_threshold: minimum confidence for recommendation
"""
response = anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return json.loads(response.content[0].text)
async def execute_mcp_calls(plan: dict):
"""Call MCP servers in parallel"""
tasks = []
for mcp_call in plan["mcp_calls"]:
if mcp_call["service"] == "smart_wallet":
tasks.append(call_smart_wallet(request))
elif mcp_call["service"] == "rewards_rag":
tasks.append(call_rewards_rag(request))
elif mcp_call["service"] == "spend_forecast":
tasks.append(call_forecast(request))
results = await asyncio.gather(*tasks)
return dict(zip([c["service"] for c in plan["mcp_calls"]], results))
```
---
## MCP Server 2: Smart Wallet
### Purpose
Analyzes user's credit cards and calculates optimal rewards.
### Deployment
- **URL:** https://mcp-1st-birthday-rewardpilot-smart-wallet.hf.space
- **Stack:** FastAPI + Python + PostgreSQL
- **Hosting:** Hugging Face Spaces
### API Endpoints
#### POST `/analyze`
Analyze transaction against user's wallet.
**Request:**
```json
{
"user_id": "u_alice",
"merchant": "Whole Foods",
"mcc": "5411",
"amount_usd": 127.50
}
```
**Response:**
```json
{
"recommended_card": {
"card_id": "c_amex_gold",
"card_name": "American Express Gold",
"rewards_earned": 5.10,
"earn_rate": "4x points",
"points_earned": 510
},
"all_cards_comparison": [
{
"card_name": "Amex Gold",
"rewards": 5.10,
"rank": 1
},
{
"card_name": "Citi Custom Cash",
"rewards": 3.82,
"rank": 2,
"note": "Cap already hit this month"
}
]
}
```
### Implementation
```python
# smart_wallet_server.py
from fastapi import FastAPI
from sqlalchemy import create_engine
from typing import List
app = FastAPI(title="Smart Wallet MCP")
class CardAnalyzer:
def __init__(self, user_id: str):
self.user_id = user_id
self.cards = self.load_user_cards()
def analyze_transaction(self, merchant: str, mcc: str, amount: float):
"""Calculate rewards for all cards"""
results = []
for card in self.cards:
# Get reward rate for this MCC
reward_rate = self.get_reward_rate(card, mcc)
# Check spending caps
current_spending = self.get_monthly_spending(card, mcc)
cap_remaining = card.monthly_cap - current_spending
# Calculate rewards
if cap_remaining >= amount:
rewards = amount * reward_rate
else:
# Partial cap scenario
rewards = (cap_remaining * reward_rate) +
((amount - cap_remaining) * card.base_rate)
results.append({
"card": card,
"rewards": rewards,
"effective_rate": rewards / amount,
"cap_status": {
"current": current_spending,
"limit": card.monthly_cap,
"remaining": cap_remaining
}
})
# Sort by rewards (descending)
results.sort(key=lambda x: x["rewards"], reverse=True)
return results[0] # Return best card
```
---
## MCP Server 3: Rewards RAG
### Purpose
Semantic search across credit card benefit documents.
### Deployment
- **URL:** https://mcp-1st-birthday-rewardpilot-rewards-rag.hf.space
- **Stack:** FastAPI + LlamaIndex + ChromaDB
- **Hosting:** Hugging Face Spaces
### API Endpoints
#### POST `/query`
Search card benefits with natural language.
**Request:**
```json
{
"query": "Does Amex Gold work at Costco for groceries?",
"card_name": "American Express Gold",
"top_k": 3
}
```
**Response:**
```json
{
"answer": "No, American Express cards are not accepted at Costco warehouse locations due to Costco's exclusive Visa agreement. However, Amex Gold works at Costco.com for online orders.",
"sources": [
{
"card_name": "American Express Gold",
"content": "Merchant acceptance: Not accepted at Costco warehouses...",
"relevance_score": 0.92
}
]
}
```
### Implementation
See `docs/llamaindex_setup.md` for detailed RAG implementation.
---
## MCP Server 4: Spend Forecast
### Purpose
ML-based spending predictions and cap warnings.
### Deployment
- **URL:** https://mcp-1st-birthday-rewardpilot-spend-forecast.hf.space
- **Stack:** FastAPI + Scikit-learn + Redis
- **Hosting:** Hugging Face Spaces
### API Endpoints
#### POST `/predict`
Predict spending for next period.
**Request:**
```json
{
"user_id": "u_alice",
"card_id": "c_amex_gold",
"category": "Groceries",
"horizon_days": 30
}
```
**Response:**
```json
{
"predicted_spending": 520.50,
"confidence_interval": [480.00, 560.00],
"warnings": [
{
"type": "cap_warning",
"message": "Likely to exceed $500 monthly cap",
"probability": 0.78,
"suggested_action": "Switch to Citi Custom Cash after $500"
}
]
}
```
### Implementation
```python
# forecast_server.py
from fastapi import FastAPI
from sklearn.ensemble import RandomForestRegressor
import numpy as np
app = FastAPI(title="Spend Forecast MCP")
class SpendingForecaster:
def __init__(self):
self.model = RandomForestRegressor(n_estimators=100)
def predict(self, user_id: str, category: str, horizon_days: int):
"""Predict spending for next N days"""
# Load historical data
history = self.load_user_history(user_id, category)
# Feature engineering
features = self.extract_features(history)
# Predict
prediction = self.model.predict(features)
# Calculate confidence interval
predictions = [tree.predict(features) for tree in self.model.estimators_]
lower = np.percentile(predictions, 5)
upper = np.percentile(predictions, 95)
return {
"predicted_spending": float(prediction[0]),
"confidence_interval": [float(lower), float(upper)]
}
```
---
## Communication Flow
### Sequence Diagram
```
User -> Gradio: Enter transaction
Gradio -> Orchestrator: POST /recommend
Orchestrator -> Claude: Create execution plan
Claude -> Orchestrator: {plan: call all 3 MCPs}
Orchestrator -> Smart Wallet: POST /analyze
Orchestrator -> RAG: POST /query
Orchestrator -> Forecast: POST /predict
Smart Wallet -> Orchestrator: {best_card: Amex Gold, rewards: 5.10}
RAG -> Orchestrator: {benefits: "4x on groceries..."}
Forecast -> Orchestrator: {warning: "Near cap"}
Orchestrator -> Gemini: Synthesize results
Gemini -> Orchestrator: {explanation: "Use Amex Gold because..."}
Orchestrator -> Gradio: Final recommendation
Gradio -> User: Display result
```
---
## Deployment Instructions
### 1. Deploy Each MCP Server to Hugging Face
```bash
# Clone template
git clone https://huggingface.co/spaces/YOUR_USERNAME/rewardpilot-orchestrator
# Add files
cp orchestrator_server.py app.py
cp requirements.txt .
# Create Space on HF
huggingface-cli repo create rewardpilot-orchestrator --type space --space_sdk gradio
# Push
git add .
git commit -m "Deploy orchestrator"
git push
```
### 2. Set Environment Variables
In each Space's settings, add:
```bash
ANTHROPIC_API_KEY=sk-ant-xxxxx
GEMINI_API_KEY=AIzaSyxxxxx
OPENAI_API_KEY=sk-xxxxx
```
### 3. Configure Endpoints
In main `app.py`:
```python
MCP_ENDPOINTS = {
"orchestrator": "https://mcp-1st-birthday-rewardpilot-orchestrator.hf.space",
"smart_wallet": "https://mcp-1st-birthday-rewardpilot-smart-wallet.hf.space",
"rewards_rag": "https://mcp-1st-birthday-rewardpilot-rewards-rag.hf.space",
"forecast": "https://mcp-1st-birthday-rewardpilot-spend-forecast.hf.space"
}
```
---
## Error Handling
### Graceful Degradation
```python
async def call_mcp_with_fallback(service_name: str, request_data: dict):
"""Call MCP server with timeout and fallback"""
try:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(
MCP_ENDPOINTS[service_name],
json=request_data
)
response.raise_for_status()
return response.json()
except httpx.TimeoutException:
logger.error(f"{service_name} timeout")
return get_fallback_response(service_name)
except httpx.HTTPError as e:
logger.error(f"{service_name} error: {e}")
return get_fallback_response(service_name)
```
---
## Monitoring
### Health Checks
```python
@app.get("/health")
async def health_check():
"""Check status of all MCP servers"""
statuses = {}
for service, url in MCP_ENDPOINTS.items():
try:
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(f"{url}/health")
statuses[service] = {
"status": "healthy" if response.status_code == 200 else "unhealthy",
"latency_ms": response.elapsed.total_seconds() * 1000
}
except Exception as e:
statuses[service] = {"status": "down", "error": str(e)}
return statuses
```
---
## Performance Optimization
### Caching Strategy
```python
from functools import lru_cache
import redis
# Redis cache for frequent queries
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
@lru_cache(maxsize=1000)
def get_card_benefits(card_name: str):
"""Cache card benefits for 1 hour"""
cache_key = f"benefits:{card_name}"
# Check cache
cached = redis_client.get(cache_key)
if cached:
return json.loads(cached)
# Fetch from RAG
result = call_rewards_rag({"query": f"Get all benefits for {card_name}"})
# Cache for 1 hour
redis_client.setex(cache_key, 3600, json.dumps(result))
return result
```
---
## Testing
### Integration Tests
```python
import pytest
import httpx
@pytest.mark.asyncio
async def test_orchestrator_end_to_end():
"""Test full recommendation flow"""
async with httpx.AsyncClient() as client:
response = await client.post(
f"{MCP_ENDPOINTS['orchestrator']}/recommend",
json={
"user_id": "test_user",
"merchant": "Whole Foods",
"amount_usd": 100.00
}
)
assert response.status_code == 200
data = response.json()
assert "recommended_card" in data
assert "rewards" in data
assert "reasoning" in data
```
---
## Next Steps
1. **Scale MCP servers** - Add load balancing
2. **Add authentication** - JWT tokens for API access
3. **Implement webhooks** - Real-time transaction notifications
4. **Add more MCP servers** - Travel optimization, business expenses, etc.
---
**Related Documentation:**
- [Modal Deployment Guide](./modal_deployment.md)
- [LlamaIndex RAG Setup](./llamaindex_setup.md)
- [Agent Reasoning Flow](./agent_reasoning.md)
```
---
|