Files
DeepTutor/web/components/mcp/surface.ts
Bingxi Zhao (Frank) 44fa7a1552 release: v1.5.8
Memory. A v1.5.7 source deployment grew past 14 GB before V8 aborted; the
causes were independent, so this cut fixes each one and bounds what was
previously unbounded.

- The dev server was never actually capped: `next dev` renders in a worker it
  spawns, and V8 flags in argv are not inherited, so
  `node --max-old-space-size=4096 .../next dev` never reached the process
  holding the memory. Next then substituted 50% of total RAM — a 12 GB heap on
  a 24 GB machine. web/scripts/dev.mjs routes the ceiling through NODE_OPTIONS
  (which the worker inherits and Next honors), clamped to 4 GB and sized off
  the cgroup limit in a container.
- Source installs serve a production build: `deeptutor start` builds once into
  .next-deeptutor and reuses it until a fingerprint over the web/ tree, the
  version file, or the build-time public settings changes. `--dev` is the
  opt-in for HMR and keeps using .next, so neither mode invalidates the other.
- LLM clients and providers come from a bounded event-loop-local LRU pool of 2
  instead of one per turn, closed on shutdown and retired on a settings
  reload; only the selected backend's SDK is imported.
- Caches gained ceilings: knowledge-task log streams cap events and bytes per
  task with a 1h TTL and a completion tombstone, the completed-task table
  keeps 256, the LlamaIndex index cache drops 8 -> 2 with a 10-minute idle
  evict, and a book runtime is released when its queue drains.
- After a turn, a finished book job, or a completed KB task, cycles are
  collected and glibc is asked to return free pages via malloc_trim; the
  container and launcher set MALLOC_ARENA_MAX=2 and a lower trim threshold,
  both operator-overridable.
- Every uvicorn launch sets --timeout-keep-alive 300. web/proxy.ts forwards
  over Node's http.globalAgent, whose 5s idle reaper matched uvicorn's default
  exactly; both ends raced to close the same socket and the loser's request
  died with ECONNRESET ("Failed to load sessions").
- deeptutor.agents, deeptutor.core.agentic, provider_core, the document
  extractor's parser libraries and the LLM error-mapping rules resolve on
  first use. `python -m deeptutor.api.run_server` no longer reloads by
  default (DEEPTUTOR_DEV_RELOAD=1 restores it).

README prose and all ten translated READMEs now describe the production-build
default instead of dev mode. Release notes: assets/releases/ver1-5-8.md
2026-08-02 13:23:45 +08:00

174 lines
5.6 KiB
TypeScript

