@kynver-app/mcp-agent-os 0.3.42 → 0.3.46

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.
@@ -23,6 +23,21 @@ export declare function headerValue(req: IncomingMessage, name: string): string
23
23
  export declare function timingSafeEqualString(a: string, b: string): boolean;
24
24
  export declare function hasForbiddenQueryAuth(url: URL): boolean;
25
25
  export declare function resolveListenHost(): string;
26
+ /** Positive integer from env, else fallback. */
27
+ export declare function intFromEnv(name: string, fallback: number): number;
28
+ /**
29
+ * Resolve + validate the Kynver API origin the server sends bearer keys to.
30
+ * A poisoned/misconfigured value would exfiltrate API keys, so fail closed on
31
+ * anything that isn't https (http is allowed only for localhost dev).
32
+ */
33
+ export declare function resolveApiBaseUrl(): string;
34
+ /** First client IP from x-forwarded-for, else the socket address. */
35
+ export declare function clientIp(req: IncomingMessage): string;
36
+ type RateLimiter = {
37
+ check: (key: string) => boolean;
38
+ };
39
+ /** Minimal in-process fixed-window limiter (the SSE server is single-process). */
40
+ export declare function createFixedWindowRateLimiter(limit: number, windowMs: number): RateLimiter;
26
41
  export declare function parseJsonBody(req: IncomingMessage, maxBytes?: number): Promise<unknown>;
27
42
  export declare function validateMcporterServerName(name: string): string;
28
43
  export declare function startKynverMcpSseServer(options: StartKynverMcpSseServerOptions): void;
@@ -26,6 +26,61 @@ export function resolveListenHost() {
26
26
  const configured = process.env.MCP_SSE_HOST?.trim();
27
27
  return configured || "127.0.0.1";
28
28
  }
