Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,16 @@ MCP_RATE_LIMIT_PER_MINUTE=60
# HEALTH_HEAP_PERCENT /health reports the process down at or above this, so
# a probe sees the decline before the crash. 0 disables.
# Default 90.
# NODE_MAX_SEMI_SPACE_MB V8 young-generation semi-space in MB (start.sh passes
# --max-semi-space-size). Unset or 0 keeps V8's default
# of 16. A busy instance promotes the garbage of every
# tool call to the old space with that default; 64
# makes the old-space collections that stall the event
# loop rarer (the `gc` block of the vitals line shows
# them). Costs about three times its value in RSS.
# Cloud default 64 (docker-compose.cloud.yml).
# VITALS_INTERVAL_SEC=30
# NODE_MAX_SEMI_SPACE_MB=64
# HEAP_WARN_PERCENT=75
# HEAP_SNAPSHOT_PERCENT=0
# HEAP_SNAPSHOT_DIR=/tmp/anythingmcp-diagnostics
Expand Down
31 changes: 27 additions & 4 deletions deploy/cloud/Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,31 @@
}
}

# Idle upstream connections are dropped after 55 s, before the app drops
# them itself: the backend at 65 s (keepAliveTimeout, main.ts), the frontend
# at 65 s (KEEP_ALIVE_TIMEOUT, docker-compose.cloud.yml). With Caddy's
# default of 2 minutes the app closed first, and a POST sent on a connection
# it had just closed came back as a 502 "connection reset by peer" (the
# uptime probe's /mcp/demo call on 2026-12-06 07:36 UTC, right after a long
# GC pause had let the backend's idle timers expire all at once).
(upstream_keepalive) {
transport http {
keepalive 55s
}
}

