SW RDC
# SW RDC — Revenue Data Connector (`@schema-weaver/rdc`)
**SW RDC (Revenue Data Connector)** — Read-only, zero-storage revenue data connector and MCP engine for Razorpay, Stripe, Cashfree, and billing APIs.
v1 implements **Razorpay** as the first provider. The catalog, executor, auth, redaction, and telemetry layers are provider-agnostic so additional revenue sources can be added without changing the MCP/CLI surface.
**Repository:** https://github.com/Schema-Weaver/sw-rdc
> **Placement:** This is an independent package/repository, like Schema Weaver's `sw-agent`, `pg-ddl-parser`, and `migration-engine`. It can be consumed in-process by the backend, run as a hosted MCP server, or published as an npm/CLI package. OAuth token storage, encryption, and Supabase persistence stay in the Schema Weaver SaaS backend; **nothing in `src/` imports a database, `.env`, or Express**.
---
## Exact repository metadata
| Field | Value |
| --- | --- |
| Repository name | `sw-rdc` |
| Description | Revenue Data Connector (SW RDC) — Read-only, zero-storage revenue data connector and MCP engine for Razorpay, Stripe, Cashfree, and billing APIs. |
| Display name | SW RDC |
| Subtitle | Revenue Data Connector |
| npm package | `@schema-weaver/rdc` |
| CLI binary | `sw-rdc` |
---
## Install & Requirements
```bash
npm install @schema-weaver/rdc
```
- Node.js `>= 18` (uses built-in `fetch`, `AbortController`, and `URL`)
- ESM (`import`), CJS (`require`), and `.d.ts` type declarations included
- Runtime dependencies: `@modelcontextprotocol/sdk`, `zod`
From a source checkout:
```bash
cd sw-rdc
npm install
npm run typecheck
npm test
npm run build
```
`npm test` currently runs **75 tests across 9 files**; `npm run build` emits ESM, CJS, source maps, and declarations into `dist/`.
---
## Quick Start
### 1. Programmatic execution
```ts
import { executeRazorpayTool } from '@schema-weaver/rdc';
const result = await executeRazorpayTool({
toolName: 'fetch_all_payments',
args: { from: 'last_7_days', count: 25, status: 'captured' },
auth: {
type: 'oauth', // Razorpay Partner OAuth token
accessToken: decryptedAccessToken,
accountId: connectionId,
// Optional: called at most once on HTTP 401
onTokenExpired: async () => refreshAndPersistToken(connectionId),
},
caller: 'resona_ai',
onExecutionEvent: async (span) => auditSink.write(span),
});
console.log(result.items, result.meta);
```
Standalone API-key auth also works:
```ts
auth: {
type: 'api_key',
keyId: process.env.RAZORPAY_KEY_ID!,
keySecret: process.env.RAZORPAY_KEY_SECRET!,
}
```
### 2. Reusable connector
```ts
import { createRazorpayConnector } from '@schema-weaver/rdc';
const payments = createRazorpayConnector({ auth, caller: 'dashboard_gen' });
const tools = payments.listTools(); // 33 Razorpay v1 tool metadata objects
const result = await payments.execute('fetch_payment', { payment_id: 'pay_ABC123' });
```
### 3. MCP server (stdio)
```ts
import { runMcpStdioServer } from '@schema-weaver/rdc/mcp';
await runMcpStdioServer({
// Called once per tools/call: ideal for hosted multi-tenant deployments.
auth: async () => loadTenantAuthFromRequestContext(),
});
```
### 4. CLI
```bash
# Print the read-only catalog
sw-rdc list-tools
# Run one tool
RAZORPAY_KEY_ID=rzp_test_xxx RAZORPAY_KEY_SECRET=yyy \
sw-rdc call fetch_all_payments '{"count":5,"status":"captured"}'
# Start a stdio MCP server for an MCP client
sw-rdc serve --access-token "$RAZORPAY_ACCESS_TOKEN"
```
---
## What Is Included
- **33 read-only Razorpay tools** — 32 `fetch_*` REST lookups plus `summarize_razorpay_resource`. No capture, refund creation, updates, or any other mutating tool exists.
- **Provider-ready architecture** — v1 ships Razorpay; the registry and result envelope are designed for Stripe, Cashfree, and billing APIs.
- **Dynamic auth per execution** — OAuth Bearer with a single 401 refresh retry, or API-key Basic auth for standalone/npm use. Credentials are never logged.
- **Zero-retention analytics** — the summarizer streams pages through a `Map` accumulator, drops each page immediately, and returns only buckets/totals. `maxPages` defaults to 20 and is hard-capped at 50.
- **Pagination that respects Razorpay** — `count`/`skip`, Unix-second windows, relative presets, deep-skip window bisection by timestamp cursor, settlement-recon day iteration, and 429 exponential backoff with jitter honoring `Retry-After`.
- **PII-safe by default** — emails/contacts become `*_masked` companions; card tokens, fingerprints, full card numbers, bank accounts, OTPs, and secret-looking fields are stripped. `includeUnmaskedPii: true` is a trusted server-only opt-out for email/contact only.
- **Integer minor units** — raw amounts stay in minor units (paise for INR); `amount_major`/`sum:amount_major` companions are added for display. Currency-specific exponents (JPY, KWD, BHD, …) are supported.
- **Audit spans in `finally`** — every success, validation failure, auth failure, and rate limit emits a sanitized `ConnectorExecutionSpan` via `onExecutionEvent`. A broken logger never breaks a query.
- **Strict allow-listed inputs** — Zod strict schemas reject unknown keys and raw URLs; paths are fixed in the catalog with an SSRF/traversal guard in the HTTP client.
### Result envelope
```ts
{
ok: true,
provider: 'razorpay',
tool: 'fetch_all_payments',
count: 5,
hasMore: true,
nextSkip: 5,
currencyDefault: 'INR',
amountUnit: 'minor (paise: divide by 100 for INR)',
items: [ /* sanitized records */ ],
meta: {
apiCalls: 1,
scannedCount: 5,
appliedWindow: { from: 1760774400, to: 1760860799 },
appliedPeriod: null,
warnings: [],
},
}
```
Errors are `ConnectorError` instances with stable codes such as `INVALID_ARGS`, `AUTH_EXPIRED`, `PERMISSION`, `NOT_FOUND`, `RATE_LIMITED`, `UPSTREAM_ERROR`, `NETWORK_ERROR`, `ABORTED`, and `UNSUPPORTED`; `toJSON()` is safe to return to a caller.
---
## Streaming Analytics Example
```ts
await executeRazorpayTool({
toolName: 'summarize_razorpay_resource',
args: {
resource: 'payments',
from: 'last_30_days',
group_by: ['method', 'status'],
time_bucket: 'day',
metrics: ['count', 'sum:amount', 'avg:amount', 'max:amount', 'sum:fee'],
where: { currency: 'INR' },
maxPages: 20,
},
auth,
});
```
Returns grouped buckets plus `meta.totals`, `meta.scannedCount`, `meta.matchedCount`, `meta.truncated`, and the applied window. Use `resource: 'settlement_recon'` with `year`/`month` (and optional `day`) for reconciliation reports.
---
## Documentation
- [Architecture & Implementation Spec](./docs/ARCHITECTURE_AND_AGENT_SPEC.md) — provider boundary, interfaces, guardrails, acceptance criteria
- [Razorpay Read-Only Tool Catalog](./docs/RAZORPAY_MCP_TOOL_CATALOG.md) — exact 33-tool specification and query rules
- [Schema Weaver Integration Contract](./docs/SCHEMA_WEAVER_INTEGRATION_CONTRACT.md) — backend, `backend-ai`, and dashboard integration
- [Implementation Notes](./docs/IMPLEMENTATION.md) — what was built, file map, design decisions, known limits
- [Tools & Resources](./docs/TOOLS_AND_RESOURCES.md) — every tool, API path, and result semantics
- [MCP Server & CLI](./docs/MCP_AND_CLI.md) — stdio setup, dynamic auth, commands, config examples
- [Official Server Reference & Learnings](./docs/OFFICIAL_MCP_REFERENCE.md) — what was mirrored from Razorpay's Go server and what was intentionally changed
- [Repository Setup](./docs/REPOSITORY_SETUP.md) — GitHub repo name, description, package identity, and publish checklist
---
## Attribution
Tool naming and query semantics follow Razorpay's MIT-licensed [`razorpay-mcp-server`](https://github.com/razorpay/razorpay-mcp-server). This package is an independent TypeScript implementation for Schema Weaver and is not affiliated with or endorsed by Razorpay. See [LICENSE](./LICENSE).
TDQS
Scored across 33 tools
Most tools target distinct Razorpay resources, but several refund/payment/settlement tools overlap in practice: fetch_refund, fetch_all_refunds, fetch_multiple_refunds_for_payment, and fetch_specific_refund_for_payment are easy to confuse. Descriptions generally clarify the differences, but an agent must carefully choose between general and scoped list/get variants.
All names are snake_case and use a fetch_ prefix, but the patterns vary: fetch_all_X, fetch_X, fetch_Xs_for_Y, fetch_X_with_id, and fetch_X_by_id. The conventions are readable but not fully predictable, especially across list/get and scoped-list tools.
The 33 tools cover many Razorpay resources, so the breadth is somewhat justified, but the surface is heavy and includes numerous paired list/get and scoped-list endpoints. It is broader than a typical well-scoped tool set and could likely be consolidated without losing coverage.
The surface provides broad read-only coverage across payments, orders, refunds, settlements, payouts, subscriptions, invoices, disputes, customers, QR codes, and payment links. Minor read gaps exist, but the main lifecycle for a read-only Razorpay connector is well covered.