@exactrows/mcp 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -2
- package/bin/exactrows-mcp.mjs +39 -0
- package/bundle/server.mjs +3065 -0
- package/package.json +37 -4
- package/sbom.cdx.json +41 -0
- package/src/license-grace.ts +147 -0
- package/src/local-engine.ts +44 -0
- package/src/server.ts +320 -0
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@exactrows/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "ExactRows MCP server: Streamable HTTP + stdio, with --local-wasm offline mode (Ed25519 license, 30-day grace). Zero runtime dependencies.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"private": false,
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/exactrows/exactrows.git",
|
|
14
|
+
"directory": "packages/exactrows-mcp"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://exactrows.com/developers",
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22"
|
|
19
|
+
},
|
|
20
|
+
"bin": {
|
|
21
|
+
"exactrows-mcp": "bin/exactrows-mcp.mjs"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"bin",
|
|
25
|
+
"bundle",
|
|
26
|
+
"src",
|
|
27
|
+
"README.md",
|
|
28
|
+
"sbom.cdx.json"
|
|
29
|
+
],
|
|
30
|
+
"dependencies": {},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"mcp",
|
|
33
|
+
"quickbooks",
|
|
34
|
+
"qbo",
|
|
35
|
+
"ofx",
|
|
36
|
+
"reconciliation",
|
|
37
|
+
"exactrows"
|
|
38
|
+
]
|
|
39
|
+
}
|
package/sbom.cdx.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bomFormat": "CycloneDX",
|
|
3
|
+
"specVersion": "1.5",
|
|
4
|
+
"version": 1,
|
|
5
|
+
"serialNumber": "urn:uuid:7b0e5d3a-2c41-4f6e-9a57-3d1c8e0b6f21",
|
|
6
|
+
"metadata": {
|
|
7
|
+
"timestamp": "2026-11-28T00:00:00Z",
|
|
8
|
+
"component": {
|
|
9
|
+
"type": "application",
|
|
10
|
+
"bom-ref": "pkg:npm/%40exactrows/mcp@0.2.0",
|
|
11
|
+
"name": "@exactrows/mcp",
|
|
12
|
+
"version": "0.2.0",
|
|
13
|
+
"purl": "pkg:npm/%40exactrows/mcp@0.2.0",
|
|
14
|
+
"description": "ExactRows MCP server. Zero runtime npm dependencies; uses Node built-ins and WebCrypto only."
|
|
15
|
+
},
|
|
16
|
+
"properties": [
|
|
17
|
+
{ "name": "exactrows:runtime-dependencies", "value": "0" },
|
|
18
|
+
{ "name": "exactrows:offline-egress", "value": "none (--local-wasm performs zero outbound fetch)" }
|
|
19
|
+
]
|
|
20
|
+
},
|
|
21
|
+
"components": [
|
|
22
|
+
{ "type": "platform", "bom-ref": "node-22", "name": "node", "version": "22", "description": "Node.js >=22 runtime (node:http, node:readline built-ins)" },
|
|
23
|
+
{ "type": "library", "bom-ref": "webcrypto", "name": "WebCrypto", "version": "1.0", "description": "globalThis.crypto.subtle: Ed25519 verify, SHA-256" },
|
|
24
|
+
{ "type": "library", "bom-ref": "exactrows-core-qbo", "name": "exactrows-core/qbo", "version": "3.1.0", "description": "src/api-worker/routes/qbo.ts + src/lib/parser/qbo-validator.ts, exporters.ts, fitid-v1.ts" },
|
|
25
|
+
{ "type": "library", "bom-ref": "exactrows-core-reconcile", "name": "exactrows-core/reconcile", "version": "3.1.0", "description": "src/api-worker/routes/reconcile.ts + src/lib/parser/reconcile.ts" },
|
|
26
|
+
{ "type": "library", "bom-ref": "exactrows-core-csv", "name": "exactrows-core/csv", "version": "3.1.0", "description": "src/api-worker/routes/csv.ts + src/lib/vault/custom-csv-templates.ts" },
|
|
27
|
+
{ "type": "library", "bom-ref": "exactrows-core-receipts", "name": "exactrows-core/receipts", "version": "3.1.0", "description": "src/api-worker/receipts.ts ExactRows-Receipt-v1 Ed25519 signing/verification" }
|
|
28
|
+
],
|
|
29
|
+
"dependencies": [
|
|
30
|
+
{
|
|
31
|
+
"ref": "pkg:npm/%40exactrows/mcp@0.2.0",
|
|
32
|
+
"dependsOn": ["node-22", "webcrypto", "exactrows-core-qbo", "exactrows-core-reconcile", "exactrows-core-csv", "exactrows-core-receipts"]
|
|
33
|
+
},
|
|
34
|
+
{ "ref": "node-22", "dependsOn": [] },
|
|
35
|
+
{ "ref": "webcrypto", "dependsOn": [] },
|
|
36
|
+
{ "ref": "exactrows-core-qbo", "dependsOn": ["webcrypto", "exactrows-core-receipts"] },
|
|
37
|
+
{ "ref": "exactrows-core-reconcile", "dependsOn": ["webcrypto", "exactrows-core-receipts"] },
|
|
38
|
+
{ "ref": "exactrows-core-csv", "dependsOn": ["webcrypto", "exactrows-core-receipts"] },
|
|
39
|
+
{ "ref": "exactrows-core-receipts", "dependsOn": ["webcrypto"] }
|
|
40
|
+
]
|
|
41
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Offline Ed25519 license token verifier + 30-day grace tracker. WebCrypto only. */
|
|
2
|
+
|
|
3
|
+
export const DAY_MS = 86_400_000;
|
|
4
|
+
export const ACTIVE_OFFLINE_DAYS = 7;
|
|
5
|
+
export const GRACE_DAYS = 30;
|
|
6
|
+
export const CLOCK_SKEW_MS = 5 * 60 * 1000; // 5 minutes clock-skew tolerance
|
|
7
|
+
|
|
8
|
+
export interface LicensePayload {
|
|
9
|
+
licenseId: string;
|
|
10
|
+
plan: string;
|
|
11
|
+
issuedAt: string;
|
|
12
|
+
/** Optional hard expiry (ISO). */
|
|
13
|
+
expiresAt?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type LicenseStatus = 'active' | 'grace' | 'expired' | 'invalid';
|
|
17
|
+
|
|
18
|
+
export interface LicenseResult {
|
|
19
|
+
status: LicenseStatus;
|
|
20
|
+
ok: boolean;
|
|
21
|
+
payload?: LicensePayload;
|
|
22
|
+
daysOffline: number;
|
|
23
|
+
graceDaysRemaining: number;
|
|
24
|
+
warning?: string;
|
|
25
|
+
reason?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function b64ToBytes(s: string): Uint8Array {
|
|
29
|
+
const n = s.replace(/-/g, '+').replace(/_/g, '/');
|
|
30
|
+
const bin = atob(n + '='.repeat((4 - (n.length % 4)) % 4));
|
|
31
|
+
const out = new Uint8Array(bin.length);
|
|
32
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function bytesToB64Url(b: Uint8Array): string {
|
|
37
|
+
let s = '';
|
|
38
|
+
for (const x of b) s += String.fromCharCode(x);
|
|
39
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const SPKI_PREFIX = new Uint8Array([0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00]);
|
|
43
|
+
|
|
44
|
+
async function importPublic(key: string): Promise<CryptoKey> {
|
|
45
|
+
let bytes = b64ToBytes(key.replace(/-----(BEGIN|END)[^-]+-----/g, '').replace(/\s+/g, ''));
|
|
46
|
+
if (bytes.length === 32) {
|
|
47
|
+
const o = new Uint8Array(44);
|
|
48
|
+
o.set(SPKI_PREFIX);
|
|
49
|
+
o.set(bytes, 12);
|
|
50
|
+
bytes = o;
|
|
51
|
+
}
|
|
52
|
+
return crypto.subtle.importKey('spki', bytes as BufferSource, { name: 'Ed25519' }, false, ['verify']);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Token format: base64url(JSON payload) + "." + base64url(Ed25519 signature over the payload segment). */
|
|
56
|
+
export async function signLicenseToken(payload: LicensePayload, privateKey: CryptoKey): Promise<string> {
|
|
57
|
+
const seg = bytesToB64Url(new TextEncoder().encode(JSON.stringify(payload)));
|
|
58
|
+
const sig = new Uint8Array(await crypto.subtle.sign({ name: 'Ed25519' }, privateKey, new TextEncoder().encode(seg)));
|
|
59
|
+
return `${seg}.${bytesToB64Url(sig)}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface VerifyOptions {
|
|
63
|
+
now?: number;
|
|
64
|
+
/** Epoch ms of last successful online verification; undefined/null = verified online right now. */
|
|
65
|
+
lastOnlineAt?: number | null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function verifyLicenseToken(token: string, publicKey: string, opts: VerifyOptions = {}): Promise<LicenseResult> {
|
|
69
|
+
const bad = (reason: string): LicenseResult => ({ status: 'invalid', ok: false, daysOffline: 0, graceDaysRemaining: 0, reason });
|
|
70
|
+
const parts = (token ?? '').trim().split('.');
|
|
71
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) return bad('malformed_token');
|
|
72
|
+
let payload: LicensePayload;
|
|
73
|
+
try {
|
|
74
|
+
const key = await importPublic(publicKey);
|
|
75
|
+
const valid = await crypto.subtle.verify(
|
|
76
|
+
{ name: 'Ed25519' },
|
|
77
|
+
key,
|
|
78
|
+
b64ToBytes(parts[1]) as BufferSource,
|
|
79
|
+
new TextEncoder().encode(parts[0]),
|
|
80
|
+
);
|
|
81
|
+
if (!valid) return bad('signature_mismatch');
|
|
82
|
+
payload = JSON.parse(new TextDecoder().decode(b64ToBytes(parts[0]))) as LicensePayload;
|
|
83
|
+
} catch {
|
|
84
|
+
return bad('signature_mismatch');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const now = opts.now ?? Date.now();
|
|
88
|
+
if (typeof now !== 'number' || Number.isNaN(now) || now < 0) {
|
|
89
|
+
return bad('invalid_time');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Validate issuedAt with clock-skew tolerance (up to 5 min in future allowed)
|
|
93
|
+
if (!payload || typeof payload !== 'object' || !payload.issuedAt || typeof payload.issuedAt !== 'string') {
|
|
94
|
+
return bad('invalid_issued_at');
|
|
95
|
+
}
|
|
96
|
+
const issuedTime = Date.parse(payload.issuedAt);
|
|
97
|
+
if (Number.isNaN(issuedTime) || issuedTime < 0) {
|
|
98
|
+
return bad('invalid_issued_at');
|
|
99
|
+
}
|
|
100
|
+
if (issuedTime > now + CLOCK_SKEW_MS) {
|
|
101
|
+
return bad('issued_in_future');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Validate optional expiresAt
|
|
105
|
+
if (payload.expiresAt !== undefined) {
|
|
106
|
+
if (typeof payload.expiresAt !== 'string') return bad('invalid_expires_at');
|
|
107
|
+
const expTime = Date.parse(payload.expiresAt);
|
|
108
|
+
if (Number.isNaN(expTime) || expTime < 0) {
|
|
109
|
+
return bad('invalid_expires_at');
|
|
110
|
+
}
|
|
111
|
+
if (expTime < issuedTime) {
|
|
112
|
+
return bad('expires_before_issued');
|
|
113
|
+
}
|
|
114
|
+
if (expTime < now) {
|
|
115
|
+
return { status: 'expired', ok: false, payload, daysOffline: 0, graceDaysRemaining: 0, reason: 'license_expired' };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (opts.lastOnlineAt == null) {
|
|
120
|
+
return { status: 'active', ok: true, payload, daysOffline: 0, graceDaysRemaining: GRACE_DAYS };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (typeof opts.lastOnlineAt !== 'number' || Number.isNaN(opts.lastOnlineAt) || opts.lastOnlineAt < 0) {
|
|
124
|
+
return bad('invalid_last_online');
|
|
125
|
+
}
|
|
126
|
+
if (opts.lastOnlineAt > now + CLOCK_SKEW_MS) {
|
|
127
|
+
return bad('last_online_in_future');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const effectiveLastOnline = Math.min(opts.lastOnlineAt, now);
|
|
131
|
+
const daysOffline = Math.max(0, Math.floor((now - effectiveLastOnline) / DAY_MS));
|
|
132
|
+
const remaining = Math.max(0, GRACE_DAYS - daysOffline);
|
|
133
|
+
if (daysOffline > GRACE_DAYS) {
|
|
134
|
+
return { status: 'expired', ok: false, payload, daysOffline, graceDaysRemaining: 0, reason: 'grace_window_exceeded' };
|
|
135
|
+
}
|
|
136
|
+
if (daysOffline > ACTIVE_OFFLINE_DAYS) {
|
|
137
|
+
return {
|
|
138
|
+
status: 'grace',
|
|
139
|
+
ok: true,
|
|
140
|
+
payload,
|
|
141
|
+
daysOffline,
|
|
142
|
+
graceDaysRemaining: remaining,
|
|
143
|
+
warning: `Offline for ${daysOffline} days; reconnect within ${remaining} days to keep the license active.`,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return { status: 'active', ok: true, payload, daysOffline, graceDaysRemaining: remaining };
|
|
147
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Offline engine: runs the deterministic ExactRows route handlers in-process. Never calls fetch. */
|
|
2
|
+
import { handleQbo } from '../../../src/api-worker/routes/qbo';
|
|
3
|
+
import { handleReconcile } from '../../../src/api-worker/routes/reconcile';
|
|
4
|
+
import { handleCsv } from '../../../src/api-worker/routes/csv';
|
|
5
|
+
import { verifyReceipt } from '../../../src/api-worker/receipts';
|
|
6
|
+
import type { ReceiptV1 } from '../../../src/api-worker/types';
|
|
7
|
+
|
|
8
|
+
export const TOOL_ROUTES: Record<string, string> = {
|
|
9
|
+
exactrows_qbo_validate: '/v1/qbo/validate',
|
|
10
|
+
exactrows_qbo_repair: '/v1/qbo/repair',
|
|
11
|
+
exactrows_qbo_generate: '/v1/qbo/generate',
|
|
12
|
+
exactrows_qbo_diff_dedupe: '/v1/qbo/diff-dedupe',
|
|
13
|
+
exactrows_reconcile_verify: '/v1/reconcile/verify',
|
|
14
|
+
exactrows_csv_normalize: '/v1/csv/normalize',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const TOOL_NAMES = [...Object.keys(TOOL_ROUTES), 'exactrows_verify_receipt'];
|
|
18
|
+
|
|
19
|
+
export type KeyEnv = Record<string, string | undefined>;
|
|
20
|
+
|
|
21
|
+
export async function runLocalTool(name: string, args: Record<string, unknown>, env: KeyEnv = {}): Promise<unknown> {
|
|
22
|
+
if (name === 'exactrows_verify_receipt') {
|
|
23
|
+
const receipt = (args.receipt ?? args) as ReceiptV1;
|
|
24
|
+
let valid = false;
|
|
25
|
+
try {
|
|
26
|
+
valid = await verifyReceipt(receipt, env);
|
|
27
|
+
} catch {
|
|
28
|
+
valid = false;
|
|
29
|
+
}
|
|
30
|
+
return { ok: true, valid };
|
|
31
|
+
}
|
|
32
|
+
const path = TOOL_ROUTES[name];
|
|
33
|
+
if (!path) throw new Error(`Unknown tool: ${name}`);
|
|
34
|
+
const request = new Request(`http://local.exactrows.invalid${path}`, {
|
|
35
|
+
method: 'POST',
|
|
36
|
+
headers: { 'content-type': 'application/json' },
|
|
37
|
+
body: JSON.stringify(args ?? {}),
|
|
38
|
+
});
|
|
39
|
+
const ctx = { path };
|
|
40
|
+
const res = (await handleQbo(request.clone() as unknown as Request, env, ctx)) ?? (await handleReconcile(request.clone() as unknown as Request, env, ctx)) ?? (await handleCsv(request as unknown as Request, env, ctx));
|
|
41
|
+
if (!res) throw new Error(`No local handler for ${path}`);
|
|
42
|
+
return res.json();
|
|
43
|
+
}
|
|
44
|
+
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/** Zero-dependency MCP JSON-RPC 2.0 server: Streamable HTTP (POST /mcp) + stdio. */
|
|
2
|
+
import { createServer, type Server } from 'node:http';
|
|
3
|
+
import { runLocalTool, TOOL_ROUTES, type KeyEnv } from './local-engine';
|
|
4
|
+
import { verifyLicenseToken } from './license-grace';
|
|
5
|
+
|
|
6
|
+
export const PROTOCOL_VERSION = '2025-03-26';
|
|
7
|
+
export const SERVER_INFO = { name: '@exactrows/mcp', version: '0.2.0' };
|
|
8
|
+
|
|
9
|
+
const obj = (properties: Record<string, unknown> = {}) => ({ type: 'object', properties, additionalProperties: true });
|
|
10
|
+
const DESCS: Record<string, string> = {
|
|
11
|
+
exactrows_qbo_validate: 'Validate a .QBO/.OFX file (qboText or qboBase64).',
|
|
12
|
+
exactrows_qbo_repair: 'Repair a .QBO/.OFX file with FITID v1 rebuild; returns signed receipt.',
|
|
13
|
+
exactrows_qbo_generate: 'Generate deterministic .qbo/.ofx from transactions.',
|
|
14
|
+
exactrows_qbo_diff_dedupe: 'Detect overlap/duplicates across statements.',
|
|
15
|
+
exactrows_reconcile_verify: 'Verify Opening + Credits - Debits = Closing in integer cents.',
|
|
16
|
+
exactrows_csv_normalize: 'Normalize a CSV (csvBase64) via preset or custom schema.',
|
|
17
|
+
exactrows_verify_receipt: 'Verify an ExactRows-Receipt-v1 Ed25519 signature.',
|
|
18
|
+
};
|
|
19
|
+
const INPUTS: Record<string, unknown> = {
|
|
20
|
+
exactrows_qbo_validate: obj({ qboText: { type: 'string' }, qboBase64: { type: 'string' }, lang: { type: 'string' } }),
|
|
21
|
+
exactrows_qbo_repair: obj({ qboText: { type: 'string' }, qboBase64: { type: 'string' }, options: { type: 'object' } }),
|
|
22
|
+
exactrows_qbo_generate: obj({ format: { type: 'string' }, currency: { type: 'string' }, transactions: { type: 'array' } }),
|
|
23
|
+
exactrows_qbo_diff_dedupe: obj({ transactions: { type: 'array' } }),
|
|
24
|
+
exactrows_reconcile_verify: obj({ openingCents: { type: 'integer' }, closingCents: { type: 'integer' }, transactions: { type: 'array' } }),
|
|
25
|
+
exactrows_csv_normalize: obj({ csvBase64: { type: 'string' }, preset: { type: 'string' }, targetFormat: { type: 'string' } }),
|
|
26
|
+
exactrows_verify_receipt: obj({ receipt: { type: 'object' } }),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const TOOLS = [...Object.keys(TOOL_ROUTES), 'exactrows_verify_receipt'].map((name) => ({
|
|
30
|
+
name,
|
|
31
|
+
description: DESCS[name],
|
|
32
|
+
inputSchema: INPUTS[name],
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
export interface ServerOptions {
|
|
36
|
+
/** Offline mode: in-process engine, no outbound fetch. */
|
|
37
|
+
localWasm?: boolean;
|
|
38
|
+
env?: KeyEnv;
|
|
39
|
+
licenseToken?: string;
|
|
40
|
+
licensePublicKey?: string;
|
|
41
|
+
lastOnlineAt?: number | null;
|
|
42
|
+
now?: number;
|
|
43
|
+
apiBase?: string;
|
|
44
|
+
apiKey?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type Rpc = { jsonrpc?: string; id?: unknown; method?: string; params?: any };
|
|
48
|
+
|
|
49
|
+
const rpcErr = (id: unknown, code: number, message: string) => ({
|
|
50
|
+
jsonrpc: '2.0',
|
|
51
|
+
id: id === undefined ? null : id,
|
|
52
|
+
error: { code, message },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
async function callTool(name: string, args: Record<string, unknown>, opts: ServerOptions): Promise<unknown> {
|
|
56
|
+
if (opts.localWasm) {
|
|
57
|
+
const lic = await verifyLicenseToken(opts.licenseToken ?? '', opts.licensePublicKey ?? '', { now: opts.now, lastOnlineAt: opts.lastOnlineAt });
|
|
58
|
+
if (!lic.ok) throw Object.assign(new Error(`License rejected: ${lic.reason}`), { licenseStatus: lic.status });
|
|
59
|
+
const result = await runLocalTool(name, args, opts.env ?? {});
|
|
60
|
+
return lic.warning && result && typeof result === 'object' ? { ...(result as object), licenseWarning: lic.warning } : result;
|
|
61
|
+
}
|
|
62
|
+
const route = name === 'exactrows_verify_receipt' ? '/v1/receipts/verify' : TOOL_ROUTES[name];
|
|
63
|
+
const res = await fetch(`${opts.apiBase ?? 'https://api.exactrows.com'}${route}`, {
|
|
64
|
+
method: 'POST',
|
|
65
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey ?? ''}` },
|
|
66
|
+
body: JSON.stringify(args),
|
|
67
|
+
});
|
|
68
|
+
return res.json();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Handle one JSON-RPC message. Returns null for notifications. */
|
|
72
|
+
export async function handleRpc(msg: Rpc, opts: ServerOptions = {}): Promise<Record<string, unknown> | null> {
|
|
73
|
+
if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
|
|
74
|
+
return rpcErr(msg && typeof msg === 'object' ? msg.id : null, -32600, 'Invalid Request');
|
|
75
|
+
}
|
|
76
|
+
const isNotification = msg.id === undefined;
|
|
77
|
+
switch (msg.method) {
|
|
78
|
+
case 'initialize':
|
|
79
|
+
return {
|
|
80
|
+
jsonrpc: '2.0',
|
|
81
|
+
id: msg.id === undefined ? null : msg.id,
|
|
82
|
+
result: { protocolVersion: PROTOCOL_VERSION, capabilities: { tools: { listChanged: false } }, serverInfo: SERVER_INFO },
|
|
83
|
+
};
|
|
84
|
+
case 'ping':
|
|
85
|
+
return { jsonrpc: '2.0', id: msg.id === undefined ? null : msg.id, result: {} };
|
|
86
|
+
case 'tools/list':
|
|
87
|
+
return { jsonrpc: '2.0', id: msg.id === undefined ? null : msg.id, result: { tools: TOOLS } };
|
|
88
|
+
case 'tools/call': {
|
|
89
|
+
if (!msg.params || typeof msg.params !== 'object' || Array.isArray(msg.params)) {
|
|
90
|
+
return rpcErr(msg.id, -32602, 'Invalid params: params object required');
|
|
91
|
+
}
|
|
92
|
+
const name = msg.params?.name;
|
|
93
|
+
if (typeof name !== 'string' || !name) {
|
|
94
|
+
return rpcErr(msg.id, -32602, 'Invalid params: tool name required');
|
|
95
|
+
}
|
|
96
|
+
if (!TOOLS.some((t) => t.name === name)) {
|
|
97
|
+
return rpcErr(msg.id, -32601, `Unknown tool: ${name}`);
|
|
98
|
+
}
|
|
99
|
+
if (msg.params.arguments !== undefined && (typeof msg.params.arguments !== 'object' || msg.params.arguments === null || Array.isArray(msg.params.arguments))) {
|
|
100
|
+
return rpcErr(msg.id, -32602, 'Invalid params: arguments must be an object');
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const out = await callTool(name, (msg.params?.arguments ?? {}) as Record<string, unknown>, opts);
|
|
104
|
+
const isError = !out || typeof out !== 'object' || (out as any).ok === false;
|
|
105
|
+
return {
|
|
106
|
+
jsonrpc: '2.0',
|
|
107
|
+
id: msg.id === undefined ? null : msg.id,
|
|
108
|
+
result: { content: [{ type: 'text', text: JSON.stringify(out) }], structuredContent: out, isError },
|
|
109
|
+
};
|
|
110
|
+
} catch (e) {
|
|
111
|
+
return {
|
|
112
|
+
jsonrpc: '2.0',
|
|
113
|
+
id: msg.id === undefined ? null : msg.id,
|
|
114
|
+
result: { content: [{ type: 'text', text: (e as Error).message }], isError: true },
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
default:
|
|
119
|
+
if (isNotification || msg.method.startsWith('notifications/')) return null;
|
|
120
|
+
return rpcErr(msg.id, -32601, `Method not found: ${msg.method}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function handleRpcPayload(payload: unknown, opts: ServerOptions = {}): Promise<unknown | null> {
|
|
125
|
+
if (Array.isArray(payload)) {
|
|
126
|
+
const out = (await Promise.all(payload.map((m) => handleRpc(m, opts)))).filter((r) => r !== null);
|
|
127
|
+
return out.length ? out : null;
|
|
128
|
+
}
|
|
129
|
+
return handleRpc(payload as Rpc, opts);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const CORS_HEADERS: Record<string, string> = {
|
|
133
|
+
'access-control-allow-origin': '*',
|
|
134
|
+
'access-control-allow-methods': 'POST, GET, OPTIONS',
|
|
135
|
+
'access-control-allow-headers': 'Content-Type, Mcp-Session-Id, Authorization',
|
|
136
|
+
'access-control-expose-headers': 'Mcp-Session-Id',
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/** Streamable HTTP: POST /mcp with JSON body, JSON response (202 for notifications). */
|
|
140
|
+
export function createHttpServer(opts: ServerOptions = {}): Server {
|
|
141
|
+
return createServer((req, res) => {
|
|
142
|
+
const rawSessionId = req.headers['mcp-session-id'];
|
|
143
|
+
const sessionId = typeof rawSessionId === 'string' && rawSessionId.trim()
|
|
144
|
+
? rawSessionId.trim()
|
|
145
|
+
: (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : undefined);
|
|
146
|
+
|
|
147
|
+
const send = (status: number, body?: unknown) => {
|
|
148
|
+
res.writeHead(status, {
|
|
149
|
+
...CORS_HEADERS,
|
|
150
|
+
...(sessionId ? { 'mcp-session-id': sessionId } : {}),
|
|
151
|
+
'content-type': 'application/json',
|
|
152
|
+
'cache-control': 'no-store',
|
|
153
|
+
});
|
|
154
|
+
res.end(body === undefined ? '' : JSON.stringify(body));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
if (req.method === 'OPTIONS') {
|
|
158
|
+
res.writeHead(204, {
|
|
159
|
+
...CORS_HEADERS,
|
|
160
|
+
...(sessionId ? { 'mcp-session-id': sessionId } : {}),
|
|
161
|
+
'cache-control': 'no-store',
|
|
162
|
+
});
|
|
163
|
+
res.end();
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const path = (req.url ?? '').split('?')[0];
|
|
168
|
+
if (path !== '/mcp') return send(404, { error: 'not_found' });
|
|
169
|
+
if (req.method !== 'POST') {
|
|
170
|
+
res.setHeader('allow', 'POST, OPTIONS');
|
|
171
|
+
return send(405, { error: 'method_not_allowed' });
|
|
172
|
+
}
|
|
173
|
+
const chunks: Buffer[] = [];
|
|
174
|
+
let size = 0;
|
|
175
|
+
req.on('data', (c: Buffer) => {
|
|
176
|
+
size += c.length;
|
|
177
|
+
if (size > 10 * 1024 * 1024) req.destroy();
|
|
178
|
+
else chunks.push(c);
|
|
179
|
+
});
|
|
180
|
+
req.on('end', async () => {
|
|
181
|
+
let payload: unknown;
|
|
182
|
+
try {
|
|
183
|
+
payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
184
|
+
} catch {
|
|
185
|
+
return send(400, rpcErr(null, -32700, 'Parse error'));
|
|
186
|
+
}
|
|
187
|
+
const out = await handleRpcPayload(payload, opts);
|
|
188
|
+
if (out === null) return send(202);
|
|
189
|
+
send(200, out);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** stdio: robust chunk buffering for newline-delimited, partial chunk, and multi-line JSON-RPC. */
|
|
195
|
+
export async function runStdio(
|
|
196
|
+
opts: ServerOptions = {},
|
|
197
|
+
input: NodeJS.ReadableStream = process.stdin,
|
|
198
|
+
output: NodeJS.WritableStream = process.stdout,
|
|
199
|
+
): Promise<void> {
|
|
200
|
+
let buffer = '';
|
|
201
|
+
const pending: Promise<void>[] = [];
|
|
202
|
+
|
|
203
|
+
const processBuffer = () => {
|
|
204
|
+
while (buffer.length > 0) {
|
|
205
|
+
const trimmed = buffer.trimStart();
|
|
206
|
+
if (!trimmed) {
|
|
207
|
+
buffer = '';
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
buffer = trimmed;
|
|
211
|
+
|
|
212
|
+
if (buffer.startsWith('{') || buffer.startsWith('[')) {
|
|
213
|
+
let depth = 0;
|
|
214
|
+
let inString = false;
|
|
215
|
+
let escape = false;
|
|
216
|
+
let endIdx = -1;
|
|
217
|
+
|
|
218
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
219
|
+
const ch = buffer[i];
|
|
220
|
+
if (inString) {
|
|
221
|
+
if (escape) {
|
|
222
|
+
escape = false;
|
|
223
|
+
} else if (ch === '\\') {
|
|
224
|
+
escape = true;
|
|
225
|
+
} else if (ch === '"') {
|
|
226
|
+
inString = false;
|
|
227
|
+
}
|
|
228
|
+
} else {
|
|
229
|
+
if (ch === '"') {
|
|
230
|
+
inString = true;
|
|
231
|
+
} else if (ch === '{' || ch === '[') {
|
|
232
|
+
depth++;
|
|
233
|
+
} else if (ch === '}' || ch === ']') {
|
|
234
|
+
depth--;
|
|
235
|
+
if (depth === 0) {
|
|
236
|
+
endIdx = i;
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (endIdx === -1) {
|
|
244
|
+
// Partial chunk, await more data
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const candidate = buffer.slice(0, endIdx + 1);
|
|
249
|
+
buffer = buffer.slice(endIdx + 1);
|
|
250
|
+
|
|
251
|
+
pending.push(
|
|
252
|
+
(async () => {
|
|
253
|
+
let out: unknown;
|
|
254
|
+
try {
|
|
255
|
+
out = await handleRpcPayload(JSON.parse(candidate), opts);
|
|
256
|
+
} catch {
|
|
257
|
+
out = rpcErr(null, -32700, 'Parse error');
|
|
258
|
+
}
|
|
259
|
+
if (out !== null) output.write(JSON.stringify(out) + '\n');
|
|
260
|
+
})(),
|
|
261
|
+
);
|
|
262
|
+
} else {
|
|
263
|
+
const nlIdx = buffer.indexOf('\n');
|
|
264
|
+
if (nlIdx === -1) {
|
|
265
|
+
// Incomplete token without newline, wait for more chunks
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
const line = buffer.slice(0, nlIdx).trim();
|
|
269
|
+
buffer = buffer.slice(nlIdx + 1);
|
|
270
|
+
if (line) {
|
|
271
|
+
pending.push(
|
|
272
|
+
(async () => {
|
|
273
|
+
let out: unknown;
|
|
274
|
+
try {
|
|
275
|
+
out = await handleRpcPayload(JSON.parse(line), opts);
|
|
276
|
+
} catch {
|
|
277
|
+
out = rpcErr(null, -32700, 'Parse error');
|
|
278
|
+
}
|
|
279
|
+
if (out !== null) output.write(JSON.stringify(out) + '\n');
|
|
280
|
+
})(),
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
await new Promise<void>((resolve) => {
|
|
288
|
+
let closed = false;
|
|
289
|
+
const onEnd = () => {
|
|
290
|
+
if (closed) return;
|
|
291
|
+
closed = true;
|
|
292
|
+
if (buffer.trim()) {
|
|
293
|
+
const candidate = buffer.trim();
|
|
294
|
+
buffer = '';
|
|
295
|
+
pending.push(
|
|
296
|
+
(async () => {
|
|
297
|
+
let out: unknown;
|
|
298
|
+
try {
|
|
299
|
+
out = await handleRpcPayload(JSON.parse(candidate), opts);
|
|
300
|
+
} catch {
|
|
301
|
+
out = rpcErr(null, -32700, 'Parse error');
|
|
302
|
+
}
|
|
303
|
+
if (out !== null) output.write(JSON.stringify(out) + '\n');
|
|
304
|
+
})(),
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
resolve();
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
input.on('data', (chunk: Buffer | string) => {
|
|
311
|
+
buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
312
|
+
processBuffer();
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
input.on('end', onEnd);
|
|
316
|
+
input.on('close', onEnd);
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
await Promise.all(pending);
|
|
320
|
+
}
|