Metadata-Version: 2.4
Name: mcp-midtrans
Version: 2.0.0
Summary: MCP Server for Midtrans Payment Gateway Documentation - Helps AI agents understand and implement Midtrans integration
Project-URL: Homepage, https://github.com/rissets/mcp-midtrans
Project-URL: Repository, https://github.com/rissets/mcp-midtrans
Project-URL: Issues, https://github.com/rissets/mcp-midtrans/issues
Author-email: rissets <danangharissetiawan@gmail.com>
License: MIT
Keywords: ai-agent,documentation,mcp,midtrans,model-context-protocol,payment-gateway
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.11
Requires-Dist: mcp[cli]>=1.2.0
Requires-Dist: pydantic>=2.0.0
Description-Content-Type: text/markdown

# 🏦 MCP Midtrans Documentation Server

> A comprehensive Model Context Protocol (MCP) server that gives AI agents complete knowledge of the Midtrans payment gateway — APIs, payment methods, integration guides, code examples, and best practices.

---

## Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [How It Works](#how-it-works)
- [Available MCP Tools](#available-mcp-tools)
- [Getting Started](#getting-started)
  - [Prerequisites](#prerequisites)
  - [Installation](#installation)
  - [Running with uvx](#running-with-uvx)
  - [Running with Docker](#running-with-docker)
  - [Running with pip](#running-with-pip)
- [Editor & Agent Setup](#editor--agent-setup)
  - [VS Code + GitHub Copilot](#vs-code--github-copilot)
  - [Claude Code (CLI)](#claude-code-cli)
  - [Claude Desktop](#claude-desktop)
  - [Cursor](#cursor)
- [Development Guide](#development-guide)
  - [Project Structure](#project-structure)
  - [Local Development](#local-development)
  - [Adding New Tools](#adding-new-tools)
  - [Adding Documentation Content](#adding-documentation-content)
  - [Testing](#testing)
- [Production Deployment](#production-deployment)
  - [Docker Production Build](#docker-production-build)
  - [Publishing to PyPI](#publishing-to-pypi)
  - [CI/CD](#cicd)
- [Coverage & Content](#coverage--content)
- [Diagrams](#diagrams)
- [License](#license)

---

## Overview

**MCP Midtrans** is an MCP server that embeds the entire Midtrans payment gateway documentation as structured, searchable tools. When connected to an AI agent (Copilot, Claude, Cursor, etc.), the agent can:

- Look up any Midtrans API endpoint, request format, or response schema
- Get complete integration code for **15+ payment methods** in **5 programming languages** (Python, Django, Node.js, Go, PHP)
- Generate ready-to-use charge request JSON for any payment type
- Get webhook/notification handler code with signature verification
- Search across all documentation to find exactly what's needed

**No API keys required** — this server provides documentation only; it does not call the Midtrans API.

---

## Architecture

```mermaid
%%{init: {'theme': 'dark', 'themeVariables': {'primaryColor': '#1a1a2e', 'primaryTextColor': '#e0e0e0', 'primaryBorderColor': '#6c63ff', 'lineColor': '#6c63ff', 'secondaryColor': '#16213e', 'tertiaryColor': '#0f3460', 'fontSize': '14px'}}}%%
graph TB
    subgraph CLIENT["🖥️ AI Client"]
        style CLIENT fill:#1a1a2e,stroke:#6c63ff,stroke-width:2px,color:#e0e0e0
        VSCODE["VS Code + Copilot"]
        CLAUDE_CODE["Claude Code"]
        CLAUDE_DESKTOP["Claude Desktop"]
        CURSOR["Cursor"]
    end

    subgraph MCP_SERVER["⚡ MCP Midtrans Server"]
        style MCP_SERVER fill:#0f3460,stroke:#6c63ff,stroke-width:2px,color:#e0e0e0
        FASTMCP["FastMCP Runtime<br/>(stdio transport)"]

        subgraph TOOLS["🔧 MCP Tools (10)"]
            style TOOLS fill:#16213e,stroke:#00d2ff,stroke-width:1px,color:#e0e0e0
            T1["get_documentation_map"]
            T2["get_documentation"]
            T3["get_payment_method_guide"]
            T4["get_json_object_schema"]
            T5["get_status_codes"]
            T6["get_code_example"]
            T7["search_documentation"]
            T8["get_charge_example"]
            T9["get_notification_handler"]
            T10["get_snap_integration"]
        end

        subgraph KB["📚 Knowledge Base"]
            style KB fill:#16213e,stroke:#ff6b6b,stroke-width:1px,color:#e0e0e0
            D1["API Reference"]
            D2["Payment Methods 15+"]
            D3["Code Examples 5 langs"]
            D4["JSON Schemas 14"]
            D5["Webhook Guides"]
            D6["Status Codes"]
        end
    end

    VSCODE -->|"stdio"| FASTMCP
    CLAUDE_CODE -->|"stdio"| FASTMCP
    CLAUDE_DESKTOP -->|"stdio"| FASTMCP
    CURSOR -->|"stdio"| FASTMCP
    FASTMCP --> TOOLS
    TOOLS --> KB
```

---

## How It Works

```mermaid
%%{init: {'theme': 'dark', 'themeVariables': {'primaryColor': '#1a1a2e', 'primaryTextColor': '#e0e0e0', 'primaryBorderColor': '#6c63ff', 'lineColor': '#00d2ff', 'secondaryColor': '#16213e', 'tertiaryColor': '#0f3460', 'fontSize': '14px'}}}%%
sequenceDiagram
    box rgb(26,26,46) AI Client
        participant User
        participant Agent as AI Agent
    end
    box rgb(15,52,96) MCP Server
        participant MCP as FastMCP Server
        participant Tool as MCP Tool
        participant KB as Knowledge Base
    end

    User->>Agent: "How do I integrate GoPay in Django?"
    Agent->>MCP: tools/call midtrans_get_payment_method_guide<br/>payment_method = gopay
    MCP->>Tool: Route to handler
    Tool->>KB: PAYMENT_METHOD_DETAILS gopay
    KB-->>Tool: Complete GoPay guide
    Tool-->>MCP: Formatted response
    MCP-->>Agent: GoPay charge example, response format, flow
    Agent->>MCP: tools/call midtrans_get_code_example<br/>language = django
    MCP->>Tool: Route to handler
    Tool->>KB: IMPLEMENTATION_EXAMPLES django
    KB-->>Tool: Django integration code
    Tool-->>MCP: Models, views, service layer, DRF code
    MCP-->>Agent: Complete Django implementation
    Agent-->>User: Here is how to integrate GoPay in Django...
```

1. **You ask** your AI agent to integrate Midtrans into your app.
2. **The agent calls** MCP tools to retrieve relevant documentation.
3. **MCP server** returns structured Midtrans documentation, code examples, and schemas.
4. **The agent generates** accurate integration code based on official docs.

---

## Available MCP Tools

| Tool | Description | Key Inputs |
|------|-------------|------------|
| `midtrans_get_documentation_map` | Complete documentation index — start here | — |
| `midtrans_get_documentation` | Detailed docs for a specific topic | `topic`: overview, authorization, snap, charge, notification, etc. (15 topics) |
| `midtrans_get_payment_method_guide` | Integration guide per payment method | `payment_method`: credit_card, gopay, qris, bca_va, etc. (15 methods) |
| `midtrans_get_json_object_schema` | JSON object field-level schema | `object_type`: transaction_details, customer_details, etc. (14 types) |
| `midtrans_get_status_codes` | HTTP status code reference | `code_range`: 2xx, 3xx, 4xx, 5xx |
| `midtrans_get_code_example` | Full implementation examples | `language`: python, django, nodejs, go, php |
| `midtrans_search_documentation` | Full-text search across all docs | `query`: any search term |
| `midtrans_get_charge_example` | Generate charge request JSON | `payment_method` + optional flags |
| `midtrans_get_notification_handler` | Webhook handler code | `language`: python, nodejs, go, php |
| `midtrans_get_snap_integration` | Complete Snap backend + frontend guide | `language`: python, django, nodejs, go, php |

---

## Getting Started

### Prerequisites

- **Python 3.11+**
- One of: [uv](https://docs.astral.sh/uv/) (recommended), [Docker](https://www.docker.com/), or pip

### Installation

```bash
git clone https://github.com/your-org/mcp-midtrans.git
cd mcp-midtrans
```

### Running with uvx

The fastest way — no install needed:

```bash
# Run directly from PyPI
uvx mcp-midtrans
```

Or install as a global tool:

```bash
uv tool install mcp-midtrans
mcp-midtrans
```

### Running with Docker

```bash
# Build the image
docker build -t mcp-midtrans .

# Run with stdio transport
docker run -i --rm mcp-midtrans
```

Or with Docker Compose:

```bash
docker compose up --build
```

### Running with pip

```bash
pip install mcp-midtrans
mcp-midtrans
```

---

## Editor & Agent Setup

### VS Code + GitHub Copilot

Create or update `.vscode/mcp.json` in your **workspace root**:

**Using uvx (recommended):**

```json
{
  "servers": {
    "midtrans": {
      "type": "stdio",
      "command": "uvx",
      "args": ["mcp-midtrans"]
    }
  }
}
```

**Using Docker:**

```json
{
  "servers": {
    "midtrans": {
      "type": "stdio",
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-midtrans"]
    }
  }
}
```

**How to use:**

1. Open VS Code with the workspace containing `.vscode/mcp.json`.
2. Open Copilot Chat (`Ctrl+Shift+I` / `Cmd+Shift+I`).
3. Switch to **Agent** mode (not Chat or Edit mode).
4. The MCP tools appear automatically — ask about Midtrans and Copilot calls the tools.
5. Example prompts:
   - *"Help me integrate GoPay payment in my Django app"*
   - *"Show me how to handle Midtrans webhooks in Express"*
   - *"What's the charge request format for BCA Virtual Account?"*

### Claude Code (CLI)

Add to your project's `.mcp.json` (project root) or `~/.claude/mcp.json` (global):

**Using uvx:**

```json
{
  "mcpServers": {
    "midtrans": {
      "command": "uvx",
      "args": ["mcp-midtrans"]
    }
  }
}
```

**Using Docker:**

```json
{
  "mcpServers": {
    "midtrans": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-midtrans"]
    }
  }
}
```

**How to use:**

1. Start Claude Code: `claude`
2. The MCP server connects automatically on startup.
3. Verify with: `/mcp` — you should see `midtrans` listed with 10 tools.
4. Ask about Midtrans — Claude will use the tools automatically:
   - *"Integrate Midtrans Snap checkout into my FastAPI app"*
   - *"Generate a BNI VA charge request with customer details"*
   - *"How do I verify Midtrans webhook signatures in Go?"*

### Claude Desktop

Edit the config file:

- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "midtrans": {
      "command": "uvx",
      "args": ["mcp-midtrans"]
    }
  }
}
```

Restart Claude Desktop after saving. The 🔧 icon should show the Midtrans tools.

### Cursor

Create `.cursor/mcp.json` in your workspace root:

```json
{
  "mcpServers": {
    "midtrans": {
      "command": "uvx",
      "args": ["mcp-midtrans"]
    }
  }
}
```

Open Cursor Settings → Features → MCP to verify the server is active.

---

## Development Guide

### Project Structure

```
mcp-midtrans/
├── src/
│   └── mcp_midtrans/
│       ├── __init__.py               # Package version
│       ├── server.py                 # MCP server, tool definitions, input models
│       ├── knowledge_base.py         # All Midtrans documentation (~3500 lines)
│       └── tools/
│           └── __init__.py
├── docs/
│   └── DIAGRAMS.md                   # Mermaid architecture & workflow diagrams
├── pyproject.toml                    # Build config, dependencies, entry point
├── Dockerfile                        # Docker image (Python 3.12 + uv)
├── docker-compose.yml                # Docker Compose config
├── .vscode/
│   └── mcp.json                      # VS Code MCP config (local dev)
├── .gitignore
└── README.md                         # This file
```

### Key Files

| File | Purpose |
|------|---------|
| `server.py` | FastMCP server initialization, 10 tool handlers, Pydantic input models, enums |
| `knowledge_base.py` | Complete embedded Midtrans docs — all API refs, 15 payment methods, 5 language examples, 14 JSON schemas |
| `pyproject.toml` | Project metadata, deps (`mcp[cli]>=1.2.0`, `pydantic>=2.0.0`), hatchling build, entry point |

### Local Development

```bash
# Clone and set up
git clone https://github.com/your-org/mcp-midtrans.git
cd mcp-midtrans

# Create virtual environment with uv
uv venv
source .venv/bin/activate

# Install in editable mode
uv pip install -e .

# Run the server
mcp-midtrans

# Test with MCP Inspector (interactive tool testing)
npx @modelcontextprotocol/inspector mcp-midtrans
```

**MCP Inspector** opens a web UI where you can:
- See all registered tools and their input schemas
- Send test requests with custom parameters
- View formatted responses in real-time

### Adding New Tools

1. **Define input model** in `server.py`:

```python
class GetMyNewGuideInput(BaseModel):
    model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")
    topic: str = Field(..., description="The topic to look up")
```

2. **Add documentation** to `knowledge_base.py`:

```python
MY_NEW_GUIDE = """
# My New Documentation Section
...
"""
```

3. **Register the tool** in `server.py`:

```python
@mcp.tool(
    name="midtrans_get_my_new_guide",
    annotations={"readOnlyHint": True, "destructiveHint": False, "idempotentHint": True},
)
async def midtrans_get_my_new_guide(params: GetMyNewGuideInput) -> str:
    """Description of what this tool returns."""
    return MY_NEW_GUIDE
```

4. **Import** the new constant in the server's import block.

### Adding Documentation Content

All documentation lives in `knowledge_base.py` as Python string constants and dicts:

| Variable | Type | Content |
|----------|------|---------|
| `MIDTRANS_OVERVIEW` | `str` | Products, environments, auth intro |
| `AUTHORIZATION_GUIDE` | `str` | Auth setup with code examples |
| `API_ENDPOINTS` | `str` | Complete endpoint reference table |
| `PAYMENT_METHOD_DETAILS` | `dict` | 15 payment method guides (key = method name) |
| `JSON_OBJECT_SCHEMAS` | `dict` | 14 JSON schema references (key = object type) |
| `IMPLEMENTATION_EXAMPLES` | `dict` | 5 language examples (keys: python, django, nodejs, go, php) |
| `STATUS_CODES` | `dict` | Status code tables (key = range like "2xx") |

To add content, append to the relevant constant or add a new entry to the dict.

### Testing

```bash
# Syntax check
python -m py_compile src/mcp_midtrans/server.py
python -m py_compile src/mcp_midtrans/knowledge_base.py

# Verify tools register correctly
python -c "
from mcp_midtrans.server import mcp
tools = [t.name for t in mcp._tool_manager._tools.values()]
print(f'{len(tools)} tools registered:')
for t in tools:
    print(f'  - {t}')
"

# Verify languages
python -c "
from mcp_midtrans.knowledge_base import IMPLEMENTATION_EXAMPLES
print('Languages:', list(IMPLEMENTATION_EXAMPLES.keys()))
"

# Interactive testing
npx @modelcontextprotocol/inspector mcp-midtrans
```

---

## Production Deployment

### Docker Production Build

```bash
# Build with tag
docker build -t mcp-midtrans:latest .

# Tag for registry
docker tag mcp-midtrans:latest ghcr.io/your-org/mcp-midtrans:latest

# Push to container registry
docker push ghcr.io/your-org/mcp-midtrans:latest
```

Then users configure their MCP clients with Docker:

```json
{
  "mcpServers": {
    "midtrans": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "ghcr.io/your-org/mcp-midtrans:latest"]
    }
  }
}
```

### Publishing to PyPI

```bash
# Build distribution
uv build

# Upload to PyPI
uv publish
# or: twine upload dist/*
```

After publishing, users can run directly without cloning:

```bash
uvx mcp-midtrans
```

### CI/CD

Example GitHub Actions workflow (`.github/workflows/ci.yml`):

```yaml
name: Build & Test

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v4
      - run: uv venv && source .venv/bin/activate && uv pip install -e .
      - run: |
          source .venv/bin/activate
          python -m py_compile src/mcp_midtrans/server.py
          python -m py_compile src/mcp_midtrans/knowledge_base.py
          python -c "from mcp_midtrans.server import mcp; assert len(list(mcp._tool_manager._tools)) == 10"

  docker:
    runs-on: ubuntu-latest
    needs: test
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t mcp-midtrans .
```

---

## Coverage & Content

### Documentation Topics (15)

| Topic | Covers |
|-------|--------|
| Overview | Products, environments, auth, key concepts |
| Authorization | API keys, Basic Auth, code in 5 languages |
| HTTP Request | Base URLs, headers, idempotency |
| API Endpoints | Full endpoint table (Payment, Card, GoPay, Subscription, Snap, PayLink, Invoice) |
| Snap | Backend + frontend integration, Snap.js, redirect flow |
| Charge | Core API charge with all features |
| Payment Methods | Complete list with types and categories |
| Notification | Webhooks, signature verification, status mapping |
| Transaction Mgmt | Get status, cancel, expire, refund, capture |
| Subscription | Create / get / update / enable / disable / cancel |
| Payment Link | Create / get / delete |
| Invoicing | Create / get / void |
| Merchant Balance | Balance mutation API |
| Testing | Sandbox credentials, test cards, simulation |
| Status Codes | 2xx, 3xx, 4xx, 5xx with troubleshooting |

### Payment Methods (15)

Credit Card · GoPay · QRIS · ShopeePay · OVO · BCA VA · BNI VA · BRI VA · Permata VA · CIMB VA · Mandiri Bill · Indomaret · Alfamart · Akulaku · Kredivo

### Code Examples (5 Languages)

| Language | Includes |
|----------|----------|
| **Python** | Flask, FastAPI, midtransclient library, manual HTTP client |
| **Django** | Models, views (FBV), DRF serializers + ViewSets, service layer, Snap template, management commands |
| **Node.js** | Express, midtrans-client library |
| **Go** | net/http, manual integration |
| **PHP** | Native, midtrans-php library |

### JSON Object Schemas (14)

transaction_details · customer_details · item_details · seller_details · custom_expiry · credit_card · gopay · shopeepay · bank_transfer · echannel · qris · ovo · convenience_store · action

---

## Diagrams

Full architecture and workflow diagrams with dark theme styling are in [`docs/DIAGRAMS.md`](docs/DIAGRAMS.md):

1. **System Architecture** — How AI clients connect to the MCP server
2. **Tool Request Flow** — Sequence diagram of a typical interaction
3. **Payment Integration Flow** — What the MCP teaches about Midtrans Snap integration
4. **Knowledge Base Structure** — Mind map of all documentation content
5. **Deployment Options** — Docker and uvx deployment flows
6. **Tool Coverage Map** — How the 10 tools map to documentation areas

---

## License

MIT
