iit-mcp-autotask 0.54.2
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/.env.example +123 -0
- package/LICENSE +21 -0
- package/README.md +788 -0
- package/capabilities.json +487 -0
- package/dist/access/gate.d.ts +34 -0
- package/dist/access/gate.js +76 -0
- package/dist/access/grants.d.ts +20 -0
- package/dist/access/grants.js +35 -0
- package/dist/access/write-env.d.ts +41 -0
- package/dist/access/write-env.js +166 -0
- package/dist/auth.d.ts +74 -0
- package/dist/auth.js +129 -0
- package/dist/base-hosts.d.ts +38 -0
- package/dist/base-hosts.js +70 -0
- package/dist/config/load.d.ts +28 -0
- package/dist/config/load.js +105 -0
- package/dist/config/schema.d.ts +166 -0
- package/dist/config/schema.js +311 -0
- package/dist/credential.d.ts +28 -0
- package/dist/credential.js +32 -0
- package/dist/doctor.d.ts +112 -0
- package/dist/doctor.js +154 -0
- package/dist/http-guard.d.ts +57 -0
- package/dist/http-guard.js +134 -0
- package/dist/http.d.ts +50 -0
- package/dist/http.js +290 -0
- package/dist/lifecycle.d.ts +29 -0
- package/dist/lifecycle.js +52 -0
- package/dist/logger.d.ts +26 -0
- package/dist/logger.js +28 -0
- package/dist/main.d.ts +12 -0
- package/dist/main.js +283 -0
- package/dist/policy.d.ts +54 -0
- package/dist/policy.js +80 -0
- package/dist/tools/aggregate.d.ts +16 -0
- package/dist/tools/aggregate.js +64 -0
- package/dist/tools/capabilities-manifest.d.ts +4 -0
- package/dist/tools/capabilities-manifest.js +94 -0
- package/dist/tools/catalog-data.d.ts +116 -0
- package/dist/tools/catalog-data.js +207 -0
- package/dist/tools/clock.d.ts +17 -0
- package/dist/tools/clock.js +43 -0
- package/dist/tools/composites.d.ts +36 -0
- package/dist/tools/composites.js +305 -0
- package/dist/tools/context/client.d.ts +41 -0
- package/dist/tools/context/client.js +139 -0
- package/dist/tools/context/derive.d.ts +9 -0
- package/dist/tools/context/derive.js +32 -0
- package/dist/tools/context/scope.d.ts +24 -0
- package/dist/tools/context/scope.js +180 -0
- package/dist/tools/context/types.d.ts +141 -0
- package/dist/tools/context/types.js +2 -0
- package/dist/tools/dispatch.d.ts +78 -0
- package/dist/tools/dispatch.js +272 -0
- package/dist/tools/field-pointer.d.ts +25 -0
- package/dist/tools/field-pointer.js +45 -0
- package/dist/tools/guide.d.ts +30 -0
- package/dist/tools/guide.js +97 -0
- package/dist/tools/lists.d.ts +9 -0
- package/dist/tools/lists.js +205 -0
- package/dist/tools/meta.d.ts +22 -0
- package/dist/tools/meta.js +709 -0
- package/dist/tools/output-file.d.ts +26 -0
- package/dist/tools/output-file.js +140 -0
- package/dist/tools/rank.d.ts +21 -0
- package/dist/tools/rank.js +57 -0
- package/dist/tools/reasons.d.ts +33 -0
- package/dist/tools/reasons.js +121 -0
- package/dist/tools/register.d.ts +23 -0
- package/dist/tools/register.js +50 -0
- package/dist/tools/resolves.d.ts +28 -0
- package/dist/tools/resolves.js +399 -0
- package/dist/tools/results/envelope.d.ts +55 -0
- package/dist/tools/results/envelope.js +63 -0
- package/dist/tools/results/errors.d.ts +147 -0
- package/dist/tools/results/errors.js +384 -0
- package/dist/tools/results/untrusted.d.ts +129 -0
- package/dist/tools/results/untrusted.js +218 -0
- package/dist/tools/revenue-rollup.d.ts +8 -0
- package/dist/tools/revenue-rollup.js +112 -0
- package/dist/tools/schemas.d.ts +467 -0
- package/dist/tools/schemas.js +444 -0
- package/dist/tools/scope-guard.d.ts +2 -0
- package/dist/tools/scope-guard.js +11 -0
- package/dist/tools/server-version.d.ts +3 -0
- package/dist/tools/server-version.js +14 -0
- package/dist/tools/server.d.ts +92 -0
- package/dist/tools/server.js +170 -0
- package/dist/tools/surface.d.ts +37 -0
- package/dist/tools/surface.js +94 -0
- package/dist/tools/tsv.d.ts +52 -0
- package/dist/tools/tsv.js +95 -0
- package/dist/tools/write/apply.d.ts +40 -0
- package/dist/tools/write/apply.js +500 -0
- package/dist/tools/write/checks.d.ts +39 -0
- package/dist/tools/write/checks.js +137 -0
- package/dist/tools/write/common.d.ts +23 -0
- package/dist/tools/write/common.js +33 -0
- package/dist/tools/write/facts.d.ts +52 -0
- package/dist/tools/write/facts.js +151 -0
- package/dist/tools/write/outcome.d.ts +23 -0
- package/dist/tools/write/outcome.js +67 -0
- package/dist/tools/write/parse.d.ts +37 -0
- package/dist/tools/write/parse.js +166 -0
- package/dist/tools/write/payload.d.ts +44 -0
- package/dist/tools/write/payload.js +119 -0
- package/dist/tools/write/preview.d.ts +3 -0
- package/dist/tools/write/preview.js +317 -0
- package/dist/tools/write/snapshot.d.ts +68 -0
- package/dist/tools/write/snapshot.js +360 -0
- package/dist/tools/write-guidance.d.ts +174 -0
- package/dist/tools/write-guidance.js +317 -0
- package/dist/tools/write.d.ts +9 -0
- package/dist/tools/write.js +10 -0
- package/dist/write/canonical.d.ts +12 -0
- package/dist/write/canonical.js +31 -0
- package/dist/write/evaluate.d.ts +77 -0
- package/dist/write/evaluate.js +91 -0
- package/dist/write/hard-rules.d.ts +49 -0
- package/dist/write/hard-rules.js +48 -0
- package/dist/write/runtime.d.ts +37 -0
- package/dist/write/runtime.js +72 -0
- package/dist/write/store/audit-log.d.ts +13 -0
- package/dist/write/store/audit-log.js +25 -0
- package/dist/write/store/constants.d.ts +34 -0
- package/dist/write/store/constants.js +35 -0
- package/dist/write/store/files.d.ts +44 -0
- package/dist/write/store/files.js +157 -0
- package/dist/write/store/heartbeat.d.ts +9 -0
- package/dist/write/store/heartbeat.js +65 -0
- package/dist/write/store/ledger.d.ts +15 -0
- package/dist/write/store/ledger.js +86 -0
- package/dist/write/store/lifecycle.d.ts +35 -0
- package/dist/write/store/lifecycle.js +114 -0
- package/dist/write/store/lock.d.ts +97 -0
- package/dist/write/store/lock.js +464 -0
- package/dist/write/store/op-lock.d.ts +13 -0
- package/dist/write/store/op-lock.js +175 -0
- package/dist/write/store/plan-store.d.ts +7 -0
- package/dist/write/store/plan-store.js +48 -0
- package/dist/write/store/plans.d.ts +5 -0
- package/dist/write/store/plans.js +19 -0
- package/dist/write/store/types.d.ts +195 -0
- package/dist/write/store/types.js +2 -0
- package/dist/write/store.d.ts +6 -0
- package/dist/write/store.js +182 -0
- package/examples/agentgateway.write-gate.yaml +29 -0
- package/package.json +71 -0
- package/server.json +69 -0
- package/skills/ar-aging.md +65 -0
- package/skills/company-360.md +69 -0
- package/skills/contract-profitability.md +65 -0
- package/skills/crm-management.md +87 -0
- package/skills/filter-semantics.md +75 -0
- package/skills/invoice-export.md +61 -0
- package/skills/log-time-entry.md +77 -0
- package/skills/non-chargeable-work.md +67 -0
- package/skills/portfolio-margin.md +66 -0
- package/skills/recurring-revenue.md +65 -0
- package/skills/revenue-rollup.md +65 -0
- package/skills/slim-reads.md +67 -0
- package/skills/ticket-triage.md +64 -0
- package/skills/unbilled-work-review.md +66 -0
- package/skills/wip-hours.md +68 -0
package/dist/http.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* http.ts — the remote transport: streamable HTTP.
|
|
3
|
+
*
|
|
4
|
+
* Many MCP clients speak streamable HTTP only (one POST endpoint), so this transport is not
|
|
5
|
+
* optional for that consumer. The caller's per-request Autotask credential tuple in the
|
|
6
|
+
* `X-Autotask-*` headers — together with the origin in `X-Autotask-Base-Url` — is what the tools
|
|
7
|
+
* use to reach Autotask, unless the optional server-held defaults fill them in (presented to the
|
|
8
|
+
* default origin only) — see `src/auth.ts` and the scope resolver in `src/tools/context/scope.ts`.
|
|
9
|
+
* The transport boundary is the network: the listener must stay on a private, unpublished network.
|
|
10
|
+
*
|
|
11
|
+
* A request with no Autotask credentials is allowed through so the SDK can serve
|
|
12
|
+
* `initialize`/`tools/list` for a catalog sync; it resolves to a fail-closed placeholder client
|
|
13
|
+
* that answers its typed refusal on any tool call (zero vendor wire), so no caller borrows an
|
|
14
|
+
* identity and no tool call reaches the vendor without credentials.
|
|
15
|
+
*/
|
|
16
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
17
|
+
import { createServer } from 'node:http';
|
|
18
|
+
import { Readable } from 'node:stream';
|
|
19
|
+
import { pipeline } from 'node:stream/promises';
|
|
20
|
+
import { serverCredentialDefaults } from './config/load.js';
|
|
21
|
+
import {} from './config/schema.js';
|
|
22
|
+
import { runDoctor } from './doctor.js';
|
|
23
|
+
import { SERVER_IDENTITY } from './tools/server.js';
|
|
24
|
+
import { describeSurface } from './tools/surface.js';
|
|
25
|
+
import { readRequestScope } from './auth.js';
|
|
26
|
+
import { scrubSecrets } from './tools/results/errors.js';
|
|
27
|
+
import { createMcpGuard, MAX_BODY_BYTES } from './http-guard.js';
|
|
28
|
+
import { AUTOTASK_BASE_URL_HEADER, AUTOTASK_IMPERSONATION_HEADER, AUTOTASK_INTEGRATION_CODE_HEADER, AUTOTASK_SECRET_HEADER, AUTOTASK_USERNAME_HEADER, } from './auth.js';
|
|
29
|
+
/** The headers that carry per-request scope, and so must never be read from a duplicated pair. */
|
|
30
|
+
const CREDENTIAL_HEADERS = new Set([
|
|
31
|
+
AUTOTASK_INTEGRATION_CODE_HEADER,
|
|
32
|
+
AUTOTASK_USERNAME_HEADER,
|
|
33
|
+
AUTOTASK_SECRET_HEADER,
|
|
34
|
+
AUTOTASK_IMPERSONATION_HEADER,
|
|
35
|
+
AUTOTASK_BASE_URL_HEADER,
|
|
36
|
+
]);
|
|
37
|
+
/** The orchestrator probe paths (the published contract — none of them call the vendor). */
|
|
38
|
+
export const HEALTH_PATH = '/health';
|
|
39
|
+
export const READY_PATH = '/ready';
|
|
40
|
+
export const METADATA_PATH = '/metadata';
|
|
41
|
+
/**
|
|
42
|
+
* The zero-wire credential preflight route (issue #5).
|
|
43
|
+
*
|
|
44
|
+
* Same trust model as {@link READY_PATH}: answered before the MCP handler, never authenticated, and
|
|
45
|
+
* never touching Autotask. It reports the shape of the SERVER-HELD credential only — the caller's
|
|
46
|
+
* own per-request credential is checked at the tool boundary, one request at a time, and is
|
|
47
|
+
* deliberately not echoed back to the caller that sent it. Reporting shape facts (a length, a
|
|
48
|
+
* two-character prefix — masked for the secret — and anomaly names) about the server's own
|
|
49
|
+
* environment is therefore not a disclosure: the caller that can reach this listener is the operator
|
|
50
|
+
* who set that environment.
|
|
51
|
+
*/
|
|
52
|
+
export const DOCTOR_PATH = '/doctor';
|
|
53
|
+
/**
|
|
54
|
+
* The `/metadata` payload: the server identity + the MCP protocol baseline + the capability
|
|
55
|
+
* manifest reference, read from `server.json` (the machine-readable surface file) when present.
|
|
56
|
+
* Served verbatim — it is the documented identity, not a re-derivation.
|
|
57
|
+
*/
|
|
58
|
+
export function loadMetadata(fallback, config) {
|
|
59
|
+
// The deployment block: what THIS process serves (the profile, its toolsets, whether a write gate is configured)
|
|
60
|
+
// and who authenticates and rate-limits callers on HTTP.
|
|
61
|
+
const deployment = config === undefined
|
|
62
|
+
? {}
|
|
63
|
+
: {
|
|
64
|
+
deployment: {
|
|
65
|
+
profile: config.AUTOTASK_PROFILE,
|
|
66
|
+
toolsets: ['core', ...config.AUTOTASK_TOOLSETS],
|
|
67
|
+
// #302: on HTTP the server never asks a person; the MCP client or gateway owns human approval
|
|
68
|
+
...(config.AUTOTASK_PROFILE === 'operator' ? { writeGate: 'client' } : {}),
|
|
69
|
+
...(config.AUTOTASK_HTTP_AUTH === undefined
|
|
70
|
+
? {}
|
|
71
|
+
: {
|
|
72
|
+
callerAuth: config.AUTOTASK_HTTP_AUTH,
|
|
73
|
+
rateLimiting: config.AUTOTASK_HTTP_AUTH === 'gateway' ? 'delegated to the gateway' : `in-process, ${config.AUTOTASK_HTTP_RATE_PER_MIN} requests per minute per principal`,
|
|
74
|
+
}),
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
const buildStamp = {
|
|
78
|
+
// The build identity is stamped by the server, not by the manifest file. FR-2: the era pair
|
|
79
|
+
// (modern baseline + legacy fallback) is stamped at BOTH levels — the server.json top level
|
|
80
|
+
// and this build block must agree.
|
|
81
|
+
name: fallback.name,
|
|
82
|
+
version: fallback.version,
|
|
83
|
+
mcpProtocolBaseline: fallback.mcpProtocolBaseline,
|
|
84
|
+
legacyProtocolFallback: fallback.legacyProtocolFallback,
|
|
85
|
+
};
|
|
86
|
+
try {
|
|
87
|
+
const here = import.meta.url;
|
|
88
|
+
// dist/http.js -> the package root (dist/ is one level up): server.json ships at the root.
|
|
89
|
+
const candidates = [new URL('../server.json', here), new URL('../../server.json', here)];
|
|
90
|
+
for (const url of candidates) {
|
|
91
|
+
try {
|
|
92
|
+
const text = readFileSyncIfPresent(new URL(url.href).pathname);
|
|
93
|
+
if (text !== undefined) {
|
|
94
|
+
const parsed = JSON.parse(text);
|
|
95
|
+
return { ...parsed, build: buildStamp, ...deployment };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// A malformed manifest must not take the probes down: fall through to the next candidate.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// No import.meta.url (e.g. a test harness): fall through to the fallback identity.
|
|
105
|
+
}
|
|
106
|
+
return { ...buildStamp, ...deployment };
|
|
107
|
+
}
|
|
108
|
+
/** Read a package-root JSON file when it exists (undefined when absent — the probes stay up). */
|
|
109
|
+
function readFileSyncIfPresent(path) {
|
|
110
|
+
return existsSync(path) ? readFileSync(path, 'utf8') : undefined;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Build the fetch-level request handler: `/health` and `/ready`, then (behind the guard, when one
|
|
114
|
+
* is given: Host/Origin validation, caller auth and the rate limit) `/metadata`, `/doctor` and MCP.
|
|
115
|
+
*
|
|
116
|
+
* Split out from the listener so the request path is testable without binding a port.
|
|
117
|
+
*/
|
|
118
|
+
export function createFetchHandler(mcp, metadata, doctor, guard, ready) {
|
|
119
|
+
return async function handle(request) {
|
|
120
|
+
const url = new URL(request.url);
|
|
121
|
+
// The orchestrator probes: pre-auth, and they must not touch the vendor — a zone outage
|
|
122
|
+
// would otherwise cycle the container, turning a partial upstream failure into a total
|
|
123
|
+
// local one. `/health` = process alive; `/ready` = config valid, plan pin checked, factory
|
|
124
|
+
// built (reaching this handler proves all three — there is no live vendor call: credentials
|
|
125
|
+
// are request-scoped). They answer a fixed status only, so they stay outside the guard.
|
|
126
|
+
if (url.pathname === HEALTH_PATH) {
|
|
127
|
+
return Response.json({ status: 'ok' });
|
|
128
|
+
}
|
|
129
|
+
if (url.pathname === READY_PATH) {
|
|
130
|
+
// Operator deployments ride the state-lock facts on /ready (issue #55): the orchestrator
|
|
131
|
+
// can tell a stale holder (lease expired) from a live one without any other channel.
|
|
132
|
+
// Readonly deployments have no state dir and keep the fixed payload.
|
|
133
|
+
const lock = ready === undefined ? undefined : ready();
|
|
134
|
+
return Response.json(lock === undefined ? { status: 'ready' } : { status: 'ready', lock });
|
|
135
|
+
}
|
|
136
|
+
// The guard (A12, review F5): Host/Origin first (DNS rebinding), then the caller's bearer
|
|
137
|
+
// token and its rate limit in tokens mode — for `/mcp` and for the two routes that describe
|
|
138
|
+
// the deployment: `/metadata` (profile, toolsets, auth mode) and `/doctor` (the shape of the
|
|
139
|
+
// server-held credential). No check for the Autotask credential headers: a request with none
|
|
140
|
+
// is let through so the SDK can answer `initialize`/`tools/list`, which never reach the
|
|
141
|
+
// vendor; the per-request factory resolves it to a fail-closed placeholder, so every tool
|
|
142
|
+
// call fails closed and no caller borrows an identity.
|
|
143
|
+
if (guard !== undefined) {
|
|
144
|
+
const verdict = guard.check(request);
|
|
145
|
+
if (verdict instanceof Response)
|
|
146
|
+
return verdict;
|
|
147
|
+
}
|
|
148
|
+
if (url.pathname === METADATA_PATH) {
|
|
149
|
+
return Response.json(metadata);
|
|
150
|
+
}
|
|
151
|
+
// Credential shape + host policy + the plan-hash gate, still no Autotask. `dialed: 0` is a
|
|
152
|
+
// property of the implementation (see `src/doctor.ts`, which holds no client), not a counter
|
|
153
|
+
// that a bug could leave at zero.
|
|
154
|
+
if (url.pathname === DOCTOR_PATH && doctor !== undefined) {
|
|
155
|
+
return Response.json(doctor());
|
|
156
|
+
}
|
|
157
|
+
return mcp.fetch(request);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Convert a Node request to a web Request for the MCP handler.
|
|
162
|
+
*
|
|
163
|
+
* A scope credential presented more than once is dropped, never combined: Node joins a duplicated
|
|
164
|
+
* custom header with ", " in `req.headers`, and a combined pair would look like one well-formed
|
|
165
|
+
* credential and pass a non-blank check. The distinct view keeps them apart so a credential
|
|
166
|
+
* presented twice is treated as absent (the all-or-nothing rule in `auth.ts`).
|
|
167
|
+
*/
|
|
168
|
+
/** Thrown while reading a body over {@link MAX_BODY_BYTES}: answered 413. */
|
|
169
|
+
class BodyTooLarge extends Error {
|
|
170
|
+
}
|
|
171
|
+
async function toWebRequest(req, port) {
|
|
172
|
+
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? `localhost:${port}`}`);
|
|
173
|
+
const headers = new Headers();
|
|
174
|
+
// Iterate `headersDistinct`, not `headers` — see the note above.
|
|
175
|
+
for (const [name, values] of Object.entries(req.headersDistinct)) {
|
|
176
|
+
if (values === undefined || values.length === 0)
|
|
177
|
+
continue;
|
|
178
|
+
if (values.length > 1) {
|
|
179
|
+
if (CREDENTIAL_HEADERS.has(name))
|
|
180
|
+
continue;
|
|
181
|
+
for (const one of values)
|
|
182
|
+
headers.append(name, one);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
headers.set(name, values[0]);
|
|
186
|
+
}
|
|
187
|
+
if (req.method === 'GET' || req.method === 'HEAD')
|
|
188
|
+
return new Request(url, { method: req.method, headers });
|
|
189
|
+
// M10: the body is capped at 1 MiB, by its declared length and again while it streams (a
|
|
190
|
+
// missing or false Content-Length cannot buy an unbounded buffer).
|
|
191
|
+
if (Number(req.headers['content-length'] ?? 0) > MAX_BODY_BYTES)
|
|
192
|
+
throw new BodyTooLarge();
|
|
193
|
+
const chunks = [];
|
|
194
|
+
let size = 0;
|
|
195
|
+
for await (const chunk of req) {
|
|
196
|
+
size += chunk.length;
|
|
197
|
+
if (size > MAX_BODY_BYTES)
|
|
198
|
+
throw new BodyTooLarge();
|
|
199
|
+
chunks.push(Buffer.from(chunk));
|
|
200
|
+
}
|
|
201
|
+
return new Request(url, { method: req.method, headers, body: Buffer.concat(chunks).toString('utf8') });
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Stream a web Response into the Node response — incrementally, never buffered.
|
|
205
|
+
*
|
|
206
|
+
* Buffering would deliver nothing to the client until the upstream body closed, hanging any
|
|
207
|
+
* long-lived or incremental body.
|
|
208
|
+
*/
|
|
209
|
+
async function send(res, response) {
|
|
210
|
+
res.statusCode = response.status;
|
|
211
|
+
response.headers.forEach((value, name) => res.setHeader(name, value));
|
|
212
|
+
if (response.body === null || res.req.method === 'HEAD') {
|
|
213
|
+
res.end();
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
await pipeline(Readable.fromWeb(response.body), res);
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// Status and headers are already on the wire; pipeline has destroyed both ends.
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Bind the listener. `mcp` is supplied by the caller so this module never builds tools itself.
|
|
225
|
+
*
|
|
226
|
+
* The bind address is `config.MCP_HOST` (`--host`, default `127.0.0.1`). `tokens` is the loaded
|
|
227
|
+
* tokens file in `tokens` mode. `exit` is a parameter only so a test can watch a listen failure
|
|
228
|
+
* without killing the test runner.
|
|
229
|
+
*/
|
|
230
|
+
export function startHttpServer(config, mcp, log, tokens, exit = process.exit, env = process.env, ready) {
|
|
231
|
+
const metadata = loadMetadata(SERVER_IDENTITY, config);
|
|
232
|
+
const host = config.MCP_HOST;
|
|
233
|
+
// A builder, not a constant: the route reports THIS process's parsed config, and nothing is read
|
|
234
|
+
// until a request arrives (so the route stays credential-free at rest).
|
|
235
|
+
const handle = createFetchHandler(mcp, metadata, () => runDoctor(config, env, describeSurface(config)), createMcpGuard(config, tokens), ready);
|
|
236
|
+
const server = createServer((req, res) => {
|
|
237
|
+
void toWebRequest(req, config.PORT)
|
|
238
|
+
.then(handle)
|
|
239
|
+
.then((response) => send(res, response))
|
|
240
|
+
.catch((err) => {
|
|
241
|
+
if (err instanceof BodyTooLarge) {
|
|
242
|
+
// The request is not read further; the connection closes after the answer.
|
|
243
|
+
res.statusCode = 413;
|
|
244
|
+
res.setHeader('Connection', 'close');
|
|
245
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: `Request body over ${MAX_BODY_BYTES} bytes` }, id: null }));
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Never echo the error to the caller: it can carry internal detail. Security R2: an
|
|
249
|
+
// out-of-handler failure can carry vendor text echoing a request value (the SDK's
|
|
250
|
+
// name-based redaction is a no-op on free text), so the logged message is value-scrubbed
|
|
251
|
+
// against the request's own credential values (single-valued header view) + the server
|
|
252
|
+
// defaults — the same control as the FT-5 error wrap.
|
|
253
|
+
const scope = readRequestScope(req.headers);
|
|
254
|
+
const defaults = serverCredentialDefaults(config);
|
|
255
|
+
const secrets = [];
|
|
256
|
+
for (const v of [
|
|
257
|
+
scope.apiIntegrationCode,
|
|
258
|
+
scope.userName,
|
|
259
|
+
scope.secret,
|
|
260
|
+
scope.impersonationResourceId,
|
|
261
|
+
defaults?.apiIntegrationCode,
|
|
262
|
+
defaults?.userName,
|
|
263
|
+
defaults?.secret,
|
|
264
|
+
defaults?.impersonationResourceId,
|
|
265
|
+
]) {
|
|
266
|
+
if (typeof v === 'string' && v.length > 0)
|
|
267
|
+
secrets.push(v);
|
|
268
|
+
}
|
|
269
|
+
log.error('request failed', { err: scrubSecrets(err instanceof Error ? err.message : String(err), secrets) });
|
|
270
|
+
if (!res.headersSent) {
|
|
271
|
+
res.statusCode = 500;
|
|
272
|
+
res.end('internal error');
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
res.destroy();
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
// Without a listener here, a bind failure (EADDRINUSE, EACCES on a privileged port) is an
|
|
280
|
+
// unhandled 'error' event and Node rethrows it as a raw stack trace. It is the same class of
|
|
281
|
+
// boot failure as an invalid config: name the problem, exit non-zero, so an orchestrator sees a
|
|
282
|
+
// failed container rather than a healthy-but-useless one.
|
|
283
|
+
server.on('error', (err) => {
|
|
284
|
+
log.error('listen failed', { port: config.PORT, host, err: err.message });
|
|
285
|
+
exit(1);
|
|
286
|
+
});
|
|
287
|
+
server.listen(config.PORT, host, () => log.info('listening', { port: config.PORT, host, transport: 'http' }));
|
|
288
|
+
return server;
|
|
289
|
+
}
|
|
290
|
+
//# sourceMappingURL=http.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lifecycle.ts — process-level crash, signal and exit logging for the http transport.
|
|
3
|
+
*
|
|
4
|
+
* Node's default SIGTERM handling is silent: a killed container leaves zero log lines, and the
|
|
5
|
+
* only way to learn the process died was to watch the port free (a server that died mid-run left no crash line at all). The http transport installs process-level handlers here so a crash,
|
|
6
|
+
* a signal or a clean exit always leaves a record in the server log:
|
|
7
|
+
*
|
|
8
|
+
* - `uncaughtException` / `unhandledRejection` → a structured error line, then exit 1
|
|
9
|
+
* - `SIGTERM` / `SIGINT` → a "shutting down" line (signal + exit code), a short grace period for
|
|
10
|
+
* in-flight work, a final "server closed" line, then exit 0
|
|
11
|
+
*
|
|
12
|
+
* The stdio transport keeps its own handler in main.ts, unchanged: its process life is tied to
|
|
13
|
+
* the client, and no orchestrator signals it.
|
|
14
|
+
*/
|
|
15
|
+
import type { Logger } from './logger.js';
|
|
16
|
+
/** The slice of `node:http`'s Server that shutdown needs: stop accepting, then force-close sockets. */
|
|
17
|
+
export interface CloseableServer {
|
|
18
|
+
close(callback?: (err?: Error) => void): void;
|
|
19
|
+
closeAllConnections?(): void;
|
|
20
|
+
}
|
|
21
|
+
/** How long shutdown waits for in-flight work before force-closing keep-alive sockets. */
|
|
22
|
+
export declare const SHUTDOWN_GRACE_MS = 2000;
|
|
23
|
+
/**
|
|
24
|
+
* Install the process-level lifecycle handlers for the http transport.
|
|
25
|
+
*
|
|
26
|
+
* `exit` is a parameter so a test can watch the code without killing the test runner — the same
|
|
27
|
+
* pattern as `startHttpServer`'s listen-failure path.
|
|
28
|
+
*/
|
|
29
|
+
export declare function installHttpLifecycle(server: CloseableServer, log: Logger, exit?: (code: number) => void): void;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** How long shutdown waits for in-flight work before force-closing keep-alive sockets. */
|
|
2
|
+
export const SHUTDOWN_GRACE_MS = 2000;
|
|
3
|
+
/**
|
|
4
|
+
* Install the process-level lifecycle handlers for the http transport.
|
|
5
|
+
*
|
|
6
|
+
* `exit` is a parameter so a test can watch the code without killing the test runner — the same
|
|
7
|
+
* pattern as `startHttpServer`'s listen-failure path.
|
|
8
|
+
*/
|
|
9
|
+
export function installHttpLifecycle(server, log, exit = process.exit) {
|
|
10
|
+
// Node's default unhandledRejection handling already terminates — silently. The handler turns
|
|
11
|
+
// that into a log line and an explicit exit code; uncaughtException gets the same treatment.
|
|
12
|
+
process.on('uncaughtException', (err) => {
|
|
13
|
+
log.error('uncaught exception', { err: describe(err) });
|
|
14
|
+
exit(1);
|
|
15
|
+
});
|
|
16
|
+
process.on('unhandledRejection', (reason) => {
|
|
17
|
+
log.error('unhandled rejection', { err: describe(reason) });
|
|
18
|
+
exit(1);
|
|
19
|
+
});
|
|
20
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
21
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
22
|
+
// A second signal mid-shutdown is a nudge, not a new shutdown: without the guard the log would
|
|
23
|
+
// carry two "shutting down" lines and two forced exits.
|
|
24
|
+
let shuttingDown = false;
|
|
25
|
+
function shutdown(signal) {
|
|
26
|
+
if (shuttingDown)
|
|
27
|
+
return;
|
|
28
|
+
shuttingDown = true;
|
|
29
|
+
log.info('shutting down', { signal, exitCode: 0 });
|
|
30
|
+
let finished = false;
|
|
31
|
+
const finish = () => {
|
|
32
|
+
if (finished)
|
|
33
|
+
return;
|
|
34
|
+
finished = true;
|
|
35
|
+
log.info('server closed', { signal });
|
|
36
|
+
exit(0);
|
|
37
|
+
};
|
|
38
|
+
server.close(() => finish());
|
|
39
|
+
// MCP clients hold keep-alive connections, which can hold `close` open indefinitely. After
|
|
40
|
+
// the grace window force-close them and finish no matter what `close` says. `unref` keeps
|
|
41
|
+
// the timer from pinning the event loop on the fast path.
|
|
42
|
+
setTimeout(() => {
|
|
43
|
+
server.closeAllConnections?.();
|
|
44
|
+
finish();
|
|
45
|
+
}, SHUTDOWN_GRACE_MS).unref();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** An Error as its stack (or message); anything else stringified. Same shape as main.ts' stdio handler. */
|
|
49
|
+
function describe(value) {
|
|
50
|
+
return value instanceof Error ? (value.stack ?? value.message) : String(value);
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=lifecycle.js.map
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* logger.ts — structured JSON logs to stdout, one object per line.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately tiny: a container's log collector wants newline-delimited JSON on stdout and nothing
|
|
5
|
+
* else. No dependency, no transports, no file rotation.
|
|
6
|
+
*
|
|
7
|
+
* On the stdio transport, stdout IS the MCP protocol channel — writing logs there would corrupt
|
|
8
|
+
* every message. Logs go to stderr in that case; see {@link createLogger}.
|
|
9
|
+
*/
|
|
10
|
+
export declare const LEVELS: readonly ["debug", "info", "warn", "error"];
|
|
11
|
+
export type Level = (typeof LEVELS)[number];
|
|
12
|
+
export interface Logger {
|
|
13
|
+
debug(msg: string, fields?: Record<string, unknown>): void;
|
|
14
|
+
info(msg: string, fields?: Record<string, unknown>): void;
|
|
15
|
+
warn(msg: string, fields?: Record<string, unknown>): void;
|
|
16
|
+
error(msg: string, fields?: Record<string, unknown>): void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* @param minLevel messages below this are dropped.
|
|
20
|
+
* @param write sink for one complete line. Defaults to stderr, which is always safe: on the stdio
|
|
21
|
+
* transport stdout carries the MCP protocol itself, so a log line written there would be parsed
|
|
22
|
+
* as a protocol message and break the session. The transport decides the sink (security V27):
|
|
23
|
+
* under http the caller passes stdout (the container's NDJSON log channel); under stdio the
|
|
24
|
+
* default (stderr) stands.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createLogger(minLevel?: Level, write?: (line: string) => void): Logger;
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* logger.ts — structured JSON logs to stdout, one object per line.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately tiny: a container's log collector wants newline-delimited JSON on stdout and nothing
|
|
5
|
+
* else. No dependency, no transports, no file rotation.
|
|
6
|
+
*
|
|
7
|
+
* On the stdio transport, stdout IS the MCP protocol channel — writing logs there would corrupt
|
|
8
|
+
* every message. Logs go to stderr in that case; see {@link createLogger}.
|
|
9
|
+
*/
|
|
10
|
+
export const LEVELS = ['debug', 'info', 'warn', 'error'];
|
|
11
|
+
/**
|
|
12
|
+
* @param minLevel messages below this are dropped.
|
|
13
|
+
* @param write sink for one complete line. Defaults to stderr, which is always safe: on the stdio
|
|
14
|
+
* transport stdout carries the MCP protocol itself, so a log line written there would be parsed
|
|
15
|
+
* as a protocol message and break the session. The transport decides the sink (security V27):
|
|
16
|
+
* under http the caller passes stdout (the container's NDJSON log channel); under stdio the
|
|
17
|
+
* default (stderr) stands.
|
|
18
|
+
*/
|
|
19
|
+
export function createLogger(minLevel = 'info', write = (l) => process.stderr.write(l + '\n')) {
|
|
20
|
+
const threshold = LEVELS.indexOf(minLevel);
|
|
21
|
+
const at = (level) => (msg, fields) => {
|
|
22
|
+
if (LEVELS.indexOf(level) < threshold)
|
|
23
|
+
return;
|
|
24
|
+
write(JSON.stringify({ ts: new Date().toISOString(), level, msg, ...fields }));
|
|
25
|
+
};
|
|
26
|
+
return { debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=logger.js.map
|
package/dist/main.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type Config } from './config/schema.js';
|
|
3
|
+
import { type Logger } from './logger.js';
|
|
4
|
+
import { type StdioServerHandle } from '@modelcontextprotocol/server/stdio';
|
|
5
|
+
import { type WriteRuntime } from './write/runtime.js';
|
|
6
|
+
/**
|
|
7
|
+
* Serve MCP over this process's stdin/stdout.
|
|
8
|
+
*
|
|
9
|
+
* Returns the handle rather than awaiting anything: `serveStdio` owns the transport for the life of
|
|
10
|
+
* the process, and the caller needs the handle only to close it on a fatal error.
|
|
11
|
+
*/
|
|
12
|
+
export declare function startStdio(config: Config, log: Logger, write?: WriteRuntime): StdioServerHandle;
|