@ca-tax/mcp 0.0.0-stage → 0.1.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/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@ca-tax/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Canadian Tax & Payroll MCP server: Streamable HTTP + stdio, with --local-wasm offline mode (zero egress). 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/ca-tax-mcp"
15
+ },
16
+ "homepage": "https://exactrows.com/developers",
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "bin": {
21
+ "ca-tax-mcp": "bin/ca-tax-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
+ "canada",
34
+ "tax",
35
+ "payroll",
36
+ "cra",
37
+ "t4127",
38
+ "revenu-quebec",
39
+ "tp-1015.g",
40
+ "gst",
41
+ "hst",
42
+ "qst",
43
+ "sales-tax"
44
+ ]
45
+ }
package/sbom.cdx.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "bomFormat": "CycloneDX",
3
+ "specVersion": "1.5",
4
+ "version": 1,
5
+ "serialNumber": "urn:uuid:8c1f6e4b-3d52-4a7f-8b68-4e2d9f1c7a32",
6
+ "metadata": {
7
+ "timestamp": "2026-11-28T00:00:00Z",
8
+ "component": {
9
+ "type": "application",
10
+ "bom-ref": "pkg:npm/%40ca-tax/mcp@0.1.0",
11
+ "name": "@ca-tax/mcp",
12
+ "version": "0.1.0",
13
+ "purl": "pkg:npm/%40ca-tax/mcp@0.1.0",
14
+ "description": "Scoped Canadian Tax & Payroll 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-ca-sales-tax", "name": "exactrows-core/ca-sales-tax", "version": "1.0.0", "description": "src/api-worker/routes/ca-tax.ts lookupCaSalesTax FSA routing, rate versioning (NS 2025-04-01), bilingual en/fr" },
25
+ { "type": "library", "bom-ref": "exactrows-ca-payroll", "name": "exactrows-core/ca-payroll", "version": "1.0.0", "description": "src/api-worker/routes/ca-tax.ts calculateCaPayrollDeductions CRA T4127 + Revenu Québec TP-1015.G" },
26
+ { "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" }
27
+ ],
28
+ "dependencies": [
29
+ {
30
+ "ref": "pkg:npm/%40ca-tax/mcp@0.1.0",
31
+ "dependsOn": ["node-22", "webcrypto", "exactrows-ca-sales-tax", "exactrows-ca-payroll", "exactrows-core-receipts"]
32
+ },
33
+ { "ref": "node-22", "dependsOn": [] },
34
+ { "ref": "webcrypto", "dependsOn": [] },
35
+ { "ref": "exactrows-ca-sales-tax", "dependsOn": ["webcrypto", "exactrows-core-receipts"] },
36
+ { "ref": "exactrows-ca-payroll", "dependsOn": ["webcrypto", "exactrows-core-receipts"] },
37
+ { "ref": "exactrows-core-receipts", "dependsOn": ["webcrypto"] }
38
+ ]
39
+ }
package/src/server.ts ADDED
@@ -0,0 +1,499 @@
1
+ /**
2
+ * Scoped Canadian Tax & Payroll MCP Server (@ca-tax/mcp)
3
+ * Zero runtime npm dependencies: Node.js built-ins + WebCrypto + in-process engine.
4
+ * Supports:
5
+ * - Streamable HTTP (POST /mcp)
6
+ * - stdio JSON-RPC 2.0
7
+ * - --local-wasm offline mode (direct in-process deterministic execution with ZERO outbound network fetch)
8
+ */
9
+ import { createServer, type Server } from 'node:http';
10
+ import {
11
+ handleCaTax,
12
+ lookupCaSalesTax,
13
+ calculateCaPayrollDeductions,
14
+ type CaProvince,
15
+ type PayFrequencyInput,
16
+ type PayrollYtdInput,
17
+ } from '../../../src/api-worker/routes/ca-tax';
18
+
19
+ export type Lang = 'en' | 'fr';
20
+
21
+ export const PROTOCOL_VERSION = '2025-03-26';
22
+ export const SERVER_INFO = { name: '@ca-tax/mcp', version: '0.1.0' };
23
+
24
+ export type KeyEnv = Record<string, string | undefined>;
25
+
26
+ export interface ServerOptions {
27
+ /** Offline mode: in-process deterministic execution, zero outbound network fetch. */
28
+ localWasm?: boolean;
29
+ env?: KeyEnv;
30
+ apiBase?: string;
31
+ apiKey?: string;
32
+ }
33
+
34
+ const obj = (properties: Record<string, unknown> = {}, required: string[] = []) => ({
35
+ type: 'object',
36
+ properties,
37
+ ...(required.length > 0 ? { required } : {}),
38
+ additionalProperties: true,
39
+ });
40
+
41
+ export const TOOLS = [
42
+ {
43
+ name: 'ca_sales_tax_lookup',
44
+ description:
45
+ 'Look up Canadian sales tax rates (GST, PST, HST, QST) by postal code / FSA or province with effective date versioning (e.g. Nova Scotia 2025-04-01), bilingual EN/FR labels, and 6-character border FSA resolution (K1A federal offices in Gatineau QC vs Ottawa ON, S9V/T9V Lloydminster SK/AB border).',
46
+ inputSchema: obj(
47
+ {
48
+ postal: {
49
+ type: 'string',
50
+ description:
51
+ 'Canadian postal code (6 characters, e.g. K1A 0B8 for Gatineau QC vs K1A 0A6 for Ottawa ON, or S9V 0X8 for Lloydminster) or 3-character FSA (e.g. H2Y 1C6 or M5V).',
52
+ },
53
+ province: { type: 'string', description: 'Two-letter Canadian province/territory code (e.g. ON, QC, AB).' },
54
+ effectiveDate: { type: 'string', description: 'Effective date for rate determination in YYYY-MM-DD format.' },
55
+ lang: { type: 'string', enum: ['en', 'fr'], description: 'Language preference for tax labels (en or fr).' },
56
+ },
57
+ ['postal'],
58
+ ),
59
+ },
60
+ {
61
+ name: 'ca_payroll_deductions',
62
+ description:
63
+ 'Calculate Canadian payroll deductions under CRA T4127 and Revenu Québec TP-1015.G rules (CPP/CPP2, QPP/QPP2, EI, QPIP, federal abatement, provincial tax, FSS, CNESST, CNT) with full TD1 Claim Codes (1..10) support.',
64
+ inputSchema: obj(
65
+ {
66
+ province: { type: 'string', description: 'Two-letter Canadian province/territory code (e.g. ON, QC, AB).' },
67
+ grossPayCents: { type: 'integer', minimum: 0, description: 'Gross pay for period in integer cents.' },
68
+ payFrequency: {
69
+ type: 'string',
70
+ enum: ['weekly', 'biweekly', 'semi_monthly', 'monthly'],
71
+ description: 'Pay frequency.',
72
+ },
73
+ periodsPerYear: {
74
+ type: 'integer',
75
+ enum: [52, 26, 24, 12],
76
+ description: 'Number of pay periods per year (alternative to payFrequency).',
77
+ },
78
+ claimCode: {
79
+ type: 'integer',
80
+ minimum: 1,
81
+ maximum: 10,
82
+ description: 'Federal and provincial TD1 claim code (1-10) for basic personal exemption amounts.',
83
+ },
84
+ ytdPensionableCents: { type: 'integer', minimum: 0, description: 'YTD pensionable earnings in cents.' },
85
+ ytdInsurableCents: { type: 'integer', minimum: 0, description: 'YTD insurable earnings in cents.' },
86
+ ytdCppCents: { type: 'integer', minimum: 0, description: 'YTD CPP deductions in cents.' },
87
+ ytdCpp2Cents: { type: 'integer', minimum: 0, description: 'YTD CPP2 deductions in cents.' },
88
+ ytdQppCents: { type: 'integer', minimum: 0, description: 'YTD QPP deductions in cents.' },
89
+ ytdQpp2Cents: { type: 'integer', minimum: 0, description: 'YTD QPP2 deductions in cents.' },
90
+ ytdEiCents: { type: 'integer', minimum: 0, description: 'YTD EI deductions in cents.' },
91
+ ytdQpipCents: { type: 'integer', minimum: 0, description: 'YTD QPIP deductions in cents.' },
92
+ effectiveDate: { type: 'string', description: 'Effective date in YYYY-MM-DD format (supported years: 2025, 2026).' },
93
+ lang: { type: 'string', enum: ['en', 'fr'], description: 'Language for labels (en or fr).' },
94
+ exemptCpp: { type: 'boolean', description: 'Whether employee is exempt from CPP/QPP.' },
95
+ exemptEi: { type: 'boolean', description: 'Whether employee is exempt from EI.' },
96
+ exemptQpip: { type: 'boolean', description: 'Whether employee is exempt from QPIP.' },
97
+ cnesstRateBps: { type: 'integer', minimum: 0, description: 'Employer CNESST rate in basis points (QC).' },
98
+ fssRateBps: { type: 'integer', minimum: 0, description: 'Employer FSS rate in basis points (QC).' },
99
+ },
100
+ ['province', 'grossPayCents'],
101
+ ),
102
+ },
103
+ ];
104
+
105
+ export async function runLocalTool(
106
+ name: string,
107
+ args: Record<string, unknown>,
108
+ env: KeyEnv = {},
109
+ ): Promise<unknown> {
110
+ if (name === 'ca_sales_tax_lookup') {
111
+ const postal = typeof args.postal === 'string' ? args.postal : undefined;
112
+ const province = typeof args.province === 'string' ? args.province : undefined;
113
+ const effectiveDate = typeof args.effectiveDate === 'string' ? args.effectiveDate : undefined;
114
+ const lang = (args.lang === 'fr' ? 'fr' : 'en') as Lang;
115
+
116
+ const params = new URLSearchParams();
117
+ if (postal) params.set('postal', postal);
118
+ if (province) params.set('province', province);
119
+ if (effectiveDate) params.set('effectiveDate', effectiveDate);
120
+ if (lang) params.set('lang', lang);
121
+
122
+ const req = new Request(`http://local.exactrows.invalid/v1/ca/sales-tax?${params.toString()}`, {
123
+ method: 'GET',
124
+ });
125
+ const ctx = { path: '/v1/ca/sales-tax', url: new URL(req.url) };
126
+ const res = await handleCaTax(req, env as any, ctx);
127
+ if (!res) {
128
+ const pure = lookupCaSalesTax({ postal, province, effectiveDate, lang });
129
+ return { ok: true, ...pure };
130
+ }
131
+ return res.json();
132
+ }
133
+
134
+ if (name === 'ca_payroll_deductions') {
135
+ const payFrequency = (args.payFrequency ?? args.periodsPerYear) as PayFrequencyInput;
136
+ const ytd: PayrollYtdInput = {
137
+ ...((args.ytd as object) ?? {}),
138
+ ...(args.ytdPensionableCents !== undefined ? { pensionableEarningsCents: Number(args.ytdPensionableCents) } : {}),
139
+ ...(args.ytdInsurableCents !== undefined ? { insurableEarningsCents: Number(args.ytdInsurableCents) } : {}),
140
+ ...(args.ytdCppCents !== undefined ? { cppCents: Number(args.ytdCppCents) } : {}),
141
+ ...(args.ytdCpp2Cents !== undefined ? { cpp2Cents: Number(args.ytdCpp2Cents) } : {}),
142
+ ...(args.ytdQppCents !== undefined ? { qppCents: Number(args.ytdQppCents) } : {}),
143
+ ...(args.ytdQpp2Cents !== undefined ? { qpp2Cents: Number(args.ytdQpp2Cents) } : {}),
144
+ ...(args.ytdEiCents !== undefined ? { eiCents: Number(args.ytdEiCents) } : {}),
145
+ ...(args.ytdQpipCents !== undefined ? { qpipCents: Number(args.ytdQpipCents) } : {}),
146
+ };
147
+
148
+ const body: Record<string, unknown> = {
149
+ ...args,
150
+ grossPayCents: args.grossPayCents,
151
+ province: args.province,
152
+ payFrequency,
153
+ effectiveDate: args.effectiveDate,
154
+ lang: args.lang,
155
+ ...(args.claimCode !== undefined ? { claimCode: Number(args.claimCode) } : {}),
156
+ ...(Object.keys(ytd).length > 0 ? { ytd } : {}),
157
+ };
158
+
159
+ const req = new Request('http://local.exactrows.invalid/v1/ca/payroll/deductions', {
160
+ method: 'POST',
161
+ headers: { 'content-type': 'application/json' },
162
+ body: JSON.stringify(body),
163
+ });
164
+ const ctx = { path: '/v1/ca/payroll/deductions', url: new URL(req.url) };
165
+ const res = await handleCaTax(req, env as any, ctx);
166
+ if (!res) {
167
+ const pure = calculateCaPayrollDeductions({
168
+ grossPayCents: Number(args.grossPayCents),
169
+ province: String(args.province ?? '') as CaProvince,
170
+ payFrequency,
171
+ effectiveDate: typeof args.effectiveDate === 'string' ? args.effectiveDate : undefined,
172
+ claimCode: args.claimCode !== undefined ? Number(args.claimCode) : undefined,
173
+ lang: args.lang === 'fr' ? 'fr' : 'en',
174
+ ytd: Object.keys(ytd).length > 0 ? ytd : undefined,
175
+ cnesstRateBps: typeof args.cnesstRateBps === 'number' ? args.cnesstRateBps : undefined,
176
+ fssRateBps: typeof args.fssRateBps === 'number' ? args.fssRateBps : undefined,
177
+ });
178
+ return { ok: true, ...pure };
179
+ }
180
+ return res.json();
181
+ }
182
+
183
+ throw new Error(`Unknown tool: ${name}`);
184
+ }
185
+
186
+ async function callTool(name: string, args: Record<string, unknown>, opts: ServerOptions): Promise<unknown> {
187
+ if (opts.localWasm) {
188
+ return runLocalTool(name, args, opts.env ?? {});
189
+ }
190
+ const apiBase = opts.apiBase ?? 'https://api.exactrows.com';
191
+ const headers: Record<string, string> = {
192
+ 'content-type': 'application/json',
193
+ ...(opts.apiKey ? { authorization: `Bearer ${opts.apiKey}` } : {}),
194
+ };
195
+
196
+ if (name === 'ca_sales_tax_lookup') {
197
+ const params = new URLSearchParams();
198
+ if (args.postal) params.set('postal', String(args.postal));
199
+ if (args.province) params.set('province', String(args.province));
200
+ if (args.effectiveDate) params.set('effectiveDate', String(args.effectiveDate));
201
+ if (args.lang) params.set('lang', String(args.lang));
202
+ const res = await fetch(`${apiBase}/v1/ca/sales-tax?${params.toString()}`, {
203
+ method: 'GET',
204
+ headers,
205
+ });
206
+ return res.json();
207
+ }
208
+
209
+ if (name === 'ca_payroll_deductions') {
210
+ const payFrequency = (args.payFrequency ?? args.periodsPerYear) as PayFrequencyInput | undefined;
211
+ const ytd: PayrollYtdInput = {
212
+ ...((args.ytd as object) ?? {}),
213
+ ...(args.ytdPensionableCents !== undefined ? { pensionableEarningsCents: Number(args.ytdPensionableCents) } : {}),
214
+ ...(args.ytdInsurableCents !== undefined ? { insurableEarningsCents: Number(args.ytdInsurableCents) } : {}),
215
+ ...(args.ytdCppCents !== undefined ? { cppCents: Number(args.ytdCppCents) } : {}),
216
+ ...(args.ytdCpp2Cents !== undefined ? { cpp2Cents: Number(args.ytdCpp2Cents) } : {}),
217
+ ...(args.ytdQppCents !== undefined ? { qppCents: Number(args.ytdQppCents) } : {}),
218
+ ...(args.ytdQpp2Cents !== undefined ? { qpp2Cents: Number(args.ytdQpp2Cents) } : {}),
219
+ ...(args.ytdEiCents !== undefined ? { eiCents: Number(args.ytdEiCents) } : {}),
220
+ ...(args.ytdQpipCents !== undefined ? { qpipCents: Number(args.ytdQpipCents) } : {}),
221
+ };
222
+ const body: Record<string, unknown> = {
223
+ ...args,
224
+ ...(payFrequency ? { payFrequency } : {}),
225
+ ...(args.claimCode !== undefined ? { claimCode: Number(args.claimCode) } : {}),
226
+ ...(Object.keys(ytd).length > 0 ? { ytd } : {}),
227
+ };
228
+ const res = await fetch(`${apiBase}/v1/ca/payroll/deductions`, {
229
+ method: 'POST',
230
+ headers,
231
+ body: JSON.stringify(body),
232
+ });
233
+ return res.json();
234
+ }
235
+
236
+ throw new Error(`Unknown tool: ${name}`);
237
+ }
238
+
239
+ type Rpc = { jsonrpc?: string; id?: unknown; method?: string; params?: any };
240
+
241
+ const rpcErr = (id: unknown, code: number, message: string) => ({
242
+ jsonrpc: '2.0',
243
+ id: id === undefined ? null : id,
244
+ error: { code, message },
245
+ });
246
+
247
+ export async function handleRpc(msg: Rpc, opts: ServerOptions = {}): Promise<Record<string, unknown> | null> {
248
+ if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
249
+ return rpcErr(msg && typeof msg === 'object' ? msg.id : null, -32600, 'Invalid Request');
250
+ }
251
+ const isNotification = msg.id === undefined;
252
+ switch (msg.method) {
253
+ case 'initialize':
254
+ return {
255
+ jsonrpc: '2.0',
256
+ id: msg.id === undefined ? null : msg.id,
257
+ result: {
258
+ protocolVersion: PROTOCOL_VERSION,
259
+ capabilities: { tools: { listChanged: false } },
260
+ serverInfo: SERVER_INFO,
261
+ },
262
+ };
263
+ case 'ping':
264
+ return { jsonrpc: '2.0', id: msg.id === undefined ? null : msg.id, result: {} };
265
+ case 'tools/list':
266
+ return { jsonrpc: '2.0', id: msg.id === undefined ? null : msg.id, result: { tools: TOOLS } };
267
+ case 'tools/call': {
268
+ if (!msg.params || typeof msg.params !== 'object' || Array.isArray(msg.params)) {
269
+ return rpcErr(msg.id, -32602, 'Invalid params: params object required');
270
+ }
271
+ const name = msg.params?.name;
272
+ if (typeof name !== 'string' || !name) {
273
+ return rpcErr(msg.id, -32602, 'Invalid params: tool name required');
274
+ }
275
+ if (!TOOLS.some((t) => t.name === name)) {
276
+ return rpcErr(msg.id, -32601, `Unknown tool: ${name}`);
277
+ }
278
+ if (msg.params.arguments !== undefined && (typeof msg.params.arguments !== 'object' || msg.params.arguments === null || Array.isArray(msg.params.arguments))) {
279
+ return rpcErr(msg.id, -32602, 'Invalid params: arguments must be an object');
280
+ }
281
+ try {
282
+ const out = await callTool(name, (msg.params?.arguments ?? {}) as Record<string, unknown>, opts);
283
+ const isError = !out || typeof out !== 'object' || (out as any).ok === false;
284
+ return {
285
+ jsonrpc: '2.0',
286
+ id: msg.id === undefined ? null : msg.id,
287
+ result: { content: [{ type: 'text', text: JSON.stringify(out) }], structuredContent: out, isError },
288
+ };
289
+ } catch (e) {
290
+ return {
291
+ jsonrpc: '2.0',
292
+ id: msg.id === undefined ? null : msg.id,
293
+ result: { content: [{ type: 'text', text: (e as Error).message }], isError: true },
294
+ };
295
+ }
296
+ }
297
+ default:
298
+ if (isNotification || msg.method.startsWith('notifications/')) return null;
299
+ return rpcErr(msg.id, -32601, `Method not found: ${msg.method}`);
300
+ }
301
+ }
302
+
303
+ export async function handleRpcPayload(payload: unknown, opts: ServerOptions = {}): Promise<unknown | null> {
304
+ if (Array.isArray(payload)) {
305
+ const out = (await Promise.all(payload.map((m) => handleRpc(m, opts)))).filter((r) => r !== null);
306
+ return out.length ? out : null;
307
+ }
308
+ return handleRpc(payload as Rpc, opts);
309
+ }
310
+
311
+ const CORS_HEADERS: Record<string, string> = {
312
+ 'access-control-allow-origin': '*',
313
+ 'access-control-allow-methods': 'POST, GET, OPTIONS',
314
+ 'access-control-allow-headers': 'Content-Type, Mcp-Session-Id, Authorization',
315
+ 'access-control-expose-headers': 'Mcp-Session-Id',
316
+ };
317
+
318
+ /** Streamable HTTP: POST /mcp with JSON body, JSON response (202 for notifications). */
319
+ export function createHttpServer(opts: ServerOptions = {}): Server {
320
+ return createServer((req, res) => {
321
+ const rawSessionId = req.headers['mcp-session-id'];
322
+ const sessionId = typeof rawSessionId === 'string' && rawSessionId.trim()
323
+ ? rawSessionId.trim()
324
+ : (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : undefined);
325
+
326
+ const send = (status: number, body?: unknown) => {
327
+ res.writeHead(status, {
328
+ ...CORS_HEADERS,
329
+ ...(sessionId ? { 'mcp-session-id': sessionId } : {}),
330
+ 'content-type': 'application/json',
331
+ 'cache-control': 'no-store',
332
+ });
333
+ res.end(body === undefined ? '' : JSON.stringify(body));
334
+ };
335
+
336
+ if (req.method === 'OPTIONS') {
337
+ res.writeHead(204, {
338
+ ...CORS_HEADERS,
339
+ ...(sessionId ? { 'mcp-session-id': sessionId } : {}),
340
+ 'cache-control': 'no-store',
341
+ });
342
+ res.end();
343
+ return;
344
+ }
345
+
346
+ const path = (req.url ?? '').split('?')[0];
347
+ if (path !== '/mcp') return send(404, { error: 'not_found' });
348
+ if (req.method !== 'POST') {
349
+ res.setHeader('allow', 'POST, OPTIONS');
350
+ return send(405, { error: 'method_not_allowed' });
351
+ }
352
+ const chunks: Buffer[] = [];
353
+ let size = 0;
354
+ req.on('data', (c: Buffer) => {
355
+ size += c.length;
356
+ if (size > 10 * 1024 * 1024) req.destroy();
357
+ else chunks.push(c);
358
+ });
359
+ req.on('end', async () => {
360
+ let payload: unknown;
361
+ try {
362
+ payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
363
+ } catch {
364
+ return send(400, rpcErr(null, -32700, 'Parse error'));
365
+ }
366
+ const out = await handleRpcPayload(payload, opts);
367
+ if (out === null) return send(202);
368
+ send(200, out);
369
+ });
370
+ });
371
+ }
372
+
373
+ /** stdio: robust chunk buffering for newline-delimited, partial chunk, and multi-line JSON-RPC. */
374
+ export async function runStdio(
375
+ opts: ServerOptions = {},
376
+ input: NodeJS.ReadableStream = process.stdin,
377
+ output: NodeJS.WritableStream = process.stdout,
378
+ ): Promise<void> {
379
+ let buffer = '';
380
+ const pending: Promise<void>[] = [];
381
+
382
+ const processBuffer = () => {
383
+ while (buffer.length > 0) {
384
+ const trimmed = buffer.trimStart();
385
+ if (!trimmed) {
386
+ buffer = '';
387
+ break;
388
+ }
389
+ buffer = trimmed;
390
+
391
+ if (buffer.startsWith('{') || buffer.startsWith('[')) {
392
+ let depth = 0;
393
+ let inString = false;
394
+ let escape = false;
395
+ let endIdx = -1;
396
+
397
+ for (let i = 0; i < buffer.length; i++) {
398
+ const ch = buffer[i];
399
+ if (inString) {
400
+ if (escape) {
401
+ escape = false;
402
+ } else if (ch === '\\') {
403
+ escape = true;
404
+ } else if (ch === '"') {
405
+ inString = false;
406
+ }
407
+ } else {
408
+ if (ch === '"') {
409
+ inString = true;
410
+ } else if (ch === '{' || ch === '[') {
411
+ depth++;
412
+ } else if (ch === '}' || ch === ']') {
413
+ depth--;
414
+ if (depth === 0) {
415
+ endIdx = i;
416
+ break;
417
+ }
418
+ }
419
+ }
420
+ }
421
+
422
+ if (endIdx === -1) {
423
+ // Partial chunk, wait for more data
424
+ break;
425
+ }
426
+
427
+ const candidate = buffer.slice(0, endIdx + 1);
428
+ buffer = buffer.slice(endIdx + 1);
429
+
430
+ pending.push(
431
+ (async () => {
432
+ let out: unknown;
433
+ try {
434
+ out = await handleRpcPayload(JSON.parse(candidate), opts);
435
+ } catch {
436
+ out = rpcErr(null, -32700, 'Parse error');
437
+ }
438
+ if (out !== null) output.write(JSON.stringify(out) + '\n');
439
+ })(),
440
+ );
441
+ } else {
442
+ const nlIdx = buffer.indexOf('\n');
443
+ if (nlIdx === -1) {
444
+ // Incomplete token without newline, wait for more chunks
445
+ break;
446
+ }
447
+ const line = buffer.slice(0, nlIdx).trim();
448
+ buffer = buffer.slice(nlIdx + 1);
449
+ if (line) {
450
+ pending.push(
451
+ (async () => {
452
+ let out: unknown;
453
+ try {
454
+ out = await handleRpcPayload(JSON.parse(line), opts);
455
+ } catch {
456
+ out = rpcErr(null, -32700, 'Parse error');
457
+ }
458
+ if (out !== null) output.write(JSON.stringify(out) + '\n');
459
+ })(),
460
+ );
461
+ }
462
+ }
463
+ }
464
+ };
465
+
466
+ await new Promise<void>((resolve) => {
467
+ let closed = false;
468
+ const onEnd = () => {
469
+ if (closed) return;
470
+ closed = true;
471
+ if (buffer.trim()) {
472
+ const candidate = buffer.trim();
473
+ buffer = '';
474
+ pending.push(
475
+ (async () => {
476
+ let out: unknown;
477
+ try {
478
+ out = await handleRpcPayload(JSON.parse(candidate), opts);
479
+ } catch {
480
+ out = rpcErr(null, -32700, 'Parse error');
481
+ }
482
+ if (out !== null) output.write(JSON.stringify(out) + '\n');
483
+ })(),
484
+ );
485
+ }
486
+ resolve();
487
+ };
488
+
489
+ input.on('data', (chunk: Buffer | string) => {
490
+ buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
491
+ processBuffer();
492
+ });
493
+
494
+ input.on('end', onEnd);
495
+ input.on('close', onEnd);
496
+ });
497
+
498
+ await Promise.all(pending);
499
+ }