Skip to main content
Glama
payment-specialist-agent

payment-specialist-agent

README.md
# Payment Specialist Agent: clinical outsourcing AI (RAG + MCP + Claude)

**Payment Specialist Agent** is an AI agent that reviews CRO and clinical vendor invoices the way a clinical outsourcing
analyst does: it checks each invoice line against the purchase order, SOW budget and rate
card, then **reads the contracts** (MSAs, SOWs, change orders) before deciding what to pay,
what to dispute and why, citing the clause behind every decision.

I built it to learn the three ideas behind most enterprise AI work today, by applying them to
the work I know: **RAG**, **MCP** and **agents**.

> All vendors, studies, contracts and numbers are synthetic. Nothing comes from a real
> company or contract.

---

## The three ideas, in plain language

### 1. RAG (Retrieval-Augmented Generation): "look it up before you answer"

A language model knows a lot about the world, but nothing about *your* contracts. RAG fixes
that in two steps:

1. **Retrieve**: search your own documents and pull out the few passages relevant to the question.
2. **Generate**: give those passages to the model with the question, so it answers from
   your documents, and can quote them, instead of from memory.

It is the same thing an analyst does: before approving an out-of-scope charge, you open the
SOW and the change-order folder. In this project:

| RAG step | File | What it does here |
|---|---|---|
| Documents | `contracts/*.md` | 3 MSAs, 6 SOWs, 4 change orders |
| Chunking | `src/rag.py` `load_chunks()` | Splits each contract into one piece per clause, and keeps the document header (vendor, PO, **signed or draft**) on every piece |
| Indexing + search | `src/rag.py` `ContractIndex` | Ranks the pieces against a question with BM25, a keyword-scoring formula |
| Generation | `src/agent.py` | Claude reads the retrieved clauses and writes the decision with citations |

**Why chunk?** A model reads best when you give it the five relevant clauses, not five hundred pages.
**Why keep the header on each chunk?** A clause that says "adds Biostatistician" means nothing
if you lose the line saying the change order was never signed.

**Keyword search vs embeddings.** BM25 matches words, so a search for "CRA" will not find
"Clinical Research Associate". Production systems add *embeddings*: each chunk becomes a list
of numbers that captures its meaning, stored in a vector database, so "fee" can match "rate".
I kept BM25 because every line of it is readable; swapping in embeddings changes `rag.py` only.

### 2. MCP (Model Context Protocol): "a standard plug for AI tools"

Before MCP, every AI app needed its own custom code to reach each system (ERP, contract
repository, CTMS). MCP is an open standard, like USB-C for AI: you wrap your system **once**
as an MCP server, and any MCP-aware app can use it.

`src/mcp_server.py` is that server. It offers four tools:

| Tool | What it returns |
|---|---|
| `list_flagged_invoices` | Invoice lines that fail a rule (unknown PO, role not in SOW, rate above Schedule A) |
| `check_invoice` | One invoice line with every rule finding |
| `get_purchase_order` | PO, study and SOW roles with budgeted hours |
| `search_contracts` | The RAG search: best-matching contract clauses, with file and section |

The same server works with Payment Specialist Agent, with **Claude Desktop** (see below) or with
any other MCP client, with no code changes. That reuse is the point.

### 3. Agent: "the model decides the next step"

A plain chatbot answers once. An agent works in a loop:

```
   ┌──────────────────────────────────────────────────────────┐
   │  Claude: "INV-1003 is flagged role_not_in_sow.           │
   │           Is there a change order? Let me search."       │
   │        │ calls search_contracts("change order PO-4504…") │
   │        ▼                                                 │
   │  MCP server runs the tool ──► result goes back to Claude │
   │        │                                                 │
   │        ▼                                                 │
   │  Claude: "Executed CO adds the role. Next invoice…"      │
   └──────────── repeats until it has enough to answer ───────┘
```

Nobody wrote "for INV-1003, search for a change order" in the code. Claude chose that step
because the system prompt tells it flags are candidates and the contract decides.

---

## Why rules alone are not enough: the demo story

The rule checks (`src/checks.py`) flag 8 of 50 invoice lines, worth USD 42,543. A rules-only
process would hold all of it. Reading the contracts changes the answer:

