Build a Paid MCP Server: Charge Users Inside Claude
The Problem: Your AI Agent Works—But How Do You Get Paid?
You've built an intelligent MCP server. It answers customer questions, processes orders, generates reports—all inside Claude. But here's the uncomfortable truth: your users aren't paying you.
Maybe you're giving away premium features for free. Maybe you're running out of compute budget. Or maybe you've built something so useful that people demand it stay free, but your server costs real money to operate.
This is where most developers hit a wall. Payment integrations are messy. You need a merchant account, PCI compliance, webhook management, and a system to hold and distribute funds. For a solo developer in Vietnam building AI tools, the friction is enormous.
There's a better way: accept payments directly into your bank account, triggered from inside Claude, with zero custody of money.
Why Payments Inside Claude Change Everything
Claude's Model Context Protocol (MCP) lets you expose tools to AI agents. Those tools can do anything—fetch data, run code, process transactions. But tools have been read-only or internal-only. What if a tool could charge?
With AgentPay VN, your MCP server becomes a point-of-sale terminal. The flow is radical in its simplicity:
- User asks Claude to do something premium ("Generate a 100-page business plan", "Analyze my restaurant's profits")
- Claude calls your MCP tool with AgentPay integrated
- User scans a VietQR code → money goes directly to your bank account
- Your tool proceeds once settlement confirms
No escrow. No holding customer funds. No middleman taking 3%.
Understanding AgentPay VN: The Mechanics
AgentPay VN is an open-source (MIT licensed) Python SDK plus MCP server that lets AI agents request payments via VietQR, Vietnam's instant transfer standard. Here's what makes it different:
- Zero custody model: Money flows straight to your merchant bank account
- Bank-level confirmation: A feed confirms settlement in real-time
- Claude-native: Works inside Claude's MCP interface
- Trivial to install:
pip install agentpay-vn
Under the hood, AgentPay generates a VietQR code pointing at your bank account. The user scans it with any Vietnamese banking app. Seconds later, your bank confirms the deposit. No tokens held server-side. No PCI audits.
Setting Up Your First Paid MCP Server
Step 1: Install and Configure AgentPay
Start with the Python SDK:
pip install agentpay-vn
Then install the MCP server:
pip install agentpay-mcp
Step 2: Create Your Merchant Profile
Create a file merchant_config.py:
from agentpay_vn import MerchantAccount
# Initialize your merchant account
merchant = MerchantAccount(
account_name="Your Business Name",
bank_account="1234567890", # Your VietCombank/Agribank/etc account
bank_code="970436", # Bank routing code
template_id="default" # VietQR template
)
merchant.save_config()
Step 3: Build a Simple Paid Tool
Here's a real-world example: a business plan generator that charges per use.
from agentpay_vn import create_payment_request, await_settlement
import json
class PaidMCPTool:
def __init__(self, merchant_config):
self.merchant = merchant_config
self.price_usd = 5 # $5 per business plan
self.price_vnd = 128_000 # ~128k VND
def generate_business_plan(self, company_name: str, industry: str):
"""
Premium tool: charges user, then generates 50-page business plan
"""
# Step 1: Create payment request
payment = create_payment_request(
amount_vnd=self.price_vnd,
description=f"Business Plan: {company_name}",
reference_id=f"plan_{company_name}_{int(time.time())}",
merchant_account=self.merchant
)
# Step 2: Return checkout URL for Claude to show user
checkout_response = {
"status": "payment_required",
"checkout_url": payment['checkout_url'],
"qr_code": payment['qr_code'],
"amount_vnd": self.price_vnd,
"expires_at": payment['expires_at']
}
# Step 3: Wait for bank settlement confirmation
# (In production, this runs async with webhooks)
settlement = await_settlement(
payment_id=payment['id'],
timeout_seconds=300 # 5-minute window
)
if not settlement['confirmed']:
return {"error": "Payment not received", "status": "timeout"}
# Step 4: Generate the actual business plan
business_plan = self._generate_plan(
company_name=company_name,
industry=industry
)
return {
"status": "success",
"payment_id": payment['id'],
"settled_at": settlement['timestamp'],
"business_plan": business_plan
}
def _generate_plan(self, company_name: str, industry: str):
# Your AI generation logic here
return f"""# Business Plan: {company_name}
## Executive Summary
[Your Claude-powered generation here]
## Market Analysis
[Industry-specific insights]..."""
tool = PaidMCPTool(merchant)
Step 4: Expose as an MCP Tool
Create an MCP server config (mcp_server.json):
{
"mcpServers": {
"agentpay-paid-tools": {
"command": "python",
"args": ["-m", "agentpay_mcp", "serve"],
"env": {
"MERCHANT_CONFIG_PATH": "./merchant_config.json",
"TOOL_MODULE": "my_paid_tools"
}
}
}
}
Add this to Claude's MCP config at ~/.config/Claude/mcp_config.json.
Real-World Walkthrough: The Online Course Bot
Imagine you run an AI consulting course. You've built Claude an MCP server that:
- Answers student questions
- Grades assignments
- Issues certificates
But here's the catch: advanced grading should be paid. Free students get automated feedback. Paid students get personalized review from Claude.
The flow in action:
- Student uploads their project report to Claude
- Claude's agent calls
grade_with_ai_review()from your MCP server - Your tool detects it's a premium feature, calls
create_payment_request(amount_vnd=50_000) - Claude displays the VietQR code to the student
- Student scans with their bank app, transfers 50k VND
- Your bank confirms in ~2 seconds
await_settlement()returns success- Your tool runs the premium grading logic
- Claude displays the detailed feedback
Total friction for the user: scan → tap → done. Total effort for you: ~30 lines of code.
Advanced Patterns: Subscriptions & Recurring Charges
For recurring revenue, chain multiple payment requests:
def create_subscription_check(user_id: str, month: str):
"""
Check if user has paid for this month's subscription.
If not, request payment before serving premium content.
"""
cached_subscription = check_payment_cache(user_id, month)
if cached_subscription:
return {"active": True, "expires_at": cached_subscription['expires']}
# Charge for the month
payment = create_payment_request(
amount_vnd=99_000, # $4/month subscription
description=f"Monthly subscription - {month}",
reference_id=f"sub_{user_id}_{month}",
merchant_account=merchant,
recurrence_rule="FREQ=MONTHLY" # Optional auto-retry
)
settlement = await_settlement(payment['id'], timeout_seconds=120)
if settlement['confirmed']:
cache_payment(user_id, month, settlement)
return {"active": True, "renews_at": next_month_date()}
else:
return {"active": False, "requires_payment": payment['checkout_url']}
With this, you can build: - AI consultant bots (charge per session) - Data analysis tools (charge per report) - Content generators (charge per 1,000 words) - Business intelligence dashboards (charge per month)
Do's and Don'ts
| ✅ DO | ❌ DON'T |
|---|---|
| Test with small amounts (1,000 VND) first | Hold user funds server-side |
| Set reasonable timeouts (2-5 min) | Hide payment amounts from users |
| Log all payment IDs for reconciliation | Retry charges without user consent |
| Provide free tier or trial first | Assume bank settlement is instant (it's usually <5s but can vary) |
| Use reference IDs matching your business logic | Process without confirming settlement |
| Implement idempotent payment checks | Build in VietQR—use AgentPay's standard flows |
Handling Edge Cases
Payment Timeout
If a user scans but doesn't complete the transfer within your timeout window:
try:
settlement = await_settlement(payment_id, timeout_seconds=300)
except PaymentTimeoutError:
# Offer to regenerate QR or refund partial processing
new_payment = create_payment_request(
amount_vnd=amount_vnd,
reference_id=f"{original_ref}_retry_1"
)
return {"status": "retry", "new_checkout_url": new_payment['checkout_url']}
Duplicate Payments
Vietnam's instant transfer system is idempotent—the same transfer won't process twice. Still, use reference IDs to track and deduplicate:
referenceId = f"task_{user_id}_{feature}_{date.today()}"
# If this ID was already settled, return cached result
# If not, request payment with this ID
Network Interruptions
AgentPay's bank feed is resilient, but if your server loses connection during settlement confirmation:
def safe_await_settlement(payment_id, timeout=300):
try:
return await_settlement(payment_id, timeout)
except NetworkError:
# Poll locally or use webhook fallback
return poll_bank_feed_for_transaction(payment_id)
Frequently Asked Questions
Q: Does AgentPay take a cut? A: No. AgentPay is open-source (MIT license). Your merchant bank account receives 100% of payments. You only pay your bank's standard transfer fees (~0.3% for most Vietnamese banks).
Q: Is this only for Vietnam? A: Currently yes—AgentPay uses VietQR, Vietnam's national instant transfer standard. International support is on the roadmap. For now, it works with any Vietnamese bank account (VietCombank, Agribank, Techcombank, etc.).
Q: What if the user cancels mid-transaction? A: The payment simply expires (after your timeout window). You never charged them. No refund logic needed.
Q: Can I combine free and paid tools in one MCP server?
A: Absolutely. Free tools call your normal methods. Paid tools call create_payment_request() first. Same server, different behaviors.
Key Takeaways
- Monetize AI agents in Claude: Turn MCP tools into revenue streams without building a payment platform
- Zero custody model: Money never touches your server—it flows straight to your bank account
- Three-line flow:
create_payment_request()→checkout_url→await_settlement() - Real VietQR, not a simulation: Users scan and pay from their own banking apps
- Open-source and MIT licensed: No vendor lock-in; full control over your implementation
- Fast settlement: Most transfers confirm in <5 seconds; never hold user funds
- Pair with Claude's tool-use: Let AI agents decide when to charge, what to charge, and what to unlock
Start Building Today
You have everything you need to launch a paid AI service this week. Install AgentPay, write your tool, expose it as an MCP server, and start charging Claude users directly into your bank account.
Get started:
pip install agentpay-vn
For complete documentation, code examples, and integration guides, visit https://agentpay.servicesai.vn/v1/docs.
Source code and issue tracking at https://github.com/phuocdu/agentpay-vn.
The age of free AI tools is over. Build, charge, scale—without the infrastructure headache.