Build a Paid MCP Server: Charge Users from Inside Claude
The Problem: Your AI Agent Creates Value, But Can't Get Paid
You've built an MCP server that saves customers hours every week. A Claude-powered research bot pulls market data. A scheduling agent books meetings with perfect timing. A content analyzer catches errors humans miss.
But here's the reality: your agent generates value while you generate invoices.
Traditional payment flows break the magic. Users leave Claude, hit a Stripe checkout, come back confused. Some never return. Payment processors hold funds for 2–7 days. You're managing subscriptions, webhooks, and error cases while your agent sits idle.
What if users could pay—from inside Claude itself—without leaving the conversation? What if the money hit your bank account within hours, not weeks?
That's the premise of AgentPay VN: an open-source Python SDK + MCP server that lets AI agents collect VietQR payments with zero friction and zero float.
Why AgentPay VN Changes the Game
Traditional Payment Flow (Broken) 1. User requests premium feature in Claude 2. Agent generates checkout link → user leaves Claude 3. User completes payment on external site 4. Webhook fires (if network is good) 5. Agent resumes (if conversation didn't time out) 6. Money sits in Stripe account for days
AgentPay VN Flow (Seamless) 1. User requests premium feature in Claude 2. Agent creates payment request (1 line) 3. User scans QR code from conversation 4. Payment hits your merchant bank account instantly 5. Agent detects settlement and delivers value 6. Conversation never breaks
Core Facts That Matter
- MIT Licensed: Deploy anywhere, modify freely, no vendor lock-in
- Zero Float: Money goes directly to your bank, not an intermediary wallet
- VietQR Native: Works with every Vietnamese bank; QR points straight at your merchant account
- Bank Feed Confirmation: Settlement verified by your bank's own feed, not a webhook you trust blindly
- Instant: From payment to agent resumption: 30–60 seconds typical
Getting Started: 3 Lines to Your First Payment
Installation
pip install agentpay-vn
That's it. No API keys to wrangle, no OAuth dance.
The Minimal 3-Step Flow
Every paid agent interaction follows this pattern:
from agentpay_vn import PaymentClient
# Initialize client (reads merchant config from env)
client = PaymentClient()
# Step 1: Create a payment request
# amount_vnd: price in Vietnamese Dong
# description: what user is paying for
payment_req = client.create_payment_request(
amount_vnd=50000, # ~$2 USD
description="Premium market analysis report",
order_id="user_123_report_456", # idempotent identifier
metadata={"user_id": "user_123", "feature": "analysis"}
)
# Step 2: Send checkout URL to user
print(f"Pay here: {payment_req.checkout_url}")
print(f"QR: {payment_req.qr_code}")
# Step 3: Wait for settlement (poll or webhook)
settlement = await client.await_settlement(
payment_id=payment_req.id,
timeout_seconds=300 # 5 minutes
)
if settlement.confirmed:
print(f"✓ Payment of {settlement.amount_vnd}đ confirmed!")
# Deliver premium content here
deliver_premium_report()
else:
print("Payment timeout or cancelled")
What happens line-by-line:
PaymentClient()reads your merchant bank account details from environment variables (MERCHANT_ACCOUNT,MERCHANT_BANK, etc.). No credentials in code.create_payment_request()generates a unique payment with a QR code that points directly at your bank account. Returns a checkout URL and QR image.await_settlement()polls your bank's feed API until the exact amount appears. When confirmed, your agent resumes.
The beauty: no webhook failures, no payment processor, no holding account.
Setting Up AgentPay MCP for Claude
To call this from inside Claude, you need an MCP server. AgentPay provides one:
1. Install the MCP Server
pip install agentpay-vn[mcp]
2. Configure Claude Desktop
Edit ~/.config/Claude/claude_desktop_config.json:
{
"mcpServers": {
"agentpay": {
"command": "python",
"args": ["-m", "agentpay_vn.mcp"],
"env": {
"MERCHANT_ACCOUNT": "1234567890",
"MERCHANT_BANK": "970408",
"MERCHANT_NAME": "Your Company Ltd"
}
}
}
}
Where to find these:
- MERCHANT_ACCOUNT: Your business bank account number
- MERCHANT_BANK: Your bank's BIN (e.g., 970408 = Techcombank)
- MERCHANT_NAME: Your registered business name
Restart Claude. You now have access to:
- create_payment_request (amount, description, order_id)
- check_settlement_status (payment_id)
- get_payment_history (filters by date, status)
3. Test in Claude
Ask Claude: "I want to charge $2 for a premium report. Can you create a payment request?"
Claude uses AgentPay MCP internally, returns something like:
Payment ID: pay_abc123
Checkout URL: https://...
QR Code: [image]
Amount: 50,000đ
You're live.
Real-World Walkthrough: The Course-Selling Bot
Scenario: "LearnAI" Chatbot
You've trained a Claude agent to sell and deliver AI courses. Free users get a taste; paid users get full curriculum + live feedback.
Architecture
from agentpay_vn import PaymentClient
import json
class CourseAgent:
def __init__(self):
self.payment_client = PaymentClient()
self.courses = {
"foundation": {"price_vnd": 150000, "title": "AI Fundamentals"},
"advanced": {"price_vnd": 300000, "title": "LLM Fine-Tuning"},
}
def handle_purchase_request(self, user_id: str, course_key: str):
"""User asks: 'I want the Advanced course'"""
if course_key not in self.courses:
return "Course not found."
course = self.courses[course_key]
# Step 1: Create payment
payment = self.payment_client.create_payment_request(
amount_vnd=course["price_vnd"],
description=f"Course: {course['title']}",
order_id=f"user_{user_id}_course_{course_key}",
metadata={"user_id": user_id, "course": course_key}
)
# Step 2: Show payment prompt
response = f"""
Great! Here's your {course['title']} payment:
Amount: {course['price_vnd']:,}đ (~$8 USD)
QR Code: [See QR in Claude]
Or visit: {payment.checkout_url}
Waiting for payment...
"""
# Step 3: Wait for settlement
settlement = self.payment_client.await_settlement(
payment_id=payment.id,
timeout_seconds=600 # 10 minutes
)
if settlement.confirmed:
# Deliver course
self.grant_course_access(user_id, course_key)
return f"✓ Payment confirmed! Your course access is active. Start with Module 1: Transformers."
else:
return "Payment timed out. Try again?"
def grant_course_access(self, user_id: str, course_key: str):
# Write to database, generate API token, etc.
print(f"Granted {course_key} to {user_id}")
# In production: save to DB, send email, etc.
# Usage in Claude conversation
agent = CourseAgent()
response = agent.handle_purchase_request(
user_id="claude_user_xyz",
course_key="advanced"
)
print(response)
What the user sees in Claude:
User: "I want to buy the Advanced course"
Claude (using AgentPay): "Great! Here's your AI course payment.
Amount: 300,000đ (~$8 USD)
[QR Code displayed]
Or visit: https://checkout.agentpay.vn/...
Waiting for payment...
✓ Payment confirmed! Your course access is active.
Let's start: Module 1 covers Transformer Architecture."
Behind the scenes: 1. QR points to merchant's bank account 2. User scans with their banking app (not a new website) 3. Payment clears in 30 seconds 4. Agent detects settlement and delivers content 5. Total UX: 60 seconds, no context switch
Do's and Don'ts: Common Pitfalls
| Do | Don't |
|---|---|
✓ Use order_id to deduplicate requests |
✗ Recreate payment requests on every retry |
✓ Set timeout_seconds based on your UX (300–600s typical) |
✗ Infinite wait loops; users get bored |
✓ Store payment_id to track settlements later |
✗ Assume payment succeeded before await_settlement returns True |
| ✓ Include clear metadata (user_id, feature, timestamp) | ✗ Leave metadata blank; you'll regret debugging later |
| ✓ Test with small amounts (5,000đ) first | ✗ Deploy to production before a single test payment |
| ✓ Handle timeout gracefully ("Payment didn't arrive yet") | ✗ Crash or hang if settlement takes >5 minutes |
Advanced: Subscription & Recurring Billing
For agents that charge monthly, AgentPay supports recurring payments:
# Create a recurring payment (monthly)
recurring = client.create_recurring_payment(
amount_vnd=100000, # 100k/month
frequency="monthly",
description="Premium AI Research Subscription",
user_id="user_123",
max_charges=12 # Stop after 1 year
)
print(f"Setup URL: {recurring.setup_url}")
# User authorizes once, then charged automatically each month
# You receive bank feed confirmation each time
Perfect for: - Agents offering ongoing services (research subscriptions, content analysis, monitoring) - Keeping UX frictionless (one QR scan, 12 months of billing)
Deployment Checklist
Before going live:
- [ ] Merchant Account Setup: Register with your bank; get account, BIN, and API access to bank feed
- [ ] Environment Variables: Set
MERCHANT_ACCOUNT,MERCHANT_BANK,MERCHANT_NAMEsafely (use.envor secrets manager) - [ ] Test Payments: Send 5–10 small test transactions; verify they appear in your bank feed within 60 seconds
- [ ] Timeout Tuning: Test different network conditions; adjust
timeout_secondsbased on real-world latency - [ ] Error Handling: Gracefully handle payment cancellations, timeouts, and network failures
- [ ] Documentation: Tell users how to pay (QR scan, no account required) in your agent's system prompt
- [ ] Compliance: Keep records of all payments and settlements for tax/audit purposes (AgentPay stores these automatically)
FAQ
Q: Does AgentPay hold my money?
No. The QR code points directly at your merchant bank account. Money arrives there; AgentPay never touches it. You're always in control.
Q: What happens if the user doesn't scan the QR within the timeout?
await_settlement() returns settled=False. Your agent should ask the user to try again or manually resend the payment link. The payment request remains valid for 24 hours.
Q: Can I use this outside Vietnam?
Not directly—AgentPay VN uses VietQR, which requires a Vietnamese bank account. However, if you accept Vietnamese customers or have a VN business bank account, you're good.
Q: How do I know if a payment really settled?
AgentPay queries your bank's official feed API directly. When settlement.confirmed == True, the money is in your account, not pending. No webhook required.
Key Takeaways
- Monetize inside Claude: Users pay without leaving the conversation; you get money without leaving your code.
- Zero float: VietQR payments go straight to your bank account, not a holding wallet.
- 3-line integration:
create_payment_request→ show QR →await_settlement. - Bank-verified: Settlement confirmed by your bank's feed, not a third-party webhook.
- Open-source: MIT license means full transparency and control; deploy anywhere.
- Real-world ready: Use it for courses, reports, consultations, services—anything your agent delivers.
Get Started Now
pip install agentpay-vn
Next Steps:
- Read the docs: https://agentpay.servicesai.vn/v1/docs
- Explore the source: https://github.com/phuocdu/agentpay-vn
- Test with Claude: Set up the MCP server; ask Claude to create a payment request
- Deploy your first paid agent: Follow the course-selling walkthrough above
Your AI agents are about to start paying their way. Welcome to the agent economy.