import {
MCP_ADMIN_BASE_PATH,
MCP_ALL_TRANSPORTS,
MCP_REMOTE_TRANSPORTS,
MCP_SPACE_BASE_PATH,
deleteSpaceMcpServer,
getMcpSettings,
getSpaceMcpState,
putSpaceMcpServer,
testMcpServer,
testSpaceMcpServer,
updateMcpSettings,
type McpServerConfig,
type McpStoreState,
type McpTestResult,
type McpTransport,
} from "@/lib/mcp-api";
/**
* Everything that differs between the places MCP servers can be managed: the
* deployment-global admin registry and the per-user one.
*
* The components take this object instead of an `isAdmin` flag so the two
* surfaces differ in one declaration rather than in conditionals sprinkled
* through the JSX — and so a new surface is a new constant, not a new branch.
*/
export interface McpSurface {
/** API base path the request helpers below hang their routes off. */
basePath: string;
/** Transports offered by the form's picker, in menu order. */
transports: readonly McpTransport[];
/**
* How a write is addressed. `"registry"` PUTs the whole map at `basePath`;
* `"per-server"` writes one server at a time under `basePath/servers/{name}`.
* The two APIs are genuinely different shapes, so the read/write helpers in
* this module dispatch on it and the callers stay shape-agnostic.
*/
writes: McpWriteStyle;
}
export type McpWriteStyle = "registry" | "per-server";
/**
* Deployment-global registry. stdio is selectable: a stdio `command` runs on
* the host as the app user, which is exactly why this surface is admin-gated.
*/
export const ADMIN_MCP_SURFACE: McpSurface = {
basePath: MCP_ADMIN_BASE_PATH,
transports: MCP_ALL_TRANSPORTS,
writes: "registry",
};
/**
* A single account's own servers. Remote transports only, permanently: stdio is
* a command executed on the host as the application user, and no per-user flag
* makes that safe to hand out.
*/
export const SPACE_MCP_SURFACE: McpSurface = {
basePath: MCP_SPACE_BASE_PATH,
transports: MCP_REMOTE_TRANSPORTS,
writes: "per-server",
};
export function surfaceAllows(
surface: McpSurface,
transport: McpTransport,
): boolean {
return surface.transports.includes(transport);
}
/**
* Delete one server by name, bypassing the whole-map diff.
*
* Needed for an entry the backend lists but will not connect (a hand-edited
* stdio server): it never appears in the servers map, so a diff-based write has
* nothing to remove.
*/
export async function deleteMcpSurfaceServer(
surface: McpSurface,
name: string,
): Promise<McpStoreState> {
if (surface.writes !== "per-server") {
throw new Error(
"Direct deletion is only available on a per-server surface",
);
}
return deleteSpaceMcpServer(surface.basePath, name);
}
export async function loadMcpSurface(
surface: McpSurface,
): Promise<McpStoreState> {
if (surface.writes === "per-server") {
return getSpaceMcpState(surface.basePath);
}
return { ...(await getMcpSettings(surface.basePath)), user: null };
}
/**
* Apply a whole-map intent to *surface*, and answer with the resulting state.
*
* A per-server surface has no whole-map write, so the intent is diffed against
* `previous`. Upserts run before deletions on purpose: a rename is one add plus
* one remove, and doing it the other way round would delete the old server
* first — then lose it for good if the add were refused (e.g. at the per-account
* cap). This order fails closed instead.
*/
export async function writeMcpSurface(
surface: McpSurface,
previous: Record<string, McpServerConfig>,
next: Record<string, McpServerConfig>,
): Promise<McpStoreState> {
if (surface.writes === "registry") {
const status = await updateMcpSettings(surface.basePath, next);
return { servers: next, status, user: null };
}
let state: McpStoreState | null = null;
for (const [name, cfg] of Object.entries(next)) {
if (isSameServer(previous[name], cfg)) continue;
state = await putSpaceMcpServer(surface.basePath, name, cfg);
}
for (const name of Object.keys(previous)) {
if (name in next) continue;
state = await deleteSpaceMcpServer(surface.basePath, name);
}
// No diff at all (a toggle re-applied to the same value): the caller still
// expects fresh state, and re-reading is cheaper than a redundant write.
return state ?? loadMcpSurface(surface);
}
/**
* Probe one definition before saving it.
*
* The per-user route is `POST /servers/{name}/test` — it runs under the caller's
* own owner id so the probe obeys the same address policy and stored
* credentials the real connection will. An unnamed draft borrows a name that no
* real server can hold (the backend's name rule rejects a leading underscore),
* so testing before naming cannot touch another server's stored credentials.
*/
export async function testMcpSurfaceServer(
surface: McpSurface,
name: string,
cfg: McpServerConfig,
secrets: Record<string, string> = {},
): Promise<McpTestResult> {
if (surface.writes === "per-server") {
return testSpaceMcpServer(
surface.basePath,
name.trim() || "_draft",
cfg,
secrets,
);
}
return testMcpServer(surface.basePath, cfg);
}
/**
* Whether a stored config and an edited one are the same write.
*
* Both sides are built by this module's own normalizer / form builder, so key
* order is stable and a structural compare is enough. It errs towards
* "changed": a reordered header map costs one idempotent PUT, while a missed
* change would silently drop the edit.
*/
function isSameServer(
previous: McpServerConfig | undefined,
next: McpServerConfig,
): boolean {
return (
previous !== undefined && JSON.stringify(previous) === JSON.stringify(next)
);
}