| Invoice | Vendor | Amount | Rule flag | What the contracts say | Correct outcome |
|---|---|---|---|---|---|
| INV-1003 | Helix | 9,100 | role not in SOW | Executed **CO-4504-01** added Biostatistician, 120 h at 182/h | **Approve** |
| INV-1015 | Northbridge | 7,336 | rate above card | Executed **CO-4502-01** raised the CRA rate on PO-4502 to 131/h | **Approve** |
| INV-1025 | Helix | 2,223 | rate above card | No change order; MSA 4.1 caps billing at Schedule A (140/h) | **Partial**: pay 1,820, dispute 403 |
| INV-1048 | Northbridge | 5,405 | role not in SOW | CO-4501-01 exists but is a **draft, not signed**; MSA 4.2 says drafts have no effect | **Reject** |
| INV-1006 | Northbridge | 2,645 | unknown PO | MSA 5.1: no valid PO, return unpaid | **Reject** |
| INV-1007, 1019, 1043 | Vantage | 15,834 | unknown PO | MSA 5.1: no valid PO, return unpaid | **Reject** |

So Payment Specialist Agent releases **USD 16,436** that rules would have wrongly held, and backs each of the
remaining disputes with a clause. `CO-4503-01` is a distractor that matches no invoice. The
unsigned draft is the hardest case: a careless reader sees "adds Data Manager" and approves.

This table is my own reading of the synthetic contracts, as the answer key. Compare it with
Payment Specialist Agent's report in `outputs/review_report.md` after you run it.

---

## Run it

Needs Python 3.10 or later. On Windows, use `py` instead of `python` if `python` is not found.

```bash
python -m venv .venv
.venv\Scripts\activate            # Windows   (macOS/Linux: source .venv/bin/activate)
pip install -r requirements.txt
```

**Step 1, no API key, no cost:** watch the MCP and RAG parts work.

```bash
python src/rag.py "change order PO-4501 Data Manager"    # just the search
python src/demo_offline.py INV-1048                       # MCP client + tools, by hand
pytest -q                                                 # 5 tests
```

**Step 2, run Payment Specialist Agent:** needs Claude API access from the Claude Console
(console.anthropic.com), which is billed separately from a claude.ai subscription.

```bash
ant auth login                 # or: set ANTHROPIC_API_KEY=sk-ant-...   (Windows cmd)
python src/agent.py            # reviews all flagged invoices, writes outputs/review_report.md
python src/agent.py "Why was INV-1003 flagged and should we pay it?"
```

You will see each tool call Payment Specialist Agent makes as it happens. A full review is a few dozen tool
calls on Claude Opus 5.5.

**Step 3, plug the MCP server into Claude Desktop** (no code, no API key): open Claude Desktop >
Settings > Developer > Edit Config, and add (use your own path):

```json
{
  "mcpServers": {
    "payment-specialist-agent": {
      "command": "C:\\path\\to\\payment-specialist-agent\\.venv\\Scripts\\python.exe",
      "args": ["C:\\path\\to\\payment-specialist-agent\\src\\mcp_server.py"]
    }
  }
}
```

Restart Claude Desktop, then ask: *"Which flagged Helix invoices should we dispute, and by when?"*
The same four tools now work inside Claude Desktop. That is MCP's reuse in practice.

---

## Project layout

```
contracts/            synthetic MSAs, SOWs, change orders (generated, then read by RAG)
data/                 invoices, POs, SOW lines, rate card (CSV; planted_error is the answer key)
src/generate_data.py      makes the CSVs
src/generate_contracts.py makes the contract documents
src/checks.py         rule-based checks on the structured data
src/rag.py            chunking + BM25 search over the contracts
src/mcp_server.py     the MCP server: four tools
src/agent.py          Payment Specialist Agent: Claude + the MCP tools in an agent loop
src/demo_offline.py   the same tools, called by hand, no API key
tests/test_tools.py   checks the rules and the retrieval
```

## What a real deployment would add

- **Real documents**: PDF contracts parsed into text, with embeddings and a vector database.
- **Real systems behind MCP**: ERP (POs, invoices), the contract repository and CTMS, read-only first.
- **Human in the loop**: Payment Specialist Agent drafts; an analyst approves every dispute before it goes to a vendor.
- **Evaluation**: a labelled set of past invoices to measure how often Payment Specialist Agent's decision matches the analyst's.
- **Audit trail**: log every tool call and cited clause for GxP and SOX review.

## Built with

Claude Opus 5.5 through the Anthropic Python SDK (tool runner and MCP helpers), the official
MCP Python SDK, and pandas. Synthetic data only.