@nhatnguyen9317/memory-mcp-server 1.1.1

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.
@@ -0,0 +1,103 @@
1
+ import { MCP_VERSION, TELEMETRY_ENABLED } from "../constants.js";
2
+ import { handleToolError, newId, nowIso } from "../utils.js";
3
+ function toJsonText(value) {
4
+ if (!value)
5
+ return null;
6
+ return JSON.stringify(value);
7
+ }
8
+ function normalizeErrorCode(text) {
9
+ if (!text)
10
+ return null;
11
+ const lower = text.toLowerCase();
12
+ if (lower.includes("not found"))
13
+ return "not_found";
14
+ if (lower.includes("must be provided") || lower.includes("invalid")) {
15
+ return "validation_error";
16
+ }
17
+ if (lower.includes("constraint"))
18
+ return "constraint_violation";
19
+ if (lower.includes("foreign key"))
20
+ return "foreign_key_violation";
21
+ return "tool_error";
22
+ }
23
+ async function resolveDatabase(provider) {
24
+ return typeof provider === "function" ? provider() : provider;
25
+ }
26
+ export async function recordToolUsageEvent(database, event) {
27
+ if (!TELEMETRY_ENABLED)
28
+ return null;
29
+ try {
30
+ const id = newId("evt");
31
+ database
32
+ .prepare(`INSERT INTO tool_usage_events (
33
+ id,
34
+ created_at,
35
+ agent_id,
36
+ client_name,
37
+ client_version,
38
+ mcp_version,
39
+ guidance_version,
40
+ tool_name,
41
+ operation_type,
42
+ access_type,
43
+ status,
44
+ error_code,
45
+ latency_ms,
46
+ session_id,
47
+ step_id,
48
+ memory_id,
49
+ related_event_id,
50
+ input_shape,
51
+ output_shape,
52
+ metadata
53
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
54
+ .run(id, nowIso(), event.agentId ?? null, event.clientName ?? null, event.clientVersion ?? null, MCP_VERSION, event.guidanceVersion ?? null, event.toolName, event.operationType, event.accessType, event.status, event.errorCode ?? null, event.latencyMs ?? null, event.sessionId ?? null, event.stepId ?? null, event.memoryId ?? null, event.relatedEventId ?? null, toJsonText(event.inputShape), toJsonText(event.outputShape), toJsonText(event.metadata));
55
+ return id;
56
+ }
57
+ catch (error) {
58
+ console.error("Telemetry recording failed:", error);
59
+ return null;
60
+ }
61
+ }
62
+ export function withTelemetry(config, handler) {
63
+ return async (params) => {
64
+ const startedAt = Date.now();
65
+ try {
66
+ const result = await handler(params);
67
+ const database = await resolveDatabase(config.database);
68
+ const event = await config.buildEvent(params, result, database);
69
+ await recordToolUsageEvent(database, {
70
+ toolName: config.toolName,
71
+ operationType: config.operationType,
72
+ accessType: config.accessType,
73
+ status: result.isError ? "error" : "success",
74
+ errorCode: result.isError
75
+ ? normalizeErrorCode(result.content[0]?.text ?? null)
76
+ : null,
77
+ latencyMs: Date.now() - startedAt,
78
+ ...event,
79
+ });
80
+ return result;
81
+ }
82
+ catch (error) {
83
+ const database = await resolveDatabase(config.database);
84
+ const text = handleToolError(error);
85
+ const result = {
86
+ content: [{ type: "text", text }],
87
+ isError: true,
88
+ };
89
+ const event = await config.buildEvent(params, result, database);
90
+ await recordToolUsageEvent(database, {
91
+ toolName: config.toolName,
92
+ operationType: config.operationType,
93
+ accessType: config.accessType,
94
+ status: "error",
95
+ errorCode: normalizeErrorCode(text),
96
+ latencyMs: Date.now() - startedAt,
97
+ ...event,
98
+ });
99
+ return result;
100
+ }
101
+ };
102
+ }
103
+ //# sourceMappingURL=telemetry.js.map
@@ -0,0 +1,83 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { MCP_VERSION } from "../constants.js";
3
+ import { MemoryGetUsageGuideInputSchema, } from "../schemas/memory.js";
4
+ import { withTelemetry } from "./telemetry.js";
5
+ const GUIDELINES_PATH = "GUIDELINES.md";
6
+ const GUIDELINES_URL = new URL(`../../${GUIDELINES_PATH}`, import.meta.url);
7
+ function extractStructuredContent(result) {
8
+ return result.structuredContent ?? null;
9
+ }
10
+ function parseGuideVersion(content) {
11
+ const match = content.match(/^Version:\s*(.+)$/m);
12
+ if (!match) {
13
+ throw new Error(`${GUIDELINES_PATH} is missing a Version line.`);
14
+ }
15
+ return match[1].trim();
16
+ }
17
+ async function readGuidelines() {
18
+ const content = await readFile(GUIDELINES_URL, "utf8");
19
+ return {
20
+ content,
21
+ guideVersion: parseGuideVersion(content),
22
+ };
23
+ }
24
+ let defaultDatabasePromise = null;
25
+ async function resolveDatabase(database) {
26
+ if (database)
27
+ return database;
28
+ defaultDatabasePromise ??= import("../db.js").then((module) => module.db);
29
+ return defaultDatabasePromise;
30
+ }
31
+ export function registerUsageGuideTool(server, database) {
32
+ const databaseProvider = () => resolveDatabase(database);
33
+ server.registerTool("get_usage_guide", {
34
+ title: "Get Usage Guide",
35
+ description: `Return the versioned ${GUIDELINES_PATH} file that defines how an agent should use this MCP.`,
36
+ inputSchema: MemoryGetUsageGuideInputSchema.shape,
37
+ annotations: {
38
+ readOnlyHint: true,
39
+ destructiveHint: false,
40
+ idempotentHint: true,
41
+ openWorldHint: false,
42
+ },
43
+ }, withTelemetry({
44
+ database: databaseProvider,
45
+ toolName: "get_usage_guide",
46
+ operationType: "guidance",
47
+ accessType: "derived",
48
+ buildEvent: (params, result) => {
49
+ const structured = extractStructuredContent(result);
50
+ return {
51
+ agentId: params.agent_id ?? null,
52
+ clientName: params.client_name ?? null,
53
+ clientVersion: params.client_version ?? null,
54
+ guidanceVersion: typeof structured?.guide_version === "string"
55
+ ? structured.guide_version
56
+ : null,
57
+ outputShape: structured
58
+ ? {
59
+ guide_version: structured.guide_version,
60
+ format: structured.format,
61
+ content_length: typeof structured.content === "string"
62
+ ? structured.content.length
63
+ : 0,
64
+ }
65
+ : null,
66
+ };
67
+ },
68
+ }, async (_params) => {
69
+ const guidelines = await readGuidelines();
70
+ const output = {
71
+ guide_version: guidelines.guideVersion,
72
+ mcp_version: MCP_VERSION,
73
+ path: GUIDELINES_PATH,
74
+ format: "markdown",
75
+ content: guidelines.content,
76
+ };
77
+ return {
78
+ content: [{ type: "text", text: guidelines.content }],
79
+ structuredContent: output,
80
+ };
81
+ }));
82
+ }
83
+ //# sourceMappingURL=usage-guide.js.map
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
package/dist/utils.js ADDED
@@ -0,0 +1,67 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { CHARACTER_LIMIT } from "./constants.js";
3
+ export function newId(prefix) {
4
+ return `${prefix}_${randomUUID()}`;
5
+ }
6
+ export function nowIso() {
7
+ return new Date().toISOString();
8
+ }
9
+ export function parseJsonArray(text) {
10
+ if (!text)
11
+ return [];
12
+ try {
13
+ const parsed = JSON.parse(text);
14
+ return Array.isArray(parsed) ? parsed.map(String) : [];
15
+ }
16
+ catch {
17
+ return [];
18
+ }
19
+ }
20
+ export function parseJsonObject(text) {
21
+ if (!text)
22
+ return null;
23
+ try {
24
+ const parsed = JSON.parse(text);
25
+ return typeof parsed === "object" && parsed !== null ? parsed : null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ /** FTS5 MATCH queries break on raw punctuation; wrap terms as a safe prefix query. */
32
+ export function toFtsQuery(raw) {
33
+ const terms = raw
34
+ .trim()
35
+ .split(/\s+/)
36
+ .filter(Boolean)
37
+ .map((t) => `"${t.replace(/"/g, '""')}"*`);
38
+ return terms.length ? terms.join(" ") : '""';
39
+ }
40
+ /** Serialize a value to text, truncating with a clear message if it exceeds CHARACTER_LIMIT. */
41
+ export function toLimitedJson(value) {
42
+ const text = JSON.stringify(value, null, 2);
43
+ if (text.length <= CHARACTER_LIMIT)
44
+ return text;
45
+ return JSON.stringify({
46
+ truncated: true,
47
+ truncation_message: `Response exceeded ${CHARACTER_LIMIT} characters and was truncated. Narrow your query (add filters, reduce limit) to see full results.`,
48
+ partial_text: text.slice(0, CHARACTER_LIMIT),
49
+ }, null, 2);
50
+ }
51
+ export function handleToolError(error) {
52
+ if (error instanceof Error) {
53
+ // better-sqlite3 constraint violations
54
+ if (error.message.includes("CHECK constraint failed")) {
55
+ return `Error: Invalid value provided (${error.message}). Check allowed ranges/enums in the tool description.`;
56
+ }
57
+ if (error.message.includes("FOREIGN KEY constraint failed")) {
58
+ return "Error: Referenced session_id does not exist. Use reasoning_start_session first, or check reasoning_list_sessions for valid IDs.";
59
+ }
60
+ if (error.message.includes("UNIQUE constraint failed")) {
61
+ return "Error: A record with this identifier already exists.";
62
+ }
63
+ return `Error: ${error.message}`;
64
+ }
65
+ return `Error: Unexpected error occurred: ${String(error)}`;
66
+ }
67
+ //# sourceMappingURL=utils.js.map
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@nhatnguyen9317/memory-mcp-server",
3
+ "version": "1.1.1",
4
+ "description": "MCP server for persisting agent long-term memory and step-by-step reasoning traces in SQLite",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "files": [
8
+ "dist/index.js",
9
+ "dist/constants.js",
10
+ "dist/db.js",
11
+ "dist/migrations/*.js",
12
+ "dist/schemas/*.js",
13
+ "dist/tools/*.js",
14
+ "dist/types.js",
15
+ "dist/utils.js",
16
+ "README.md",
17
+ "GUIDELINES.md"
18
+ ],
19
+ "bin": {
20
+ "memory-mcp-server": "dist/index.js"
21
+ },
22
+ "scripts": {
23
+ "start": "node dist/index.js",
24
+ "dev": "tsx watch src/index.ts",
25
+ "build": "tsc && node -e \"require('fs').chmodSync('dist/index.js','755')\"",
26
+ "test": "npm run build && node --test dist/__tests__/*.test.js",
27
+ "clean": "rm -rf dist"
28
+ },
29
+ "engines": {
30
+ "node": ">=22.5.0"
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "^1.6.1",
34
+ "zod": "^3.23.8"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^22.10.0",
38
+ "tsx": "^4.19.2",
39
+ "typescript": "^5.7.2"
40
+ }
41
+ }