MCP servers for trade operations: architecture and examples
How Model Context Protocol servers expose trade-operations data (ERP, banking, shipping, KYB) safely to AI agents — architecture patterns, security model, and three reference implementations.
MCP Servers for Trade Operations: Architecture and Examples
Your AI agent needs to classify an HS code, check duty rates, and submit a customs declaration. Without MCP, that's three separate integrations, three authentication flows, three error-handling patterns. Multiply by every country you operate in, and you've built a maintenance nightmare before your agent executes its first trade.
The Model Context Protocol solves this by giving AI agents a single way to discover and use trade system capabilities. Instead of hardcoding API calls, your agent asks an MCP server "what can you do?" and gets back structured resources (data it can read) and tools (actions it can take). The server handles the messy reality of inconsistent customs APIs, carrier formats, and bank interfaces.
This article walks through MCP architecture for trade operations, with working examples for customs declarations and trade finance. You'll see how to design resources for HS classification, build tools for declaration submission, and handle the async approval workflows that make trade different from typical enterprise integrations.
What Is the Model Context Protocol and Why Does It Matter for Trade?
The Integration Problem MCP Solves
Every AI agent that touches trade systems faces the same math problem: N agents times M systems equals N×M custom integrations. Your classification agent needs ACE access. Your documentation agent needs carrier APIs. Your compliance agent needs sanctions screening. Each connection requires authentication code, error handling, rate limiting, and format translation.
MCP collapses this to N+M. Agents speak MCP. Servers speak MCP. The protocol handles capability discovery, so agents don't need hardcoded knowledge of what each system offers.
The ecosystem is growing fast. Within two months of Anthropic releasing the specification, developers had built over 1,000 community MCP servers. Most target generic enterprise use cases—databases, file systems, communication tools. Trade-specific servers remain rare, which is both a gap and an opportunity.
MCP Architecture: Resources, Tools, and Prompts
MCP defines three primitives that map cleanly to trade operations:
Resources expose data your agent can read. For trade, this includes:
- HS code classification databases
- Duty rate schedules by country pair
- Shipment tracking status
- Document templates and requirements
Tools let your agent take actions. Trade examples:
submit_customs_declaration— file entry with a Single Window systemrequest_certificate_of_origin— initiate CO applicationinitiate_letter_of_credit— start LC workflow with issuing bank
Prompts provide reusable workflows. A classification prompt might guide an agent through gathering product details, checking binding rulings, and selecting the appropriate HS code with reasoning.
The key insight: resources are read-only and safe to call freely. Tools execute actions and require explicit user consent before invocation. This distinction matters for compliance—your audit trail shows exactly when a human approved each declaration submission.
How MCP Differs from Traditional API Integration
| Aspect | Traditional REST/GraphQL | Model Context Protocol |
|---|---|---|
| Connection model | Point-to-point, hardcoded endpoints | Capability discovery, dynamic binding |
| Data access | Custom parsing per API | Standardized resource format |
| Action execution | Direct API calls | Tool invocation with consent checkpoint |
| Consent handling | Application-level (if any) | Protocol-level, explicit approval |
| Audit capability | Custom logging implementation | Built-in invocation tracking |
| Transport | HTTP only | stdio (local) or HTTP+SSE (remote) |
MCP uses JSON-RPC 2.0 as its message format, running over either stdio (for local development) or HTTP with Server-Sent Events (for production deployments). The protocol includes capability negotiation—servers declare what they support, clients declare what they need, and both sides agree on a compatible feature set.
For trade operations, the consent model deserves emphasis. When your agent calls submit_customs_declaration, MCP requires the user to approve before execution. This isn't just good UX—it's audit evidence that a human authorized each filing, which matters when customs asks who approved that entry.
Trade Operations MCP Server Architecture
Reference Architecture for Cross-Border Trade
The architecture layers cleanly:
AI Client Layer: Claude, GPT-4, or your custom agent. Speaks MCP, discovers available servers, orchestrates multi-step workflows.
MCP Server Layer: Purpose-built servers for each trade domain. A customs server wraps Single Window APIs. A shipping server normalizes carrier tracking. A trade finance server handles LC and payment workflows.
Schema Layer: The WCO Data Model (used by 183 member countries) and UN/CEFACT standards inform how MCP servers structure their resources and tools. When your customs server exposes an HS classification resource, the response format aligns with WCO conventions.
System Layer: The actual APIs—US ACE, EU EUCDM, carrier EDI, bank SWIFT interfaces. MCP servers translate between protocol-standard formats and system-specific requirements.
Designing MCP Resources for Trade Data
Resources follow a URI pattern and return structured data. A well-designed trade resource includes:
{
"jsonrpc": "2.0",
"method": "resources/read",
"params": {
"uri": "trade://customs/hs-classification/8471.30"
},
"id": 1
}
Response:
{
"jsonrpc": "2.0",
"result": {
"contents": [{
"uri": "trade://customs/hs-classification/8471.30",
"mimeType": "application/json",
"text": "{\"code\":\"8471.30\",\"description\":\"Portable automatic data processing machines, weighing not more than 10 kg\",\"duty_rates\":{\"US\":{\"general\":\"0%\",\"column2\":\"35%\"},\"EU\":{\"MFN\":\"0%\"}},\"notes\":[\"Includes laptops, notebooks, tablets with keyboard\"],\"binding_rulings_available\":true}"
}]
},
"id": 1
}
Notice the resource includes duty rates for multiple jurisdictions, relevant classification notes, and a flag indicating binding rulings exist. Your agent can use this to make informed decisions without additional API calls.
Building MCP Tools for Trade Actions
Tools require more careful design because they execute real-world actions. A customs declaration tool needs:
- Input validation — Catch errors before hitting the customs API
- Consent checkpoint — MCP protocol ensures user approval
- Execution with error handling — Graceful failure modes
- Audit logging — Every invocation recorded with parameters and outcome
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "submit_customs_declaration",
"arguments": {
"entry_type": "01",
"importer_id": "12-3456789",
"port_of_entry": "2704",
"line_items": [
{
"hs_code": "8471.30.0100",
"description": "Laptop computers",
"quantity": 500,
"value_usd": 250000,
"country_of_origin": "TW"
}
]
}
},
"id": 2
}
The MCP client (Claude, your agent framework) intercepts this call and presents it to the user for approval before the server executes. This creates a clear audit record: "User X approved declaration submission at timestamp Y with parameters Z."
Multi-Server Orchestration for End-to-End Workflows
Real trade workflows span multiple domains. An import requires customs clearance, shipping coordination, and payment execution. MCP handles this through multi-server connections—your agent maintains sessions with each relevant server and orchestrates the workflow.
The consent checkpoint appears before each tool invocation. Your agent might calculate duties and prepare documentation automatically, but the actual submission waits for human approval. This matches how Authorized Economic Operator programs expect compliance controls to work.
For payment execution, the BIS Project Nexus specifications target sub-60-second cross-border settlement. An MCP tool wrapping Nexus-compatible payment rails could trigger near-instant settlement once the customs release confirms.
Example: Customs Declaration MCP Server
Wrapping Single Window APIs with MCP
The WTO Trade Facilitation Agreement (Article 10.4) requires member countries to implement Single Window systems—one submission point for all import/export documentation. In practice, each country's Single Window has different APIs, authentication methods, and data formats.
An MCP customs server abstracts these differences. Your agent calls the same submit_customs_declaration tool whether filing with US ACE, EU EUCDM, or Singapore TradeNet. The server handles:
- Authentication (certificates, API keys, OAuth tokens depending on system)
- Format translation (your standard payload to system-specific XML/JSON)
- Response normalization (various status codes mapped to consistent states)
- Error handling (system-specific errors translated to actionable messages)
This abstraction pays off quickly. Adding a new country means implementing one MCP server, not updating every agent that touches customs.
Resource Implementation: HS Code Classification
The HS classification resource demonstrates MCP's data access pattern. Here's a simplified implementation:
@server.read_resource("trade://customs/hs-classification/{code}")
async def read_hs_classification(code: str) -> Resource:
# Query HS database (WCO Data Model format)
classification = await hs_database.lookup(code)
# Enrich with duty rates from multiple jurisdictions
duty_rates = await duty_service.get_rates(
code,
jurisdictions=["US", "EU", "UK", "CA"]
)
# Check for binding rulings
rulings = await rulings_database.search(code)
return Resource(
uri=f"trade://customs/hs-classification/{code}",
mimeType="application/json",
text=json.dumps({
"code": code,
"description": classification.description,
"chapter_notes": classification.notes,
"duty_rates": duty_rates,
"binding_rulings": [r.summary for r in rulings[:5]],
"last_updated": classification.updated_at.isoformat()
})
)
The resource aggregates data from multiple sources—HS database, duty rate service, binding rulings—into a single response. Your agent gets everything needed for classification decisions in one call.
For deeper coverage of classification approaches, see our guide on AI-powered HS code classification.
Tool Implementation: Declaration Submission
The declaration submission tool shows MCP's action execution pattern with proper consent handling:
@server.tool("submit_customs_declaration")
async def submit_declaration(
entry_type: str,
importer_id: str,
port_of_entry: str,
line_items: list[LineItem],
supporting_documents: list[DocumentRef]
) -> ToolResult:
# Validate before execution
validation_errors = validate_declaration(
entry_type, importer_id, port_of_entry, line_items
)
if validation_errors:
return ToolResult(
success=False,
error=f"Validation failed: {validation_errors}"
)
# Log the invocation (audit trail)
audit_log.record(
action="submit_customs_declaration",
parameters={
"entry_type": entry_type,
"importer_id": importer_id,
"port_of_entry": port_of_entry,
"line_items_count": len(line_items),
"total_value": sum(item.value for item in line_items)
},
timestamp=datetime.utcnow(),
user_consent_received=True # MCP protocol ensures this
)
# Submit to appropriate Single Window
result = await single_window_client.submit(
build_declaration_payload(
entry_type, importer_id, port_of_entry,
line_items, supporting_documents
)
)
return ToolResult(
success=result.accepted,
data={
"entry_number": result.entry_number,
"status": result.status,
"estimated_release": result.estimated_release_time
}
)
The audit log captures every invocation with full parameters. When customs audits your entries, you can show exactly what was submitted, when, and that user consent was obtained through the MCP protocol.
Studies show automation can reduce customs clearance time by 70-80% compared to manual processing. MCP-powered agents can achieve these gains while maintaining the compliance controls that keep your AEO status intact.
Handling Regulatory Approval Workflows
Customs decisions aren't instant. Your declaration might clear immediately, get flagged for document review, or require physical inspection. MCP tools need to handle these async patterns:
@server.tool("check_declaration_status")
async def check_status(entry_number: str) -> ToolResult:
status = await single_window_client.get_status(entry_number)
if status.state == "PENDING_DOCUMENTS":
return ToolResult(
success=True,
data={
"status": "pending_documents",
"required_documents": status.required_docs,
"deadline": status.response_deadline.isoformat(),
"suggested_action": "Upload required documents using submit_supporting_document tool"
}
)
if status.state == "EXAMINATION_ORDERED":
return ToolResult(
success=True,
data={
"status": "examination_ordered",
"exam_type": status.exam_type,
"location": status.exam_location,
"suggested_action": "Coordinate with freight forwarder for exam scheduling"
}
)
# ... handle other states
Your agent can poll status and take appropriate follow-up actions—uploading additional documents, notifying stakeholders, or escalating to human operators when needed.
Example: Trade Finance MCP Server
Connecting AI Agents to Letters of Credit Systems
Trade finance remains stubbornly paper-based. Less than 1% of trade documents are fully digital, according to the ICC Digital Standards Initiative. This creates opportunity for MCP servers that bridge AI agents to LC systems.
The legal framework is evolving. MLETR (Model Law on Electronic Transferable Records) adoption enables digital bills of lading and other negotiable instruments. An MCP trade finance server can expose tools that work within this emerging digital framework.
@server.tool("initiate_letter_of_credit")
async def initiate_lc(
applicant: str,
beneficiary: str,
amount: Money,
terms: LCTerms,
required_documents: list[str]
) -> ToolResult:
# Note: Actual LC initiation requires bank relationship and KYC
# This tool initiates the application workflow
application = await bank_api.create_lc_application(
applicant=applicant,
beneficiary=beneficiary,
amount=amount,
terms=terms,
required_documents=required_documents
)
return ToolResult(
success=True,
data={
"application_id": application.id,
"status": "pending_bank_review",
"next_steps": [
"Bank will review application within 2 business days",
"Additional documentation may be requested",
"LC will be issued upon approval"
]
}
)
Note the tool initiates an application workflow rather than directly issuing an LC. Bank relationships, KYC requirements, and credit decisions remain with the financial institution. The MCP server streamlines the application process, not the approval decision.
Document Verification Resources
Trade finance depends on document verification—bills of lading, certificates of origin, commercial invoices. MCP resources can expose verification status:
@server.read_resource("trade://finance/document/{document_id}")
async def read_document_status(document_id: str) -> Resource:
doc = await document_registry.get(document_id)
verification = {
"document_type": doc.type,
"issuer": doc.issuer,
"issue_date": doc.issued_at.isoformat(),
"verification_status": doc.verification_status,
"blockchain_anchor": doc.blockchain_tx_id if doc.anchored else None,
"matches_lc_requirements": doc.lc_compliance_check
}
return Resource(
uri=f"trade://finance/document/{document_id}",
mimeType="application/json",
text=json.dumps(verification)
)
When documents are anchored to blockchain or verified through trusted registries, the resource exposes that verification status. Your agent can check document authenticity before proceeding with payment release.
Payment Trigger Tools with ISO 20022
Cross-border payments increasingly use ISO 20022 messaging. An MCP tool can trigger payment execution using this standard:
@server.tool("trigger_trade_payment")
async def trigger_payment(
lc_reference: str,
payment_amount: Money,
beneficiary_account: BankAccount,
documents_presented: list[str]
) -> ToolResult:
# Verify LC conditions met
lc = await lc_service.get(lc_reference)
compliance = await lc_service.check_document_compliance(
lc, documents_presented
)
if not compliance.all_conditions_met:
return ToolResult(
success=False,
error=f"LC conditions not met: {compliance.missing_conditions}"
)
# Build ISO 20022 payment message
payment_msg = build_iso20022_payment(
amount=payment_amount,
beneficiary=beneficiary_account,
reference=lc_reference
)
# Submit to payment network
result = await payment_network.submit(payment_msg)
return ToolResult(
success=True,
data={
"payment_reference": result.reference,
"status": result.status,
"expected_settlement": result.settlement_time.isoformat()
}
)
With BIS Project Nexus targeting sub-60-second settlement for cross-border payments, these tools can enable near-instant payment execution once trade conditions are verified.
Compliance and Audit Considerations
Why MCP's Consent Model Matters for Regulated Trade
The MCP specification requires explicit user consent before tool execution. This isn't optional—it's built into the protocol. For trade operations, this design choice aligns with regulatory expectations.
The WCO SAFE Framework expects AEO-certified companies to maintain clear authorization controls. When your AI agent submits a customs declaration, auditors want to see:
- Who authorized the submission
- What information was submitted
- When the authorization occurred
- What the agent's reasoning was
MCP's consent checkpoint creates evidence for points 1-3 automatically. Your implementation adds point 4 through proper logging.
Building Audit Trails into MCP Servers
Every MCP server handling trade operations should log:
class AuditLogger:
async def log_tool_invocation(
self,
tool_name: str,
parameters: dict,
user_id: str,
consent_timestamp: datetime,
result: ToolResult,
execution_time_ms: int
):
await self.store.insert({
"event_type": "tool_invocation",
"tool": tool_name,
"parameters": self.sanitize_sensitive(parameters),
"user": user_id,
"consent_at": consent_timestamp.isoformat(),
"success": result.success,
"result_summary": self.summarize_result(result),
"execution_ms": execution_time_ms,
"server_version": self.version,
"timestamp": datetime.utcnow().isoformat()
})
Sanitize sensitive data (pricing, customer details) while retaining enough information for audit purposes. Store logs in append-only storage with integrity verification.
Handling Sensitive Trade Data
MCP servers processing trade data handle sensitive information:
- Commercial invoice values and pricing
- Customer and supplier identities
- Trade patterns that reveal business strategy
- Banking and payment details
Security considerations:
- Transport encryption: Use TLS for HTTP+SSE transport in production
- Authentication: Implement proper auth before exposing MCP endpoints
- Data minimization: Resources should return only what agents need
- Access logging: Track which agents access which resources
- Retention policies: Define how long to keep detailed logs
Production Deployment Patterns
Transport Selection: stdio vs HTTP+SSE
MCP supports two transports:
stdio — Server runs as a subprocess, communicating through standard input/output. Best for:
- Local development and testing
- Single-user desktop applications (Claude Desktop)
- Scenarios where the agent and server run on the same machine
HTTP+SSE — Server exposes HTTP endpoints with Server-Sent Events for streaming. Best for:
- Production multi-tenant deployments
- Servers that need to scale independently
- Scenarios requiring load balancing and failover
For trade operations, production deployments typically use HTTP+SSE. Your customs MCP server runs as a service, handling requests from multiple agents across your organization.
Scaling MCP Servers for High-Volume Trade
Trade operations have specific scaling challenges:
Rate-limited customs APIs: Many Single Window systems impose strict rate limits. Your MCP server needs:
- Request queuing with priority handling
- Caching for read-only resources (HS codes, duty rates)
- Circuit breakers to prevent cascade failures
Connection pooling: Maintain persistent connections to underlying systems rather than connecting per-request.
Geographic distribution: For multi-country operations, deploy MCP servers close to the customs systems they wrap. Latency matters when you're racing to file before cutoff times.
class RateLimitedClient:
def __init__(self, rate_limit: int, window_seconds: int):
self.semaphore = asyncio.Semaphore(rate_limit)
self.window = window_seconds
async def call(self, request):
async with self.semaphore:
result = await self._execute(request)
await asyncio.sleep(self.window / self.rate_limit)
return result
Monitoring and Observability
Track these metrics for trade MCP servers:
- Latency by tool: How long does declaration submission take? HS lookup?
- Error rates by destination country: Which customs systems are failing?
- API quota consumption: Are you approaching rate limits?
- Consent-to-execution time: How long do users take to approve actions?
- Cache hit rates: Are HS code lookups hitting cache?
Set alerts for:
- Error rate spikes (customs system outage?)
- Latency increases (API degradation?)
- Quota approaching limits (need to throttle?)
Getting Started: Your First Trade MCP Server
Choosing Your First Integration Target
Start with read-only resources before building tools that execute actions:
Good first projects:
- HS code classification resource (read-only, high value)
- Shipment tracking resource (read-only, immediate utility)
- Duty rate calculator resource (read-only, complex logic)
Save for later:
- Declaration submission tools (requires careful consent handling)
- Payment trigger tools (requires bank integration)
- Multi-country orchestration (requires multiple server implementations)
Development Environment Setup
The official MCP SDK provides TypeScript and Python implementations. For trade operations, Python often makes sense given the data processing involved.
# Install MCP SDK
pip install mcp
# Clone reference implementations
git clone https://github.com/modelcontextprotocol/servers
# Create your trade server
mkdir trade-mcp-server
cd trade-mcp-server
Structure your server:
trade-mcp-server/
├── server.py # MCP server implementation
├── resources/ # Resource handlers
│ ├── hs_codes.py
│ └── duty_rates.py
├── tools/ # Tool handlers
│ └── declarations.py
├── clients/ # External API clients
│ ├── ace_client.py
│ └── eucdm_client.py
└── tests/
Testing with Claude Desktop
Claude Desktop includes native MCP support, making it ideal for testing trade servers during development.
Configure your server in Claude's settings:
{
"mcpServers": {
"trade-customs": {
"command": "python",
"args": ["/path/to/trade-mcp-server/server.py"],
"env": {
"CUSTOMS_API_KEY": "your-key"
}
}
}
}
Now you can interact with your trade server through Claude:
"Look up the HS code for laptop computers and show me the duty rates for importing to the US from Taiwan."
Claude will call your HS classification resource and return structured results. You can iterate on resource design, test error handling, and refine the data format before deploying to production.
For the broader context of how MCP fits into autonomous trade systems, see our overview of agentic commerce fundamentals and the AI-powered agentic commerce pillar.
The OECD estimates digital trade facilitation can reduce trade costs by 10-15% for SMEs. MCP servers that connect AI agents to trade systems are infrastructure for capturing those gains. Start with a single resource, prove the pattern works, then expand to tools and multi-server orchestration.
The protocol is new. The trade-specific implementations are sparse. That's the opportunity: build the MCP servers your operations need, and you're ahead of competitors still maintaining point-to-point integrations.