29
+ /** Positive integer from env, else fallback. */
30
+ export function intFromEnv(name, fallback) {
31
+ const raw = process.env[name];
32
+ if (!raw)
33
+ return fallback;
34
+ const n = parseInt(raw, 10);
35
+ return Number.isFinite(n) && n > 0 ? n : fallback;
36
+ }
37
+ /**
38
+ * Resolve + validate the Kynver API origin the server sends bearer keys to.
39
+ * A poisoned/misconfigured value would exfiltrate API keys, so fail closed on
40
+ * anything that isn't https (http is allowed only for localhost dev).
41
+ */
42
+ export function resolveApiBaseUrl() {
43
+ const raw = process.env.KYNVER_API_URL?.trim();
44
+ if (!raw)
45
+ return "https://kynver.com";
46
+ let parsed;
47
+ try {
48
+ parsed = new URL(raw);
49
+ }
50
+ catch {
51
+ throw new Error(`Invalid KYNVER_API_URL: ${raw}`);
52
+ }
53
+ const isLocalhost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
54
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLocalhost)) {
55
+ throw new Error(`KYNVER_API_URL must be https (got "${parsed.protocol}//${parsed.hostname}"); API keys are sent to this origin.`);
56
+ }
57
+ return raw.replace(/\/$/, "");
58
+ }
59
+ /** First client IP from x-forwarded-for, else the socket address. */
60
+ export function clientIp(req) {
61
+ const fwd = headerValue(req, "x-forwarded-for");
62
+ if (fwd)
63
+ return fwd.split(",")[0].trim();
64
+ return req.socket?.remoteAddress ?? "unknown";
65
+ }
66
+ /** Minimal in-process fixed-window limiter (the SSE server is single-process). */
67
+ export function createFixedWindowRateLimiter(limit, windowMs) {
68
+ const hits = new Map();
69
+ return {
70
+ check(key) {
71
+ const now = Date.now();
72
+ const entry = hits.get(key);
73
+ if (!entry || now >= entry.resetAt) {
74
+ hits.set(key, { count: 1, resetAt: now + windowMs });
75
+ return true;
76
+ }
77
+ if (entry.count >= limit)
78
+ return false;
79
+ entry.count += 1;
80
+ return true;
81
+ },
82
+ };
83
+ }
29
84
  export function parseJsonBody(req, maxBytes = MAX_SSE_BODY_BYTES) {
30
85
  return new Promise((resolve, reject) => {
31
86
  const chunks = [];
@@ -106,14 +161,37 @@ function json(res, status, body) {
106
161
  }
107
162
  export function startKynverMcpSseServer(options) {
108
163
  const port = parseInt(process.env.PORT ?? String(options.defaultPort), 10);
109
- const baseUrl = process.env.KYNVER_API_URL ?? "https://kynver.com";
164
+ const baseUrl = resolveApiBaseUrl();
110
165
  const serviceSecret = process.env.KYNVER_SERVICE_SECRET ?? "";
111
166
  const host = resolveListenHost();
112
167
  const sessions = {};
168
+ // Resource / abuse limits (env-overridable; in-process per server).
169
+ const maxSessions = intFromEnv("MCP_SSE_MAX_SESSIONS", 200);
170
+ const maxSessionsPerUser = intFromEnv("MCP_SSE_MAX_SESSIONS_PER_USER", 20);
171
+ const idleTimeoutMs = intFromEnv("MCP_SSE_IDLE_TIMEOUT_MS", 5 * 60 * 1000);
172
+ const rateLimitPerMin = intFromEnv("MCP_SSE_RATE_LIMIT_PER_MIN", 120);
173
+ const rejectQueryApiKey = /^(1|true|yes)$/i.test(process.env.MCP_SSE_REJECT_QUERY_APIKEY ?? "");
174
+ const rateLimiter = createFixedWindowRateLimiter(rateLimitPerMin, 60 * 1000);
175
+ // Close idle SSE sessions so a flood of half-open connections can't pin memory.
176
+ const idleSweep = setInterval(() => {
177
+ const now = Date.now();
178
+ for (const [sid, entry] of Object.entries(sessions)) {
179
+ if (now - entry.lastActivity > idleTimeoutMs) {
180
+ delete sessions[sid];
181
+ void entry.transport.close().catch(() => { });
182
+ }
183
+ }
184
+ }, 60 * 1000);
185
+ idleSweep.unref?.();
113
186
  const httpServer = createServer(async (req, res) => {
114
187
  const url = parseUrl(req, port);
115
188
  const path = url.pathname;
116
189
  if (req.method === "GET" && path === "/sse") {
190
+ // Pre-auth rate limit by client IP (we don't know the user yet).
191
+ if (!rateLimiter.check(`sse:${clientIp(req)}`)) {
192
+ json(res, 429, { error: "Too many requests. Slow down and retry." });
193
+ return;
194
+ }
117
195
  if (hasForbiddenQueryAuth(url)) {
118
196
  json(res, 400, {
119
197
  error: "Internal auth via query params is not allowed. Use X-Kynver-User-Id and X-Kynver-Service-Secret headers.",
@@ -121,6 +199,12 @@ export function startKynverMcpSseServer(options) {
121
199
  return;
122
200
  }
123
201
  if (url.searchParams.has("apiKey")) {
202
+ if (rejectQueryApiKey) {
203
+ json(res, 400, {
204
+ error: "apiKey via query param is disabled. Use Authorization: Bearer <key>.",
205
+ });
206
+ return;
207
+ }
124
208
  console.warn("[MCP SSE] WARNING: apiKey in query string may leak via logs. Prefer Authorization header when your client supports it.");
125
209
  }
126
210
  let userId = null;
@@ -144,9 +228,20 @@ export function startKynverMcpSseServer(options) {
144
228
  });
145
229
  return;
146
230
  }
231
+ // Connection caps — bound total + per-user concurrent SSE sessions so an
232
+ // authenticated caller can't exhaust memory/sockets by opening many.
233
+ const allEntries = Object.values(sessions);
234
+ if (allEntries.length >= maxSessions) {
235
+ json(res, 503, { error: "Server at capacity. Try again shortly." });
236
+ return;
237
+ }
238
+ if (allEntries.filter((s) => s.userId === userId).length >= maxSessionsPerUser) {
239
+ json(res, 429, { error: "Too many concurrent connections for this account." });
240
+ return;
241
+ }
147
242
  console.log(`[MCP SSE] New connection (${options.label}, user: ${userId.slice(0, 8)}...)`);
148
243
  const transport = new SSEServerTransport("/messages", res);
149
- sessions[transport.sessionId] = { transport, userId, auth };
244
+ sessions[transport.sessionId] = { transport, userId, auth, lastActivity: Date.now() };
150
245
  res.on("close", () => {
151
246
  delete sessions[transport.sessionId];
152
247
  });
@@ -165,6 +260,12 @@ export function startKynverMcpSseServer(options) {
165
260
  json(res, 401, { error: "Unauthorized. Re-send the same credentials used to open the SSE session." });
166
261
  return;
167
262
  }
263
+ // Per-user rate limit on tool/message traffic.
264
+ if (!rateLimiter.check(`msg:${entry.userId}`)) {
265
+ json(res, 429, { error: "Too many requests. Slow down and retry." });
266
+ return;
267
+ }
268
+ entry.lastActivity = Date.now();
168
269
  try {
169
270
  const body = await parseJsonBody(req);
170
271
  await options.requestContext.run({ userId: entry.userId }, async () => {
package/dist/server.js CHANGED
@@ -23,6 +23,8 @@ import { registerPrBacklogTools } from "./tools/pr-backlog.js";
23
23
  import { registerMeshLivenessTools } from "./tools/mesh-liveness.js";
24
24
  import { registerDiagnosticsTools } from "./tools/diagnostics.js";
25
25
  import { registerSkillsTools } from "./tools/skills.js";
26
+ import { registerMemoryLedgerTools } from "./tools/memory-ledger.js";
27
+ import { registerMemoryVaultTools } from "./tools/memory-vault.js";
26
28
  import { registerMonitorTools } from "./tools/monitor.js";
27
29
  import { readOwnPackageVersion } from "./lib/package-version.js";
28
30
  const PACKAGE_VERSION = readOwnPackageVersion(import.meta.url);
@@ -308,7 +310,7 @@ export function createAgentOsServer() {
308
310
  const s = await resolveToolSlug(slug);
309
311
  return jsonResult(await patch(`/agent-os/${s}/projects/${projectId}`, body));
310
312
  });
311
- register("agent_os_search_memory", "Semantic + keyword hybrid search over the agent's long-term memory (ownerType=agent). Use to recall specific decisions, project details, or lessons without loading full context. Replaces grep/reading MEMORY.md. Optionally restrict to one source namespace via sourceId, or several via sourceIds (sourceId takes precedence when both are set). Workspace owners and env admins receive operator diagnostics (rrfScore, lanes, hygiene) unless surface=customer; grantees always receive grantee-safe hits (content, trust, evidence links only).", {
313
+ register("agent_os_search_memory", "Search the agent's long-term memory (ownerType=agent). Use to recall specific decisions, project details, or lessons without loading full context. Replaces grep/reading MEMORY.md. Optionally restrict to one source namespace via sourceId, or several via sourceIds (sourceId takes precedence when both are set). Workspace owners and env admins receive additional operator diagnostics unless surface=customer; grantees always receive grantee-safe hits (content, trust, evidence links only).", {
312
314
  query: z.string().describe("Natural language query to search memory."),
313
315
  k: z.number().optional().describe("Number of results (default 5, max 50)."),
314
316
  sourceId: z
@@ -321,7 +323,7 @@ export function createAgentOsServer() {
321
323
  .describe("Restrict search to any of these source namespaces. Ignored when sourceId is also set."),
322
324
  ticker: z.string().optional().describe("Trading desk: filter hits to this ticker symbol."),
323
325
  debatePersona: z.enum(["bull", "bear"]).optional().describe("Trading desk: filter to bull or bear advocate memories."),
324
- personaSlug: z.string().optional().describe("Layer in this persona's operating rules in Lane A alongside global rules."),
326
+ personaSlug: z.string().optional().describe("Layer in this persona's operating rules alongside global rules."),
325
327
  surface: memorySurfaceField,
326
328
  slug: slugField,
327
329
  }, async (args) => {
@@ -717,7 +719,7 @@ export function createAgentOsServer() {
717
719
  registerCommandCenterTools({ register, resolveToolSlug, jsonResult });
718
720
  // Memory quality feedback (M2): record events + query status.
719
721
  registerMemoryQualityFeedbackTools({ register, resolveToolSlug, jsonResult, compact });
720
- // Lane A instruction policy (operating rules boundary).
722
+ // Operating-rules instruction policy.
721
723
  registerOperatingRulesTools({ register, resolveToolSlug, jsonResult, compact });
722
724
  // Daemon-mediated provider evidence (read-only verification surface).
723
725
  registerProviderEvidenceTools({ register, resolveToolSlug, jsonResult });
@@ -729,6 +731,8 @@ export function createAgentOsServer() {
729
731
  registerDiagnosticsTools({ register, resolveToolSlug, jsonResult });
730
732
  // Skill library: query-first discovery + on-demand recipe fetch (bounded, metadata-first).
731
733
  registerSkillsTools({ register, resolveToolSlug, jsonResult });
734
+ registerMemoryLedgerTools({ register, resolveToolSlug, jsonResult });
735
+ registerMemoryVaultTools({ register, resolveToolSlug, jsonResult });
732
736
  registerMonitorTools({ register, resolveToolSlug, jsonResult });
733
737
  return server;
734
738
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Memory ledger MCP tools (audited-memory M5) — agent-readable summaries so
3
+ * the runtime agent can narrate what was read and why, then steer the
4
+ * workbench to the Memory activity panel.
5
+ */
6
+ type ToolResult = {
7
+ content: {
8
+ type: "text";
9
+ text: string;
10
+ }[];
11
+ structuredContent?: unknown;
12
+ };
13
+ export interface MemoryLedgerToolDeps {
14
+ register: (name: string, description: string, inputSchema: Record<string, unknown>, cb: (args: any) => any) => void;
15
+ resolveToolSlug: (explicitSlug?: string) => Promise<string>;
16
+ jsonResult: (data: unknown) => ToolResult;
17
+ }
18
+ export declare function registerMemoryLedgerTools({ register, resolveToolSlug, jsonResult, }: MemoryLedgerToolDeps): void;
19
+ export {};
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Memory ledger MCP tools (audited-memory M5) — agent-readable summaries so
3
+ * the runtime agent can narrate what was read and why, then steer the
4
+ * workbench to the Memory activity panel.
5
+ */
6
+ import { z } from "zod";
7
+ import { get } from "../lib/kynver-client.js";
8
+ export function registerMemoryLedgerTools({ register, resolveToolSlug, jsonResult, }) {
9
+ register("agent_os_memory_ledger_summary", [
10
+ "Read a narrated summary of the workspace owner's signed memory access ledger",
11
+ "(receipt counts, recent human-framed activity lines, chain integrity, and workbench",
12
+ "steering hints). Use when the operator asks what memories were read, what changed,",
13
+ "or wants a weekly digest. Customer vocabulary only — no retrieval mechanics.",
14
+ "After summarizing, offer to open Memory activity via agent_os_workbench_view",
15
+ "(kind=open_panel, panel=memory-activity). Read-only and safe for unattended use.",
16
+ ].join(" "), {
17
+ slug: z.string().optional().describe("AgentOS slug. Defaults to env/primary."),
18
+ periodDays: z
19
+ .number()
20
+ .int()
21
+ .min(1)
22
+ .max(90)
23
+ .optional()
24
+ .describe("Rolling window in days when from/to omitted (default 7)."),
25
+ from: z.string().optional().describe("Inclusive ISO lower bound."),
26
+ to: z.string().optional().describe("Inclusive ISO upper bound."),
27
+ recentLimit: z
28
+ .number()
29
+ .int()
30
+ .min(1)
31
+ .max(25)
32
+ .optional()
33
+ .describe("Recent narrated lines (default 12)."),
34
+ }, async (args) => {
35
+ const slug = await resolveToolSlug(args.slug);
36
+ const params = new URLSearchParams();
37
+ if (args.periodDays != null)
38
+ params.set("periodDays", String(args.periodDays));
39
+ if (args.from)
40
+ params.set("from", args.from);
41
+ if (args.to)
42
+ params.set("to", args.to);
43
+ if (args.recentLimit != null)
44
+ params.set("recentLimit", String(args.recentLimit));
45
+ const qs = params.toString();
46
+ return jsonResult(await get(`/agent-os/${encodeURIComponent(slug)}/memory-ledger/summary${qs ? `?${qs}` : ""}`));
47
+ });
48
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Memory vault MCP tools (audited-memory M4) — sealed-memory label visibility
3
+ * for the runtime agent. STRICT contract: the agent may learn that sealed
4
+ * memories exist (label + slug + createdAt) and nothing else. Sealed content
5
+ * is encrypted client-side; opening requires the user's explicit per-request
6
+ * consent in the Kynver web chat, where they decrypt it locally.
7
+ */
8
+ type ToolResult = {
9
+ content: {
10
+ type: "text";
11
+ text: string;
12
+ }[];
13
+ structuredContent?: unknown;
14
+ };
15
+ export interface MemoryVaultToolDeps {
16
+ register: (name: string, description: string, inputSchema: Record<string, unknown>, cb: (args: any) => any) => void;
17
+ resolveToolSlug: (explicitSlug?: string) => Promise<string>;
18
+ jsonResult: (data: unknown) => ToolResult;
19
+ }
20
+ export declare function registerMemoryVaultTools({ register, resolveToolSlug, jsonResult, }: MemoryVaultToolDeps): void;
21
+ export {};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Memory vault MCP tools (audited-memory M4) — sealed-memory label visibility
3
+ * for the runtime agent. STRICT contract: the agent may learn that sealed
4
+ * memories exist (label + slug + createdAt) and nothing else. Sealed content
5
+ * is encrypted client-side; opening requires the user's explicit per-request
6
+ * consent in the Kynver web chat, where they decrypt it locally.
7
+ */
8
+ import { z } from "zod";
9
+ import { get } from "../lib/kynver-client.js";
10
+ export function registerMemoryVaultTools({ register, resolveToolSlug, jsonResult, }) {
11
+ register("agent_os_vault_labels", [
12
+ "List the workspace owner's sealed (vault) memories — labels, slugs, and creation dates",
13
+ "ONLY. Sealed content is encrypted in the user's browser before upload and can never be",
14
+ "read by you or the platform; this tool proves a sealed memory exists, nothing more.",
15
+ "To use one, ask the user to open it — they decrypt it locally and choose per request",
16
+ "(opens happen in the Kynver web chat via a consent card; each open is receipted in the",
17
+ "Memory activity ledger). Read-only and safe for unattended use.",
18
+ ].join(" "), {
19
+ slug: z.string().optional().describe("AgentOS slug. Defaults to env/primary."),
20
+ }, async (args) => {
21
+ const slug = await resolveToolSlug(args.slug);
22
+ return jsonResult(await get(`/agent-os/${encodeURIComponent(slug)}/memory/vault/labels`));
23
+ });
24
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
- * MCP tools for Lane A instruction policy (operating rules boundary).
2
+ * MCP tools for the operating-rules instruction policy.
3
3
  *
4
- * agent_os_operating_rules_get — deterministic Lane A policy + optional injection markdown.
4
+ * agent_os_operating_rules_get — deterministic operating-rules policy + optional injection markdown.
5
5
  */
6
6
  import type { MemoryQualityFeedbackToolDeps } from "./memory-quality-feedback.js";
7
7
  export declare function registerOperatingRulesTools(deps: MemoryQualityFeedbackToolDeps): void;
@@ -1,7 +1,7 @@
1
1
  /**
2
- * MCP tools for Lane A instruction policy (operating rules boundary).
2
+ * MCP tools for the operating-rules instruction policy.
3
3
  *
4
- * agent_os_operating_rules_get — deterministic Lane A policy + optional injection markdown.
4
+ * agent_os_operating_rules_get — deterministic operating-rules policy + optional injection markdown.
5
5
  */
6
6
  import { z } from "zod";
7
7
  import { get } from "../lib/kynver-client.js";
@@ -9,7 +9,7 @@ export function registerOperatingRulesTools(deps) {
9
9
  const { register, resolveToolSlug, jsonResult, compact } = deps;
10
10
  register("agent_os_operating_rules_get", [
11
11
  "Return the AgentOS instruction policy (internal + custom operating-rule tiers).",
12
- "Uses explicit kind=operating-rule Prisma fetch — not semantic Lane A recall.",
12
+ "Returns operating rules by exact lookup, not semantic search.",
13
13
  "Operator access required; internal-tier mechanics visible to Kynver platform admins only.",
14
14
  "Set includeMarkdown=1 to receive prompt injection text.",
15
15
  ].join(" "), {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kynver-app/mcp-agent-os",
3
- "version": "0.3.42",
4
- "description": "Kynver Agentic OS MCP server — slug-keyed agent identity, goals, projects, sessions, and long-term memory",
3
+ "version": "0.3.46",
4
+ "description": "Kynver Agentic OS MCP server \u2014 slug-keyed agent identity, goals, projects, sessions, and long-term memory",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "kynver-mcp-agent-os": "dist/index.js"
@@ -18,6 +18,7 @@
18
18
  "build": "node --max-old-space-size=8192 ../../node_modules/typescript/bin/tsc",
19
19
  "dev": "node --max-old-space-size=8192 ../../node_modules/typescript/bin/tsc --watch",
20
20
  "start": "node dist/index.js",
21
+ "prepublishOnly": "npm run build && node ../../scripts/npm-publish-guard.mjs",
21
22
  "start:sse": "node dist/sse.js"
22
23
  },
23
24
  "engines": {