(backend) {
@blue vars amcp_colour blue
@green vars amcp_colour green
handle @blue {
reverse_proxy backend-blue:4000
reverse_proxy backend-blue:4000 {
import upstream_keepalive
}
}
handle @green {
reverse_proxy backend-green:4000
reverse_proxy backend-green:4000 {
import upstream_keepalive
}
}
handle {
respond "No live release selected" 503
Expand All @@ -59,10 +76,14 @@
@blue vars amcp_colour blue
@green vars amcp_colour green
handle @blue {
reverse_proxy frontend-blue:3000
reverse_proxy frontend-blue:3000 {
import upstream_keepalive
}
}
handle @green {
reverse_proxy frontend-green:3000
reverse_proxy frontend-green:3000 {
import upstream_keepalive
}
}
handle {
respond "No live release selected" 503
Expand Down Expand Up @@ -233,13 +254,15 @@
header_up -X-Forwarded-For
header_up -X-Real-IP
header_up -Forwarded
import upstream_keepalive
}
}
handle @green {
reverse_proxy frontend-green:3000 {
header_up -X-Forwarded-For
header_up -X-Real-IP
header_up -Forwarded
import upstream_keepalive
}
}
handle {
Expand Down
11 changes: 11 additions & 0 deletions docker-compose.cloud.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ x-backend: &backend
# .env when the host has the RAM to back it — roughly half of total is a
# safe ceiling, since postgres, redis, motis and caddy share the box.
- NODE_MAX_OLD_SPACE_MB=${NODE_MAX_OLD_SPACE_MB:-2048}
# V8 semi-space (young generation) in MB, read by start.sh; 0 keeps V8's
# default of 16. 64 keeps the garbage of a tool call out of the old
# space, so the old-space collections that stall the event loop come
# less often (reasoning in start.sh). The `gc` block of the vitals log
# line shows the effect.
- NODE_MAX_SEMI_SPACE_MB=${NODE_MAX_SEMI_SPACE_MB:-64}
# Heap guard (packages/backend/src/common/process-vitals.ts; every var
# documented in .env.example). The snapshot stays OFF here: on a heap
# this size V8's snapshot builder is what pushed RSS into the cgroup
Expand Down Expand Up @@ -358,6 +364,11 @@ x-frontend: &frontend
environment:
- NODE_ENV=production
- NEXT_PUBLIC_API_URL=https://${DOMAIN}
# Next's standalone server closes idle keep-alive connections after 5 s
# unless told otherwise. Caddy reuses them for longer, and a POST sent
# on a connection just closed came back as a 502. 65 s, as the backend
# has; Caddy lets go first, at 55 s (deploy/cloud/Caddyfile).
- KEEP_ALIVE_TIMEOUT=65000
- GTM_ID=${GTM_ID:-}
- COOKIE_DOMAIN=${COOKIE_DOMAIN:-}
# Sentry: server runtime, and handed to the browser by the root layout
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "anythingmcp",
"version": "0.55.23",
"version": "0.55.24",
"description": "Turn any REST/OpenAPI, SOAP/WSDL, GraphQL, OData or SQL API into MCP tools for Claude, ChatGPT and Copilot, no code. 977 pre-built adapters for ERP, e-commerce and more (SAP S/4HANA, SAP Business One, Odoo, Xentral, JTL-Wawi, Shopware, WooCommerce, Amazon Seller). Self-hosted, open source (AGPL-3.0).",
"private": true,
"license": "AGPL-3.0-only",
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anythingmcp/backend",
"version": "0.55.23",
"version": "0.55.24",
"description": "AnythingMCP — NestJS Backend + Dynamic MCP Server",
"private": true,
"license": "AGPL-3.0-only",
Expand Down
23 changes: 21 additions & 2 deletions packages/backend/src/common/process-vitals.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { mkdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { monitorEventLoopDelay, IntervalHistogram } from 'node:perf_hooks';
import { monitorEventLoopDelay, IntervalHistogram, PerformanceObserver } from 'node:perf_hooks';
import * as v8 from 'node:v8';
import {
evaluateHeap,
gcKind,
GcWindow,
HeapPolicy,
HeapSample,
HeapState,
Expand Down Expand Up @@ -70,7 +72,8 @@ const mb = (n: number | undefined) => (n === undefined ? undefined : Math.round(
* What it does each tick:
*
* 1. read memory, the heap limit, the cgroup limit, event-loop delay,
* active handles and the live gauges other modules maintain;
* garbage-collection pauses by kind, active handles and the live gauges
* other modules maintain;
* 2. log them as one structured line, so the trend before any incident is
* in the log rather than reconstructed from `docker stats` afterwards;
* 3. warn once when the heap crosses HEAP_WARN_PERCENT;
Expand All @@ -90,6 +93,9 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(ProcessVitalsService.name);
private timer?: ReturnType<typeof setInterval>;
private loopDelay?: IntervalHistogram;
private gcObserver?: PerformanceObserver;
/** Public so tests can feed collections without a real GC. */
readonly gc = new GcWindow();
private state: HeapState = { ...INITIAL_HEAP_STATE };
private exitRequested = false;
private rssLimit: number | undefined;
Expand All @@ -109,6 +115,17 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy {
}
this.loopDelay = monitorEventLoopDelay({ resolution: 20 });
this.loopDelay.enable();
try {
this.gcObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
this.gc.record(gcKind((entry as { detail?: { kind?: unknown } }).detail?.kind), entry.duration);
}
});
this.gcObserver.observe({ entryTypes: ['gc'] });
} catch (err) {
// Diagnostics only: a runtime without GC entries still gets its vitals.
this.logger.warn(`GC observer not available: ${(err as Error)?.message ?? err}`);
}
this.rssLimit = this.collector.rssLimit();

const limit = this.collector.heapLimit();
Expand All @@ -128,6 +145,7 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy {
onModuleDestroy(): void {
if (this.timer) clearInterval(this.timer);
this.loopDelay?.disable();
this.gcObserver?.disconnect();
}

/** One tick. Never throws: a diagnostics failure must not become an outage. */
Expand Down Expand Up @@ -176,6 +194,7 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy {
activeResources: resources.length,
activeByType: byType,
eventLoop: loop,
gc: this.gc.snapshotAndReset(),
gauges: processGauges.snapshot(),
};
// An object message: nestjs-pino merges it into the JSON line, so every
Expand Down
36 changes: 36 additions & 0 deletions packages/backend/src/common/process-vitals.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {
evaluateHeap,
gcKind,
GcWindow,
heapStatus,
HeapPolicy,
INITIAL_HEAP_STATE,
Expand Down Expand Up @@ -227,6 +229,26 @@ describe('ProcessGauges', () => {
});
});

describe('GcWindow', () => {
it('counts collections by kind, keeps the longest, and starts over after a snapshot', () => {
const gc = new GcWindow();
gc.record('major', 1200.4);
gc.record('major', 8100.2);
gc.record('minor', 3.2);
gc.record('minor', NaN);
gc.record('minor', -1);
expect(gc.snapshotAndReset()).toEqual({
major: { count: 2, totalMs: 9301, maxMs: 8100 },
minor: { count: 1, totalMs: 3, maxMs: 3 },
});
expect(gc.snapshotAndReset()).toEqual({});
});

it('maps perf_hooks GC kinds', () => {
expect([1, 4, 8, 16, undefined].map(gcKind)).toEqual(['minor', 'major', 'incremental', 'other', 'other']);
});
});

describe('ProcessVitalsService.tick', () => {
function service(samples: Array<{ heapPct: number; rss?: number }>, overrides: Partial<HeapPolicy> = {}) {
const svc = new ProcessVitalsService();
Expand Down Expand Up @@ -267,6 +289,20 @@ describe('ProcessVitalsService.tick', () => {
expect(typeof line.vitals.rssPercent).toBe('number');
expect(line.vitals.activeByType).toEqual({ TCPSocketWrap: 2, Timeout: 1 });
expect(typeof line.vitals.gauges).toBe('object');
expect(line.vitals.gc).toEqual({});
});

it('reports the GC pauses of the interval once', async () => {
const { svc, log } = service([{ heapPct: 40 }]);
svc.gc.record('major', 1500);
svc.gc.record('minor', 4);
await svc.tick();
await svc.tick();
expect(log.log.mock.calls[0][0].vitals.gc).toEqual({
major: { count: 1, totalMs: 1500, maxMs: 1500 },
minor: { count: 1, totalMs: 4, maxMs: 4 },
});
expect(log.log.mock.calls[1][0].vitals.gc).toEqual({});
});

it('pauses to flush the log before writing the snapshot, writes once, and requests exit once', async () => {
Expand Down
52 changes: 52 additions & 0 deletions packages/backend/src/common/process-vitals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,3 +299,55 @@ export class ProcessGauges {
}

export const processGauges = new ProcessGauges();

/** What one garbage collection was, as far as the vitals line cares. */
export type GcKind = 'major' | 'minor' | 'incremental' | 'other';

export interface GcKindStats {
count: number;
totalMs: number;
maxMs: number;
}

/**
* Garbage-collection pauses since the last vitals line.
*
* The event-loop delay in the vitals line says THAT the loop stalled; it
* cannot say why. On Cloud the long stalls (1-2 s with a 4 GB heap, up to
* 8 s with 6 GB, 2026-12-06) lined up with old-space collections, but that
* was read off heap sizes before and after, 30 s apart. Counting the
* collections themselves, by kind, makes the next heap or semi-space change
* a measurement instead of a guess: `major` is a stop-the-world old-space
* collection, `minor` a young-generation scavenge.
*/
export class GcWindow {
private stats = new Map<GcKind, GcKindStats>();

record(kind: GcKind, durationMs: number): void {
if (!Number.isFinite(durationMs) || durationMs < 0) return;
const s = this.stats.get(kind) ?? { count: 0, totalMs: 0, maxMs: 0 };
s.count += 1;
s.totalMs += durationMs;
if (durationMs > s.maxMs) s.maxMs = durationMs;
this.stats.set(kind, s);
}

/** The window so far, rounded to whole milliseconds; then starts a new one. */
snapshotAndReset(): Partial<Record<GcKind, GcKindStats>> {
const out: Partial<Record<GcKind, GcKindStats>> = {};
for (const [kind, s] of this.stats) {
out[kind] = { count: s.count, totalMs: Math.round(s.totalMs), maxMs: Math.round(s.maxMs) };
}
this.stats = new Map();
return out;
}
}

/** Map a `PerformanceEntry.detail.kind` of a `gc` entry (perf_hooks constants) to a GcKind. */
export function gcKind(kind: unknown): GcKind {
// NODE_PERFORMANCE_GC_MINOR = 1, _MAJOR = 4, _INCREMENTAL = 8, _WEAKCB = 16.
if (kind === 4) return 'major';
if (kind === 1) return 'minor';
if (kind === 8) return 'incremental';
return 'other';
}
2 changes: 1 addition & 1 deletion packages/frontend/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anythingmcp/frontend",
"version": "0.55.23",
"version": "0.55.24",
"description": "AnythingMCP — Next.js Admin UI",
"private": true,
"license": "AGPL-3.0-only",
Expand Down
2 changes: 1 addition & 1 deletion server.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/HelpCode-ai/anythingmcp",
"source": "github"
},
"version": "0.55.23",
"version": "0.55.24",
"websiteUrl": "https://anythingmcp.com",
"icons": [
{
Expand Down
15 changes: 14 additions & 1 deletion start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,20 @@ REPORT_FLAGS=""
if node --report-exclude-env -e 0 >/dev/null 2>&1; then
REPORT_FLAGS="--report-on-fatalerror --report-exclude-env --report-compact --report-directory=${HEAP_SNAPSHOT_DIR:-/tmp}"
fi
BACKEND_CMD="node --max-old-space-size=${NODE_MAX_OLD_SPACE_MB:-2048} ${REPORT_FLAGS} dist/src/main.js"
# Young generation. V8's default semi-space (16 MB) fills several times a
# second under load, so objects that live only as long as one tool call (a
# second or two) survive two scavenges and are promoted to the old space,
# which then needs frequent stop-the-world collections: on Cloud, 1-2 s every
# few minutes with a 4 GB heap, up to 8 s with 6 GB (2026-12-06). A larger
# semi-space lets request garbage die young. Opt-in via NODE_MAX_SEMI_SPACE_MB
# (MB, digits only); unset or 0 keeps V8's default. Costs about three times
# its value in RSS.
SEMI_SPACE_FLAG=""
case "${NODE_MAX_SEMI_SPACE_MB:-}" in
''|0|*[!0-9]*) ;;
*) SEMI_SPACE_FLAG="--max-semi-space-size=${NODE_MAX_SEMI_SPACE_MB}" ;;
esac
BACKEND_CMD="node --max-old-space-size=${NODE_MAX_OLD_SPACE_MB:-2048} ${SEMI_SPACE_FLAG} ${REPORT_FLAGS} dist/src/main.js"

case "$MODE" in
backend)
Expand Down
Loading