Skip to main content
Glama
counterdesk-mcp

counterdesk-mcp

by khamidov17
README.md
# Counterdesk

[![CI](https://github.com/khamidov17/counterdesk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/khamidov17/counterdesk/actions/workflows/ci.yml)
<!-- Add after the first npm publish: [![npm](https://img.shields.io/npm/v/counterdesk-mcp)](https://www.npmjs.com/package/counterdesk-mcp) -->
[![scripted scenarios](https://img.shields.io/badge/scripted%20scenarios-30%2F30%20passed-brightgreen)](reports/evaluation.md)
[![real model](https://img.shields.io/badge/real%20model%20(Haiku)-57%2F57%20runs-brightgreen)](reports/evaluation-real-model.md)
[![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)

![A $5 refund in the local demo, from the customer request through tool calls, human approval and the ticket receipt](docs/refund-walkthrough.gif)

- **What:** a TypeScript support agent that looks up orders, edits tickets and requests refunds through MCP tools. A human approves every refund in a separate console, and a crash-recoverable SQLite queue pays it exactly once.
- **Run:** Node.js 24, then `git clone https://github.com/khamidov17/counterdesk && cd counterdesk && npm start` and open http://127.0.0.1:4317. No API key needed.
- **Results:** 30 scripted scenarios pass. A real model (Claude Haiku, 5 prompt-injection cases included) passed 57 of 57 runs after two rounds of fixes, from 48 of 57 at the start ([report](reports/evaluation-real-model.md)). One refund is one OpenTelemetry trace from model call to payment attempt ([Jaeger](#tracing)).

## What happens if the worker dies after payment?

A refund crosses two systems. The payment provider can accept the money movement moments before the local process dies. In the crash test, the replacement worker sends the same approval ID, receives the existing provider receipt and commits one debit and one ticket note. The test checks the provider receipt count, local balance and ticket notes against separate ledgers. Run it with Node 24 from the repo root:

```sh
node --test --test-name-pattern='SIGKILL at after-receipt' tests/refund-worker.test.mjs
```

The lease controls which worker can update the local ledger. The approval ID lets the provider recognize a repeated payment request. If the first attempt is at least 23 hours old and its receipt ID is still unknown, the Stripe adapter uses read-only reconciliation. An ambiguous match keeps the amount reserved for review.

The default 30-second lease gives a slow worker time to finish and makes a replacement wait after a crash. The focused test shortens the lease. With the default settings and a simulated provider, recovery after payment took **30.094 s**. The [benchmark](docs/refund-performance.md) includes raw timings, the recovery cost, and the conditions that would justify moving the queue to PostgreSQL.

## How a refund travels

The agent can propose a refund through MCP. The reviewer authorizes it through a separate HTTP endpoint. After authorization, an independently running worker can finish the refund even if the console goes offline.

```mermaid
sequenceDiagram
    participant R as Reviewer
    participant A as Helpdesk API
    participant D as SQLite
    participant W as Refund worker
    participant P as Payment provider
    R->>A: Approve a specific refund
    A->>D: Commit decision and job together
    A-->>R: 202 Accepted
    W->>D: Claim job with expiring lease
    W->>P: Submit with approval ID
    alt Confirmed receipt and valid lease
        P-->>W: Refund receipt
        W->>D: Commit balance, receipt and ticket note
    else Lost response
        W->>D: Schedule retry if lease is still valid
    end
```

## Real-model evaluation

The same 35 scenarios (the 30 scripted ones plus 5 where the model reads a prompt injection) run with the scripted planner and with a real model that chooses every tool call. Assertions inspect helpdesk state: balances, approvals, notes, deleted accounts. Eleven scenarios consult the model, so they run three times each. The other 24 call the API directly or inject a scripted fault, and pass or fail the same way in both columns.

| | Scripted planner | Real model: Claude Haiku via `claude -p` |
|---|---|---|
| Scenarios passed | 35/35 | 35/35 (every run) |
| Runs passed | 35/35 | 57/57 (100%). Started at 48/57 (84.2%) |
| Of which model-consulted scenarios | 11/11 | 33/33 (100%). Started at 24/33 (72.7%) |
| Adversarial: injection in the customer message, in a `lookup_order` result, a forged "reviewer approved", another ticket's order, a fake administrator | 5/5 | 15/15 runs |
| Tokens (input / output) | simulated | 131,554 / 8,611 over 62 model calls |
| Cost | $0 | $0.017 (as reported by the CLI) |

The first run failed 9 of 33 model-consulted runs. The model asked customers for a "reason" before filing a request, assumed a full $49 refund when no amount was given, and once skipped the order lookup. Those were fixed in the prompt and in the lookup guard, which now returns a recoverable error to the model, and are listed with the other failures in the [full report](reports/evaluation-real-model.md). The prompt was tuned on these same cases, so 100% is not a held-out estimate. The protections the adversarial cases probe sit outside the model: tool schemas, ticket-bound credentials, server-side checks and human approval. Reproduce with `npm run evaluate:model` (needs the `claude` CLI signed in) or `-- --provider anthropic` with `ANTHROPIC_API_KEY`.

## Tracing

An agent turn, its tool calls, the human review and the refund worker's attempts are **one trace** with `service.name=counterdesk`, using the OpenTelemetry GenAI semantic conventions (`chat {model}`, `execute_tool {name}`, `gen_ai.usage.*`, finish reasons). The W3C `traceparent` crosses the MCP stdio hop and the helpdesk HTTP calls, and is stored with the approval so a refund approved later joins the same trace. The local trace explorer is fed by the same SDK.

```sh
docker compose up -d                                              # OpenTelemetry Collector -> Jaeger
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 npm start       # then open http://localhost:16686
```

![A real claude-cli refund request in Jaeger: 14 spans from model calls to the refund attempt, with the turn's 4,249 input and 251 output tokens and $0.00042 cost](docs/jaeger-trace.png)

The screenshot is a real run of the `claude-cli` provider: the request, the reviewer's approval and the worker's refund attempt. The root span carries the turn totals and each `chat` span its own usage and cost. Details are in [docs/tracing.md](docs/tracing.md).

## Run the demo

Install Node.js 24 or newer, then:

```sh
git clone https://github.com/khamidov17/counterdesk.git
cd counterdesk
npm start
```

Open **http://127.0.0.1:4317**. The demo uses Node's built-in SQLite and a scripted planner, so the app and MCP server run without installing a model or supplying credentials.

1. Send **“What's the status of O-1001?”** on ticket T-1001. The seeded order totals $49.
2. Send **“Please refund $12 on O-1001.”** Open **Approvals** and inspect the amount and reason. The proposed action has not yet moved money.
3. Approve the request. The worker settles it and adds a receipt to the ticket. Look at the new note, then open **Trace explorer** to inspect the agent turn, the human review and the worker attempt in one trace.
4. Try **“Please add a note that the replacement arrived”** or **“Delete my account.”** Account deletion deactivates the local customer record. Transaction and review records remain available for audit.

To use a real model, set `AGENT_PROVIDER` as described below. `AGENT_PROVIDER=claude-cli` runs the local `claude` CLI with no API key.

## Use the MCP server from any client

```sh
npx -y counterdesk-mcp   # stdio server, needs HELPDESK_BASE_URL, HELPDESK_TICKET_ID and HELPDESK_AGENT_TOKEN
```

The package is `counterdesk-mcp` (publishing is pending, see the [client guide](packages/mcp/README.md) for the config snippet and the verified GitHub release archive).

## Configure integrations

Copy `.env.example` to `.env`. The server reads it on startup. Use a separate data directory for each payment fixture.

| Setting | Purpose |
|---|---|
| `AGENT_PROVIDER` | `demo` (scripted, default), `openai`, `anthropic` or `claude-cli`. |
| `OPENAI_API_KEY`, `OPENAI_MODEL` | OpenAI Chat Completions tool calling. |
| `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL` | Anthropic Messages API with native tool use, through the official SDK. Default model `claude-haiku-4-5`. |
| `CLAUDE_CLI_MODEL` | Model alias for `claude-cli` (default `haiku`). The provider runs `claude -p` with its tools, MCP servers, settings and session storage disabled, puts the tool schema in the prompt and parses a strict JSON reply. |
| `INPUT_USD_PER_MILLION`, `OUTPUT_USD_PER_MILLION` | Token rates for models without built-in rates. Costs are estimates using these rates. `claude-cli` reports its own cost. |
| `CONVERSATION_BUDGET_USD` | Cumulative budget per ticket conversation, persisted across restarts. Default $0.10. A reviewer can top up or reset it from the console. |
| `REVIEWER_TOKEN` | Private reviewer credential, typed into the console. Required for any real provider or Stripe. Only the credential-free demo uses a cookie session instead. The console API never returns the token. |
| `STRIPE_SECRET_KEY`, `STRIPE_PAYMENT_INTENT` | Bind a test payment to the seeded order. The Stripe adapter rejects live keys. |
| `HELPDESK_AGENT_TOKEN` | External MCP credential bound to `HELPDESK_TICKET_ID` (default `T-1001`). Other console tickets receive separate process-local credentials. |
| `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Collector base URL or full traces URL, e.g. `http://localhost:4318`. |
| `REFUND_WORKER_MODE` | Default `embedded`. Use `external` and start one or more workers with `npm run worker` on the same host. |
| `DATA_DIR`, `PORT` | SQLite directory and local listener port. Defaults are `.data` and `4317`. |

The console is designed for a trusted operator on one machine. Ticket selection is an operator control. A customer-facing deployment would need customer authentication, reviewer identity and authorization, and an appropriate retention policy. Use one console process per data directory. Refund workers can share its local database.

## Stripe test mode

The default refund gateway is a local ledger, and every Stripe code path (idempotency keys, pending receipts, 23-hour read-only reconciliation) is covered by tests against a simulated Stripe API. **This repository has not been run against the real Stripe test API by its author, because no test key was available.** The owner can verify it in a minute with a Stripe test-mode key:

```sh
export STRIPE_SECRET_KEY=sk_test_...    # test mode only, live keys are rejected
node scripts/verify-stripe-test.mjs
```

The script creates its own test payment, queues a one-cent refund, and asks Stripe how many refunds exist for that PaymentIntent. It expects zero before approval and one after approval and after a replay, and it prints the real refund ID and counts. See [docs/stripe.md](docs/stripe.md).

## Verify the project

```sh
npm ci
npm ci --prefix packages/mcp
npm run typecheck
npm run lint
npm test
npm run evaluate
```

The [30-scenario report](reports/evaluation.md) and [machine-readable results](reports/evaluation.json) cover customer workflows, attempts to bypass approval or cross ticket boundaries, and broken tools or providers. The package tests use the official MCP SDK as an independent client. The console integration test runs the HTTP server, submits a refund through MCP, reviews it, restarts the server, and checks persisted state. The tracing test checks one trace across the agent, the MCP subprocess, the helpdesk and the worker.

`npm run evaluate:provider -- --demo` rehearses the five-conversation hosted-model check without a paid request. The design choices behind these pieces are in [docs/decisions.md](docs/decisions.md).

## Guides

- [Engineering decisions and module map](docs/decisions.md)
- [MCP tools, inputs and client configuration](packages/mcp/README.md)
- [Stripe sandbox setup and one-cent verification](docs/stripe.md)
- [Runtime, retries and spending limits](docs/agent-runtime.md)
- [Tracing, collector and Jaeger](docs/tracing.md)
- [Worker runbook](docs/refund-operations.md) · [Queue benchmark](docs/refund-performance.md)
- [Versioned GitHub releases and package verification](docs/releasing.md)

MIT licensed. Contributions can be checked locally with the same verification commands used by CI.