@gilangjavier/chrona 0.1.0 → 0.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 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/utils.ts","../src/validate.ts","../src/store.ts","../src/mcp.ts"],"sourcesContent":["export const memoryTypes = [\"decision\", \"preference\", \"fact\", \"incident\", \"constraint\"] as const;\nexport const memoryScopes = [\"user\", \"project\", \"org\", \"shared\"] as const;\nexport const sourceKinds = [\"tool\", \"session\", \"repo\"] as const;\n\nexport type MemoryType = (typeof memoryTypes)[number];\nexport type MemoryScope = (typeof memoryScopes)[number];\nexport type SourceKind = (typeof sourceKinds)[number];\n\nexport interface MemorySource {\n kind: SourceKind;\n value: string;\n}\n\nexport interface MemoryEntry {\n id: string;\n type: MemoryType;\n text: string;\n createdAt: string;\n source: MemorySource;\n confidence: number;\n scope: MemoryScope;\n tags: string[];\n expiresAt?: string;\n links?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface AddMemoryInput {\n id?: string;\n type: MemoryType;\n text: string;\n createdAt?: string;\n source: MemorySource;\n confidence: number;\n scope: MemoryScope;\n tags: string[];\n expiresAt?: string;\n links?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface QueryOptions {\n scopes?: MemoryScope[];\n types?: MemoryType[];\n tags?: string[];\n sourceKind?: SourceKind;\n sourceValue?: string;\n before?: string;\n after?: string;\n includeExpired?: boolean;\n limit?: number;\n}\n\nexport interface SearchOptions extends QueryOptions {\n query: string;\n}\n\nexport interface TimelineOptions extends QueryOptions {\n order?: \"asc\" | \"desc\";\n}\n\nexport interface ExportOptions extends TimelineOptions {}\n\nexport interface ImportResult {\n imported: number;\n updated: number;\n ids: string[];\n}\n\nexport interface GcResult {\n deleted: number;\n ids: string[];\n now: string;\n}\n","import { randomUUID } from \"node:crypto\";\n\nexport function toIsoString(value?: string | Date): string {\n const date = value instanceof Date ? value : value ? new Date(value) : new Date();\n const iso = date.toISOString();\n\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid date: ${String(value)}`);\n }\n\n return iso;\n}\n\nexport function uniqueSorted(values: string[] | undefined): string[] {\n return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))].sort((a, b) => a.localeCompare(b));\n}\n\nexport function normalizeConfidence(value: number): number {\n if (!Number.isFinite(value) || value < 0 || value > 1) {\n throw new Error(\"confidence must be between 0 and 1\");\n }\n\n return Number(value.toFixed(6));\n}\n\nexport function parseJsonObject(value: unknown): Record<string, unknown> | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n\n if (typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new Error(\"metadata must be an object or JSON object string\");\n }\n\n const parsed = JSON.parse(value) as unknown;\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"metadata must be a JSON object\");\n }\n\n return parsed as Record<string, unknown>;\n}\n\nexport function parseCsv(value?: string): string[] {\n if (!value) {\n return [];\n }\n\n return value.split(\",\").map((item) => item.trim()).filter(Boolean);\n}\n\nexport function ensureId(value?: string): string {\n return value?.trim() || randomUUID();\n}\n\nexport function serializeJson(value: unknown): string {\n return JSON.stringify(value ?? {});\n}\n","import {\n memoryScopes,\n memoryTypes,\n sourceKinds,\n type AddMemoryInput,\n type MemoryEntry,\n type MemoryScope,\n type MemoryType,\n type SourceKind\n} from \"./types.js\";\nimport { ensureId, normalizeConfidence, parseJsonObject, toIsoString, uniqueSorted } from \"./utils.js\";\n\nfunction includesValue<T extends string>(values: readonly T[], value: string, label: string): T {\n if (!values.includes(value as T)) {\n throw new Error(`Invalid ${label}: ${value}`);\n }\n\n return value as T;\n}\n\nexport function parseMemoryType(value: string): MemoryType {\n return includesValue(memoryTypes, value, \"type\");\n}\n\nexport function parseMemoryScope(value: string): MemoryScope {\n return includesValue(memoryScopes, value, \"scope\");\n}\n\nexport function parseSourceKind(value: string): SourceKind {\n return includesValue(sourceKinds, value, \"source kind\");\n}\n\nexport function normalizeEntry(input: AddMemoryInput | MemoryEntry): MemoryEntry {\n if (!input.text.trim()) {\n throw new Error(\"text is required\");\n }\n\n if (!input.source?.value?.trim()) {\n throw new Error(\"source.value is required\");\n }\n\n return {\n id: ensureId(input.id),\n type: parseMemoryType(input.type),\n text: input.text.trim(),\n createdAt: toIsoString(input.createdAt),\n source: {\n kind: parseSourceKind(input.source.kind),\n value: input.source.value.trim()\n },\n confidence: normalizeConfidence(input.confidence),\n scope: parseMemoryScope(input.scope),\n tags: uniqueSorted(input.tags),\n expiresAt: input.expiresAt ? toIsoString(input.expiresAt) : undefined,\n links: uniqueSorted(input.links),\n metadata: parseJsonObject(input.metadata)\n };\n}\n","import Database from \"better-sqlite3\";\nimport { mkdirSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport type {\n AddMemoryInput,\n ExportOptions,\n GcResult,\n ImportResult,\n MemoryEntry,\n QueryOptions,\n SearchOptions,\n TimelineOptions\n} from \"./types.js\";\nimport { normalizeEntry } from \"./validate.js\";\nimport { serializeJson, toIsoString } from \"./utils.js\";\n\ninterface MemoryRow {\n id: string;\n type: MemoryEntry[\"type\"];\n text: string;\n created_at: string;\n source_kind: MemoryEntry[\"source\"][\"kind\"];\n source_value: string;\n confidence: number;\n scope: MemoryEntry[\"scope\"];\n tags_json: string;\n expires_at: string | null;\n links_json: string;\n metadata_json: string;\n}\n\nexport class ChromaStore {\n readonly path: string;\n readonly db: Database.Database;\n\n constructor(path = resolve(process.cwd(), \".chrona/chrona.db\")) {\n this.path = resolve(path);\n mkdirSync(dirname(this.path), { recursive: true });\n this.db = new Database(this.path);\n this.db.pragma(\"journal_mode = WAL\");\n this.db.pragma(\"foreign_keys = ON\");\n this.db.pragma(\"busy_timeout = 5000\");\n }\n\n init(): void {\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS memories (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL,\n text TEXT NOT NULL,\n created_at TEXT NOT NULL,\n source_kind TEXT NOT NULL,\n source_value TEXT NOT NULL,\n confidence REAL NOT NULL,\n scope TEXT NOT NULL,\n tags_json TEXT NOT NULL,\n expires_at TEXT,\n links_json TEXT NOT NULL,\n metadata_json TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at);\n CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope);\n CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(type);\n CREATE INDEX IF NOT EXISTS idx_memories_expires_at ON memories(expires_at);\n CREATE INDEX IF NOT EXISTS idx_memories_source ON memories(source_kind, source_value);\n `);\n }\n\n close(): void {\n this.db.close();\n }\n\n add(input: AddMemoryInput): MemoryEntry {\n const entry = normalizeEntry(input);\n this.init();\n\n this.db.prepare(`\n INSERT INTO memories (\n id,\n type,\n text,\n created_at,\n source_kind,\n source_value,\n confidence,\n scope,\n tags_json,\n expires_at,\n links_json,\n metadata_json\n ) VALUES (\n @id,\n @type,\n @text,\n @created_at,\n @source_kind,\n @source_value,\n @confidence,\n @scope,\n @tags_json,\n @expires_at,\n @links_json,\n @metadata_json\n )\n `).run(this.toRow(entry));\n\n return entry;\n }\n\n get(id: string): MemoryEntry | null {\n this.init();\n const row = this.db.prepare(\"SELECT * FROM memories WHERE id = ?\").get(id) as MemoryRow | undefined;\n return row ? this.fromRow(row) : null;\n }\n\n search(options: SearchOptions): MemoryEntry[] {\n this.init();\n const { sql, params } = this.buildQuery(\n options,\n [\n \"(\",\n \"lower(text) LIKE @query\",\n \"OR lower(tags_json) LIKE @query\",\n \"OR lower(source_kind || ':' || source_value) LIKE @query\",\n \"OR lower(metadata_json) LIKE @query\",\n \")\"\n ].join(\" \"),\n { query: `%${options.query.toLowerCase()}%` },\n \"ORDER BY created_at DESC, confidence DESC, id ASC\"\n );\n\n return this.db.prepare(sql).all(params).map((row) => this.fromRow(row as MemoryRow));\n }\n\n timeline(options: TimelineOptions = {}): MemoryEntry[] {\n this.init();\n const direction = options.order === \"desc\" ? \"DESC\" : \"ASC\";\n const { sql, params } = this.buildQuery(options, undefined, {}, `ORDER BY created_at ${direction}, id ASC`);\n return this.db.prepare(sql).all(params).map((row) => this.fromRow(row as MemoryRow));\n }\n\n exportJsonl(options: ExportOptions = {}): string {\n return this.timeline(options).map((entry) => JSON.stringify(entry)).join(\"\\n\");\n }\n\n importJsonl(input: string): ImportResult {\n this.init();\n const lines = input.split(/\\r?\\n/).map((line) => line.trim()).filter(Boolean);\n const ids: string[] = [];\n let imported = 0;\n let updated = 0;\n\n const statement = this.db.prepare(`\n INSERT INTO memories (\n id,\n type,\n text,\n created_at,\n source_kind,\n source_value,\n confidence,\n scope,\n tags_json,\n expires_at,\n links_json,\n metadata_json\n ) VALUES (\n @id,\n @type,\n @text,\n @created_at,\n @source_kind,\n @source_value,\n @confidence,\n @scope,\n @tags_json,\n @expires_at,\n @links_json,\n @metadata_json\n )\n ON CONFLICT(id) DO UPDATE SET\n type = excluded.type,\n text = excluded.text,\n created_at = excluded.created_at,\n source_kind = excluded.source_kind,\n source_value = excluded.source_value,\n confidence = excluded.confidence,\n scope = excluded.scope,\n tags_json = excluded.tags_json,\n expires_at = excluded.expires_at,\n links_json = excluded.links_json,\n metadata_json = excluded.metadata_json\n `);\n\n const transaction = this.db.transaction(() => {\n for (const line of lines) {\n const entry = normalizeEntry(JSON.parse(line) as AddMemoryInput);\n const exists = this.get(entry.id);\n statement.run(this.toRow(entry));\n ids.push(entry.id);\n if (exists) {\n updated += 1;\n } else {\n imported += 1;\n }\n }\n });\n\n transaction();\n\n return {\n imported,\n updated,\n ids: [...ids].sort((a, b) => a.localeCompare(b))\n };\n }\n\n gc(now?: string | Date): GcResult {\n this.init();\n const nowIso = toIsoString(now);\n const rows = this.db.prepare(\n \"SELECT id FROM memories WHERE expires_at IS NOT NULL AND expires_at <= ? ORDER BY expires_at ASC, id ASC\"\n ).all(nowIso) as Array<{ id: string }>;\n const ids = rows.map((row) => row.id);\n\n if (ids.length > 0) {\n this.db.prepare(\"DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at <= ?\").run(nowIso);\n }\n\n return {\n deleted: ids.length,\n ids,\n now: nowIso\n };\n }\n\n private buildQuery(\n options: QueryOptions,\n extraWhere?: string,\n extraParams: Record<string, unknown> = {},\n orderBy = \"ORDER BY created_at ASC, id ASC\"\n ): { sql: string; params: Record<string, unknown> } {\n const where: string[] = [];\n const params: Record<string, unknown> = { ...extraParams };\n\n if (!options.includeExpired) {\n where.push(\"(expires_at IS NULL OR expires_at > @now)\");\n params.now = toIsoString();\n }\n\n if (options.scopes?.length) {\n const placeholders = options.scopes.map((_, index) => `@scope${index}`);\n where.push(`scope IN (${placeholders.join(\", \")})`);\n for (const [index, scope] of options.scopes.entries()) {\n params[`scope${index}`] = scope;\n }\n }\n\n if (options.types?.length) {\n const placeholders = options.types.map((_, index) => `@type${index}`);\n where.push(`type IN (${placeholders.join(\", \")})`);\n for (const [index, type] of options.types.entries()) {\n params[`type${index}`] = type;\n }\n }\n\n if (options.tags?.length) {\n const tagParts: string[] = [];\n for (const [index, tag] of options.tags.entries()) {\n const key = `tag${index}`;\n tagParts.push(`lower(tags_json) LIKE @${key}`);\n params[key] = `%${tag.toLowerCase()}%`;\n }\n where.push(`(${tagParts.join(\" OR \")})`);\n }\n\n if (options.sourceKind) {\n where.push(\"source_kind = @sourceKind\");\n params.sourceKind = options.sourceKind;\n }\n\n if (options.sourceValue) {\n where.push(\"source_value = @sourceValue\");\n params.sourceValue = options.sourceValue;\n }\n\n if (options.before) {\n where.push(\"created_at <= @before\");\n params.before = toIsoString(options.before);\n }\n\n if (options.after) {\n where.push(\"created_at >= @after\");\n params.after = toIsoString(options.after);\n }\n\n if (extraWhere) {\n where.push(extraWhere);\n }\n\n const limit = Math.max(1, Math.min(options.limit ?? 50, 1000));\n params.limit = limit;\n const whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\n return {\n sql: `SELECT * FROM memories ${whereSql} ${orderBy} LIMIT @limit`,\n params\n };\n }\n\n private toRow(entry: MemoryEntry): Record<string, unknown> {\n return {\n id: entry.id,\n type: entry.type,\n text: entry.text,\n created_at: entry.createdAt,\n source_kind: entry.source.kind,\n source_value: entry.source.value,\n confidence: entry.confidence,\n scope: entry.scope,\n tags_json: serializeJson(entry.tags),\n expires_at: entry.expiresAt ?? null,\n links_json: serializeJson(entry.links ?? []),\n metadata_json: serializeJson(entry.metadata ?? {})\n };\n }\n\n private fromRow(row: MemoryRow): MemoryEntry {\n return {\n id: row.id,\n type: row.type,\n text: row.text,\n createdAt: row.created_at,\n source: {\n kind: row.source_kind,\n value: row.source_value\n },\n confidence: row.confidence,\n scope: row.scope,\n tags: JSON.parse(row.tags_json) as string[],\n expiresAt: row.expires_at ?? undefined,\n links: JSON.parse(row.links_json) as string[],\n metadata: JSON.parse(row.metadata_json) as Record<string, unknown>\n };\n }\n}\n","import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from \"node:http\";\nimport { resolve } from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport * as z from \"zod/v4\";\nimport { ChromaStore } from \"./store.js\";\nimport { memoryScopes, memoryTypes, sourceKinds, type AddMemoryInput, type MemoryEntry, type QueryOptions } from \"./types.js\";\n\nconst memoryTypeSchema = z.enum(memoryTypes);\nconst memoryScopeSchema = z.enum(memoryScopes);\nconst sourceKindSchema = z.enum(sourceKinds);\nconst jsonValueSchema = z.json();\nconst jsonObjectSchema = z.record(z.string(), jsonValueSchema);\nconst sourceSchema = z.object({\n kind: sourceKindSchema,\n value: z.string().trim().min(1)\n});\nconst memoryEntrySchema = z.object({\n id: z.string(),\n type: memoryTypeSchema,\n text: z.string(),\n createdAt: z.string(),\n source: sourceSchema,\n confidence: z.number(),\n scope: memoryScopeSchema,\n tags: z.array(z.string()),\n expiresAt: z.string().optional(),\n links: z.array(z.string()),\n metadata: jsonObjectSchema\n});\nconst queryOptionsSchema = z.object({\n scopes: z.array(memoryScopeSchema).optional(),\n types: z.array(memoryTypeSchema).optional(),\n tags: z.array(z.string()).optional(),\n sourceKind: sourceKindSchema.optional(),\n sourceValue: z.string().trim().min(1).optional(),\n before: z.string().optional(),\n after: z.string().optional(),\n includeExpired: z.boolean().default(false)\n});\n\nexport const chronaAddInputSchema = z.object({\n id: z.string().trim().min(1).optional(),\n type: memoryTypeSchema,\n text: z.string().trim().min(1),\n createdAt: z.string().optional(),\n source: sourceSchema,\n confidence: z.number().min(0).max(1),\n scope: memoryScopeSchema,\n tags: z.array(z.string()).default([]),\n expiresAt: z.string().optional(),\n links: z.array(z.string()).default([]),\n metadata: jsonObjectSchema.default({})\n});\nexport const chronaAddResultSchema = z.object({\n entry: memoryEntrySchema\n});\nexport const chronaGetInputSchema = z.object({\n id: z.string().trim().min(1)\n});\nexport const chronaGetResultSchema = z.object({\n entry: memoryEntrySchema.nullable()\n});\nexport const chronaSearchInputSchema = queryOptionsSchema.extend({\n query: z.string().trim().min(1),\n limit: z.number().int().min(1).max(1000).default(50)\n});\nexport const chronaSearchResultSchema = z.object({\n count: z.number().int().min(0),\n items: z.array(memoryEntrySchema)\n});\nexport const chronaTimelineInputSchema = queryOptionsSchema.extend({\n order: z.enum([\"asc\", \"desc\"]).default(\"asc\"),\n limit: z.number().int().min(1).max(1000).default(50)\n});\nexport const chronaTimelineResultSchema = z.object({\n count: z.number().int().min(0),\n items: z.array(memoryEntrySchema)\n});\nexport const chronaExportInputSchema = queryOptionsSchema.extend({\n order: z.enum([\"asc\", \"desc\"]).default(\"asc\"),\n limit: z.number().int().min(1).max(1000).default(1000)\n});\nexport const chronaExportResultSchema = z.object({\n count: z.number().int().min(0),\n jsonl: z.string()\n});\nexport const chronaImportInputSchema = z.object({\n jsonl: z.string()\n});\nexport const chronaImportResultSchema = z.object({\n imported: z.number().int().min(0),\n updated: z.number().int().min(0),\n ids: z.array(z.string())\n});\nexport const chronaGcInputSchema = z.object({\n now: z.string().optional()\n});\nexport const chronaGcResultSchema = z.object({\n deleted: z.number().int().min(0),\n ids: z.array(z.string()),\n now: z.string()\n});\n\nexport type ChronaAddInput = z.input<typeof chronaAddInputSchema>;\nexport type ChronaAddResult = z.infer<typeof chronaAddResultSchema>;\nexport type ChronaGetInput = z.input<typeof chronaGetInputSchema>;\nexport type ChronaGetResult = z.infer<typeof chronaGetResultSchema>;\nexport type ChronaSearchInput = z.input<typeof chronaSearchInputSchema>;\nexport type ChronaSearchResult = z.infer<typeof chronaSearchResultSchema>;\nexport type ChronaTimelineInput = z.input<typeof chronaTimelineInputSchema>;\nexport type ChronaTimelineResult = z.infer<typeof chronaTimelineResultSchema>;\nexport type ChronaExportInput = z.input<typeof chronaExportInputSchema>;\nexport type ChronaExportResult = z.infer<typeof chronaExportResultSchema>;\nexport type ChronaImportInput = z.input<typeof chronaImportInputSchema>;\nexport type ChronaImportResult = z.infer<typeof chronaImportResultSchema>;\nexport type ChronaGcInput = z.input<typeof chronaGcInputSchema>;\nexport type ChronaGcResult = z.infer<typeof chronaGcResultSchema>;\n\nexport interface ChronaMcpHandlers {\n add(input: ChronaAddInput): ChronaAddResult;\n get(input: ChronaGetInput): ChronaGetResult;\n search(input: ChronaSearchInput): ChronaSearchResult;\n timeline(input: ChronaTimelineInput): ChronaTimelineResult;\n export(input: ChronaExportInput): ChronaExportResult;\n import(input: ChronaImportInput): ChronaImportResult;\n gc(input?: ChronaGcInput): ChronaGcResult;\n}\n\ntype JsonValue = z.infer<typeof jsonValueSchema>;\ntype JsonObject = z.infer<typeof jsonObjectSchema>;\n\nexport interface StartChronaMcpServerOptions {\n dbPath: string;\n port?: number;\n}\n\nfunction withStore<T>(dbPath: string, run: (store: ChromaStore) => T): T {\n const store = new ChromaStore(dbPath);\n\n try {\n return run(store);\n } finally {\n store.close();\n }\n}\n\nfunction toQueryOptions(input: z.infer<typeof queryOptionsSchema> & { limit?: number; order?: \"asc\" | \"desc\" }): QueryOptions {\n return {\n scopes: input.scopes,\n types: input.types,\n tags: input.tags,\n sourceKind: input.sourceKind,\n sourceValue: input.sourceValue,\n before: input.before,\n after: input.after,\n includeExpired: input.includeExpired,\n limit: input.limit\n };\n}\n\nfunction sortJsonValue(value: JsonValue): JsonValue {\n if (Array.isArray(value)) {\n return value.map(sortJsonValue);\n }\n\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, innerValue]) => [key, sortJsonValue(innerValue)])\n );\n }\n\n return value;\n}\n\nfunction toOutputEntry(entry: MemoryEntry): z.infer<typeof memoryEntrySchema> {\n const base = {\n id: entry.id,\n type: entry.type,\n text: entry.text,\n createdAt: entry.createdAt,\n source: {\n kind: entry.source.kind,\n value: entry.source.value\n },\n confidence: entry.confidence,\n scope: entry.scope,\n tags: [...entry.tags],\n links: [...(entry.links ?? [])],\n metadata: sortJsonValue((entry.metadata ?? {}) as JsonObject) as JsonObject\n };\n\n if (entry.expiresAt) {\n return {\n ...base,\n expiresAt: entry.expiresAt\n };\n }\n\n return base;\n}\n\nfunction toToolResult<T extends object>(value: T): { content: Array<{ type: \"text\"; text: string }>; structuredContent: T } {\n const stableValue = sortJsonValue(value as JsonValue) as T;\n\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(stableValue, null, 2)\n }\n ],\n structuredContent: stableValue\n };\n}\n\nfunction lineCount(value: string): number {\n return value === \"\" ? 0 : value.split(\"\\n\").length;\n}\n\nexport function createChronaMcpHandlers(dbPath: string): ChronaMcpHandlers {\n const resolvedDbPath = resolve(dbPath);\n\n return {\n add(input) {\n const args = chronaAddInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => {\n const entry = store.add({\n id: args.id,\n type: args.type,\n text: args.text,\n createdAt: args.createdAt,\n source: args.source,\n confidence: args.confidence,\n scope: args.scope,\n tags: args.tags,\n expiresAt: args.expiresAt,\n links: args.links,\n metadata: args.metadata\n } satisfies AddMemoryInput);\n\n return {\n entry: toOutputEntry(entry)\n };\n });\n },\n get(input) {\n const args = chronaGetInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => {\n const entry = store.get(args.id);\n\n return {\n entry: entry ? toOutputEntry(entry) : null\n };\n });\n },\n search(input) {\n const args = chronaSearchInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => {\n const items = store.search({\n ...toQueryOptions(args),\n query: args.query\n }).map(toOutputEntry);\n\n return {\n count: items.length,\n items\n };\n });\n },\n timeline(input) {\n const args = chronaTimelineInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => {\n const items = store.timeline({\n ...toQueryOptions(args),\n order: args.order\n }).map(toOutputEntry);\n\n return {\n count: items.length,\n items\n };\n });\n },\n export(input) {\n const args = chronaExportInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => {\n const jsonl = store.exportJsonl({\n ...toQueryOptions(args),\n order: args.order\n });\n\n return {\n count: lineCount(jsonl),\n jsonl\n };\n });\n },\n import(input) {\n const args = chronaImportInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => store.importJsonl(args.jsonl));\n },\n gc(input = {}) {\n const args = chronaGcInputSchema.parse(input);\n\n return withStore(resolvedDbPath, (store) => store.gc(args.now));\n }\n };\n}\n\nexport function createChronaMcpServer(dbPath: string): McpServer {\n const handlers = createChronaMcpHandlers(dbPath);\n const server = new McpServer({\n name: \"chrona\",\n version: \"0.1.1\"\n });\n\n server.registerTool(\n \"chrona_add\",\n {\n description: \"Add a memory entry to Chrona.\",\n inputSchema: chronaAddInputSchema,\n outputSchema: chronaAddResultSchema\n },\n async (input) => toToolResult(handlers.add(input))\n );\n\n server.registerTool(\n \"chrona_get\",\n {\n description: \"Get a memory entry by id.\",\n inputSchema: chronaGetInputSchema,\n outputSchema: chronaGetResultSchema,\n annotations: { readOnlyHint: true }\n },\n async (input) => toToolResult(handlers.get(input))\n );\n\n server.registerTool(\n \"chrona_search\",\n {\n description: \"Search memory entries with deterministic ordering.\",\n inputSchema: chronaSearchInputSchema,\n outputSchema: chronaSearchResultSchema,\n annotations: { readOnlyHint: true }\n },\n async (input) => toToolResult(handlers.search(input))\n );\n\n server.registerTool(\n \"chrona_timeline\",\n {\n description: \"List memory entries in time order.\",\n inputSchema: chronaTimelineInputSchema,\n outputSchema: chronaTimelineResultSchema,\n annotations: { readOnlyHint: true }\n },\n async (input) => toToolResult(handlers.timeline(input))\n );\n\n server.registerTool(\n \"chrona_export\",\n {\n description: \"Export matching entries as deterministic JSONL.\",\n inputSchema: chronaExportInputSchema,\n outputSchema: chronaExportResultSchema,\n annotations: { readOnlyHint: true }\n },\n async (input) => toToolResult(handlers.export(input))\n );\n\n server.registerTool(\n \"chrona_import\",\n {\n description: \"Import entries from JSONL.\",\n inputSchema: chronaImportInputSchema,\n outputSchema: chronaImportResultSchema\n },\n async (input) => toToolResult(handlers.import(input))\n );\n\n server.registerTool(\n \"chrona_gc\",\n {\n description: \"Delete expired memory entries.\",\n inputSchema: chronaGcInputSchema,\n outputSchema: chronaGcResultSchema\n },\n async (input) => toToolResult(handlers.gc(input))\n );\n\n return server;\n}\n\nasync function readRequestBody(request: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n\n for await (const chunk of request) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n\n const body = Buffer.concat(chunks).toString(\"utf8\").trim();\n return body === \"\" ? undefined : JSON.parse(body);\n}\n\nfunction sendHttpJson(response: ServerResponse, statusCode: number, payload: unknown): void {\n response.statusCode = statusCode;\n response.setHeader(\"content-type\", \"application/json\");\n response.end(JSON.stringify(payload));\n}\n\nfunction createChronaMcpHttpServer(dbPath: string, port: number): HttpServer {\n return createServer(async (request, response) => {\n const requestUrl = new URL(request.url ?? \"/\", `http://${request.headers.host ?? `127.0.0.1:${port}`}`);\n\n if (requestUrl.pathname !== \"/mcp\") {\n sendHttpJson(response, 404, {\n error: {\n code: 404,\n message: \"Not found\"\n }\n });\n return;\n }\n\n if (request.method !== \"POST\") {\n sendHttpJson(response, 405, {\n error: {\n code: 405,\n message: \"Method not allowed\"\n }\n });\n return;\n }\n\n const server = createChronaMcpServer(dbPath);\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined\n });\n\n response.on(\"close\", () => {\n transport.close().catch(() => undefined);\n server.close().catch(() => undefined);\n });\n\n try {\n const parsedBody = await readRequestBody(request);\n await server.connect(transport);\n await transport.handleRequest(request, response, parsedBody);\n } catch (error) {\n if (!response.headersSent) {\n sendHttpJson(response, 500, {\n error: {\n code: 500,\n message: error instanceof Error ? error.message : String(error)\n }\n });\n }\n }\n });\n}\n\nexport async function startChronaMcpServer(options: StartChronaMcpServerOptions): Promise<void> {\n const resolvedDbPath = resolve(options.dbPath);\n\n if (options.port !== undefined) {\n const server = createChronaMcpHttpServer(resolvedDbPath, options.port);\n\n await new Promise<void>((resolvePromise, reject) => {\n server.once(\"error\", reject);\n server.listen(options.port, \"127.0.0.1\", () => {\n server.off(\"error\", reject);\n console.error(`Chrona MCP server listening on http://127.0.0.1:${options.port}/mcp`);\n resolvePromise();\n });\n });\n\n return;\n }\n\n const server = createChronaMcpServer(resolvedDbPath);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n"],"mappings":";AAAO,IAAM,cAAc,CAAC,YAAY,cAAc,QAAQ,YAAY,YAAY;AAC/E,IAAM,eAAe,CAAC,QAAQ,WAAW,OAAO,QAAQ;AACxD,IAAM,cAAc,CAAC,QAAQ,WAAW,MAAM;;;ACFrD,SAAS,kBAAkB;AAEpB,SAAS,YAAY,OAA+B;AACzD,QAAM,OAAO,iBAAiB,OAAO,QAAQ,QAAQ,IAAI,KAAK,KAAK,IAAI,oBAAI,KAAK;AAChF,QAAM,MAAM,KAAK,YAAY;AAE7B,MAAI,OAAO,MAAM,KAAK,QAAQ,CAAC,GAAG;AAChC,UAAM,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AAQ,SAAS,QAAW;AAC9B,UAAMC,UAAS,0BAA0B,gBAAgB,QAAQ,IAAI;AAErE,UAAM,IAAI,QAAc,CAAC,gBAAgB,WAAW;AAClD,MAAAA,QAAO,KAAK,SAAS,MAAM;AAC3B,MAAAA,QAAO,OAAO,QAAQ,MAAM,aAAa,MAAM;AAC7C,QAAAA,QAAO,IAAI,SAAS,MAAM;AAC1B,gBAAQ,MAAM,mDAAmD,QAAQ,IAAI,MAAM;AACnF,uBAAe;AAAA,MACjB,CAAC;AAAA,IACH,CAAC;AAED;AAAA,EACF;AAEA,QAAM,SAAS,sBAAsB,cAAc;AACnD,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;","names":["resolve","resolve","server"]}
package/dist/cli.cjs CHANGED
@@ -26,7 +26,15 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  // src/cli.ts
27
27
  var import_commander = require("commander");
28
28
  var import_node_fs2 = require("fs");
29
+ var import_node_path3 = require("path");
30
+
31
+ // src/mcp.ts
32
+ var import_node_http = require("http");
29
33
  var import_node_path2 = require("path");
34
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
35
+ var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
36
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
37
+ var z = __toESM(require("zod/v4"), 1);
30
38
 
31
39
  // src/store.ts
32
40
  var import_better_sqlite3 = __toESM(require("better-sqlite3"), 1);
@@ -407,9 +415,409 @@ var ChromaStore = class {
407
415
  }
408
416
  };
409
417
 
418
+ // src/mcp.ts
419
+ var memoryTypeSchema = z.enum(memoryTypes);
420
+ var memoryScopeSchema = z.enum(memoryScopes);
421
+ var sourceKindSchema = z.enum(sourceKinds);
422
+ var jsonValueSchema = z.json();
423
+ var jsonObjectSchema = z.record(z.string(), jsonValueSchema);
424
+ var sourceSchema = z.object({
425
+ kind: sourceKindSchema,
426
+ value: z.string().trim().min(1)
427
+ });
428
+ var memoryEntrySchema = z.object({
429
+ id: z.string(),
430
+ type: memoryTypeSchema,
431
+ text: z.string(),
432
+ createdAt: z.string(),
433
+ source: sourceSchema,
434
+ confidence: z.number(),
435
+ scope: memoryScopeSchema,
436
+ tags: z.array(z.string()),
437
+ expiresAt: z.string().optional(),
438
+ links: z.array(z.string()),
439
+ metadata: jsonObjectSchema
440
+ });
441
+ var queryOptionsSchema = z.object({
442
+ scopes: z.array(memoryScopeSchema).optional(),
443
+ types: z.array(memoryTypeSchema).optional(),
444
+ tags: z.array(z.string()).optional(),
445
+ sourceKind: sourceKindSchema.optional(),
446
+ sourceValue: z.string().trim().min(1).optional(),
447
+ before: z.string().optional(),
448
+ after: z.string().optional(),
449
+ includeExpired: z.boolean().default(false)
450
+ });
451
+ var chronaAddInputSchema = z.object({
452
+ id: z.string().trim().min(1).optional(),
453
+ type: memoryTypeSchema,
454
+ text: z.string().trim().min(1),
455
+ createdAt: z.string().optional(),
456
+ source: sourceSchema,
457
+ confidence: z.number().min(0).max(1),
458
+ scope: memoryScopeSchema,
459
+ tags: z.array(z.string()).default([]),
460
+ expiresAt: z.string().optional(),
461
+ links: z.array(z.string()).default([]),
462
+ metadata: jsonObjectSchema.default({})
463
+ });
464
+ var chronaAddResultSchema = z.object({
465
+ entry: memoryEntrySchema
466
+ });
467
+ var chronaGetInputSchema = z.object({
468
+ id: z.string().trim().min(1)
469
+ });
470
+ var chronaGetResultSchema = z.object({
471
+ entry: memoryEntrySchema.nullable()
472
+ });
473
+ var chronaSearchInputSchema = queryOptionsSchema.extend({
474
+ query: z.string().trim().min(1),
475
+ limit: z.number().int().min(1).max(1e3).default(50)
476
+ });
477
+ var chronaSearchResultSchema = z.object({
478
+ count: z.number().int().min(0),
479
+ items: z.array(memoryEntrySchema)
480
+ });
481
+ var chronaTimelineInputSchema = queryOptionsSchema.extend({
482
+ order: z.enum(["asc", "desc"]).default("asc"),
483
+ limit: z.number().int().min(1).max(1e3).default(50)
484
+ });
485
+ var chronaTimelineResultSchema = z.object({
486
+ count: z.number().int().min(0),
487
+ items: z.array(memoryEntrySchema)
488
+ });
489
+ var chronaExportInputSchema = queryOptionsSchema.extend({
490
+ order: z.enum(["asc", "desc"]).default("asc"),
491
+ limit: z.number().int().min(1).max(1e3).default(1e3)
492
+ });
493
+ var chronaExportResultSchema = z.object({
494
+ count: z.number().int().min(0),
495
+ jsonl: z.string()
496
+ });
497
+ var chronaImportInputSchema = z.object({
498
+ jsonl: z.string()
499
+ });
500
+ var chronaImportResultSchema = z.object({
501
+ imported: z.number().int().min(0),
502
+ updated: z.number().int().min(0),
503
+ ids: z.array(z.string())
504
+ });
505
+ var chronaGcInputSchema = z.object({
506
+ now: z.string().optional()
507
+ });
508
+ var chronaGcResultSchema = z.object({
509
+ deleted: z.number().int().min(0),
510
+ ids: z.array(z.string()),
511
+ now: z.string()
512
+ });
513
+ function withStore(dbPath, run) {
514
+ const store = new ChromaStore(dbPath);
515
+ try {
516
+ return run(store);
517
+ } finally {
518
+ store.close();
519
+ }
520
+ }
521
+ function toQueryOptions(input) {
522
+ return {
523
+ scopes: input.scopes,
524
+ types: input.types,
525
+ tags: input.tags,
526
+ sourceKind: input.sourceKind,
527
+ sourceValue: input.sourceValue,
528
+ before: input.before,
529
+ after: input.after,
530
+ includeExpired: input.includeExpired,
531
+ limit: input.limit
532
+ };
533
+ }
534
+ function sortJsonValue(value) {
535
+ if (Array.isArray(value)) {
536
+ return value.map(sortJsonValue);
537
+ }
538
+ if (value && typeof value === "object") {
539
+ return Object.fromEntries(
540
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, innerValue]) => [key, sortJsonValue(innerValue)])
541
+ );
542
+ }
543
+ return value;
544
+ }
545
+ function toOutputEntry(entry) {
546
+ const base = {
547
+ id: entry.id,
548
+ type: entry.type,
549
+ text: entry.text,
550
+ createdAt: entry.createdAt,
551
+ source: {
552
+ kind: entry.source.kind,
553
+ value: entry.source.value
554
+ },
555
+ confidence: entry.confidence,
556
+ scope: entry.scope,
557
+ tags: [...entry.tags],
558
+ links: [...entry.links ?? []],
559
+ metadata: sortJsonValue(entry.metadata ?? {})
560
+ };
561
+ if (entry.expiresAt) {
562
+ return {
563
+ ...base,
564
+ expiresAt: entry.expiresAt
565
+ };
566
+ }
567
+ return base;
568
+ }
569
+ function toToolResult(value) {
570
+ const stableValue = sortJsonValue(value);
571
+ return {
572
+ content: [
573
+ {
574
+ type: "text",
575
+ text: JSON.stringify(stableValue, null, 2)
576
+ }
577
+ ],
578
+ structuredContent: stableValue
579
+ };
580
+ }
581
+ function lineCount(value) {
582
+ return value === "" ? 0 : value.split("\n").length;
583
+ }
584
+ function createChronaMcpHandlers(dbPath) {
585
+ const resolvedDbPath = (0, import_node_path2.resolve)(dbPath);
586
+ return {
587
+ add(input) {
588
+ const args = chronaAddInputSchema.parse(input);
589
+ return withStore(resolvedDbPath, (store) => {
590
+ const entry = store.add({
591
+ id: args.id,
592
+ type: args.type,
593
+ text: args.text,
594
+ createdAt: args.createdAt,
595
+ source: args.source,
596
+ confidence: args.confidence,
597
+ scope: args.scope,
598
+ tags: args.tags,
599
+ expiresAt: args.expiresAt,
600
+ links: args.links,
601
+ metadata: args.metadata
602
+ });
603
+ return {
604
+ entry: toOutputEntry(entry)
605
+ };
606
+ });
607
+ },
608
+ get(input) {
609
+ const args = chronaGetInputSchema.parse(input);
610
+ return withStore(resolvedDbPath, (store) => {
611
+ const entry = store.get(args.id);
612
+ return {
613
+ entry: entry ? toOutputEntry(entry) : null
614
+ };
615
+ });
616
+ },
617
+ search(input) {
618
+ const args = chronaSearchInputSchema.parse(input);
619
+ return withStore(resolvedDbPath, (store) => {
620
+ const items = store.search({
621
+ ...toQueryOptions(args),
622
+ query: args.query
623
+ }).map(toOutputEntry);
624
+ return {
625
+ count: items.length,
626
+ items
627
+ };
628
+ });
629
+ },
630
+ timeline(input) {
631
+ const args = chronaTimelineInputSchema.parse(input);
632
+ return withStore(resolvedDbPath, (store) => {
633
+ const items = store.timeline({
634
+ ...toQueryOptions(args),
635
+ order: args.order
636
+ }).map(toOutputEntry);
637
+ return {
638
+ count: items.length,
639
+ items
640
+ };
641
+ });
642
+ },
643
+ export(input) {
644
+ const args = chronaExportInputSchema.parse(input);
645
+ return withStore(resolvedDbPath, (store) => {
646
+ const jsonl = store.exportJsonl({
647
+ ...toQueryOptions(args),
648
+ order: args.order
649
+ });
650
+ return {
651
+ count: lineCount(jsonl),
652
+ jsonl
653
+ };
654
+ });
655
+ },
656
+ import(input) {
657
+ const args = chronaImportInputSchema.parse(input);
658
+ return withStore(resolvedDbPath, (store) => store.importJsonl(args.jsonl));
659
+ },
660
+ gc(input = {}) {
661
+ const args = chronaGcInputSchema.parse(input);
662
+ return withStore(resolvedDbPath, (store) => store.gc(args.now));
663
+ }
664
+ };
665
+ }
666
+ function createChronaMcpServer(dbPath) {
667
+ const handlers = createChronaMcpHandlers(dbPath);
668
+ const server = new import_mcp.McpServer({
669
+ name: "chrona",
670
+ version: "0.1.1"
671
+ });
672
+ server.registerTool(
673
+ "chrona_add",
674
+ {
675
+ description: "Add a memory entry to Chrona.",
676
+ inputSchema: chronaAddInputSchema,
677
+ outputSchema: chronaAddResultSchema
678
+ },
679
+ async (input) => toToolResult(handlers.add(input))
680
+ );
681
+ server.registerTool(
682
+ "chrona_get",
683
+ {
684
+ description: "Get a memory entry by id.",
685
+ inputSchema: chronaGetInputSchema,
686
+ outputSchema: chronaGetResultSchema,
687
+ annotations: { readOnlyHint: true }
688
+ },
689
+ async (input) => toToolResult(handlers.get(input))
690
+ );
691
+ server.registerTool(
692
+ "chrona_search",
693
+ {
694
+ description: "Search memory entries with deterministic ordering.",
695
+ inputSchema: chronaSearchInputSchema,
696
+ outputSchema: chronaSearchResultSchema,
697
+ annotations: { readOnlyHint: true }
698
+ },
699
+ async (input) => toToolResult(handlers.search(input))
700
+ );
701
+ server.registerTool(
702
+ "chrona_timeline",
703
+ {
704
+ description: "List memory entries in time order.",
705
+ inputSchema: chronaTimelineInputSchema,
706
+ outputSchema: chronaTimelineResultSchema,
707
+ annotations: { readOnlyHint: true }
708
+ },
709
+ async (input) => toToolResult(handlers.timeline(input))
710
+ );
711
+ server.registerTool(
712
+ "chrona_export",
713
+ {
714
+ description: "Export matching entries as deterministic JSONL.",
715
+ inputSchema: chronaExportInputSchema,
716
+ outputSchema: chronaExportResultSchema,
717
+ annotations: { readOnlyHint: true }
718
+ },
719
+ async (input) => toToolResult(handlers.export(input))
720
+ );
721
+ server.registerTool(
722
+ "chrona_import",
723
+ {
724
+ description: "Import entries from JSONL.",
725
+ inputSchema: chronaImportInputSchema,
726
+ outputSchema: chronaImportResultSchema
727
+ },
728
+ async (input) => toToolResult(handlers.import(input))
729
+ );
730
+ server.registerTool(
731
+ "chrona_gc",
732
+ {
733
+ description: "Delete expired memory entries.",
734
+ inputSchema: chronaGcInputSchema,
735
+ outputSchema: chronaGcResultSchema
736
+ },
737
+ async (input) => toToolResult(handlers.gc(input))
738
+ );
739
+ return server;
740
+ }
741
+ async function readRequestBody(request) {
742
+ const chunks = [];
743
+ for await (const chunk of request) {
744
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
745
+ }
746
+ const body = Buffer.concat(chunks).toString("utf8").trim();
747
+ return body === "" ? void 0 : JSON.parse(body);
748
+ }
749
+ function sendHttpJson(response, statusCode, payload) {
750
+ response.statusCode = statusCode;
751
+ response.setHeader("content-type", "application/json");
752
+ response.end(JSON.stringify(payload));
753
+ }
754
+ function createChronaMcpHttpServer(dbPath, port) {
755
+ return (0, import_node_http.createServer)(async (request, response) => {
756
+ const requestUrl = new URL(request.url ?? "/", `http://${request.headers.host ?? `127.0.0.1:${port}`}`);
757
+ if (requestUrl.pathname !== "/mcp") {
758
+ sendHttpJson(response, 404, {
759
+ error: {
760
+ code: 404,
761
+ message: "Not found"
762
+ }
763
+ });
764
+ return;
765
+ }
766
+ if (request.method !== "POST") {
767
+ sendHttpJson(response, 405, {
768
+ error: {
769
+ code: 405,
770
+ message: "Method not allowed"
771
+ }
772
+ });
773
+ return;
774
+ }
775
+ const server = createChronaMcpServer(dbPath);
776
+ const transport = new import_streamableHttp.StreamableHTTPServerTransport({
777
+ sessionIdGenerator: void 0
778
+ });
779
+ response.on("close", () => {
780
+ transport.close().catch(() => void 0);
781
+ server.close().catch(() => void 0);
782
+ });
783
+ try {
784
+ const parsedBody = await readRequestBody(request);
785
+ await server.connect(transport);
786
+ await transport.handleRequest(request, response, parsedBody);
787
+ } catch (error) {
788
+ if (!response.headersSent) {
789
+ sendHttpJson(response, 500, {
790
+ error: {
791
+ code: 500,
792
+ message: error instanceof Error ? error.message : String(error)
793
+ }
794
+ });
795
+ }
796
+ }
797
+ });
798
+ }
799
+ async function startChronaMcpServer(options) {
800
+ const resolvedDbPath = (0, import_node_path2.resolve)(options.dbPath);
801
+ if (options.port !== void 0) {
802
+ const server2 = createChronaMcpHttpServer(resolvedDbPath, options.port);
803
+ await new Promise((resolvePromise, reject) => {
804
+ server2.once("error", reject);
805
+ server2.listen(options.port, "127.0.0.1", () => {
806
+ server2.off("error", reject);
807
+ console.error(`Chrona MCP server listening on http://127.0.0.1:${options.port}/mcp`);
808
+ resolvePromise();
809
+ });
810
+ });
811
+ return;
812
+ }
813
+ const server = createChronaMcpServer(resolvedDbPath);
814
+ const transport = new import_stdio.StdioServerTransport();
815
+ await server.connect(transport);
816
+ }
817
+
410
818
  // src/cli.ts
411
819
  function openStore(options) {
412
- return new ChromaStore((0, import_node_path2.resolve)(options.db ?? process.env.CHRONA_DB ?? ".chrona/chrona.db"));
820
+ return new ChromaStore((0, import_node_path3.resolve)(options.db ?? process.env.CHRONA_DB ?? ".chrona/chrona.db"));
413
821
  }
414
822
  function emit(value, asJson) {
415
823
  if (asJson) {
@@ -435,7 +843,7 @@ function parseTags(value) {
435
843
  return tags.length ? tags : void 0;
436
844
  }
437
845
  var program = new import_commander.Command();
438
- program.name("chrona").description("Time-aware local memory store for agents").version("0.1.0").option("--db <path>", "Path to the SQLite database").option("--json", "Emit machine-readable JSON");
846
+ program.name("chrona").description("Time-aware local memory store for agents").version("0.1.1").option("--db <path>", "Path to the SQLite database").option("--json", "Emit machine-readable JSON");
439
847
  program.command("init").description("Create or open the memory database").action(() => {
440
848
  const options = program.opts();
441
849
  const store = openStore(options);
@@ -524,9 +932,9 @@ program.command("export").description("Export entries as JSONL").option("--outpu
524
932
  limit: Number(commandOptions.limit)
525
933
  });
526
934
  if (commandOptions.output) {
527
- (0, import_node_fs2.writeFileSync)((0, import_node_path2.resolve)(commandOptions.output), jsonl ? `${jsonl}
935
+ (0, import_node_fs2.writeFileSync)((0, import_node_path3.resolve)(commandOptions.output), jsonl ? `${jsonl}
528
936
  ` : "");
529
- emit({ ok: true, output: (0, import_node_path2.resolve)(commandOptions.output) }, options.json);
937
+ emit({ ok: true, output: (0, import_node_path3.resolve)(commandOptions.output) }, options.json);
530
938
  } else {
531
939
  emit(jsonl, false);
532
940
  }
@@ -535,7 +943,7 @@ program.command("export").description("Export entries as JSONL").option("--outpu
535
943
  program.command("import").description("Import entries from JSONL").argument("[input]", "Path to JSONL file, or - for stdin", "-").action((input) => {
536
944
  const options = program.opts();
537
945
  const store = openStore(options);
538
- const jsonl = input === "-" ? (0, import_node_fs2.readFileSync)(0, "utf8") : (0, import_node_fs2.readFileSync)((0, import_node_path2.resolve)(input), "utf8");
946
+ const jsonl = input === "-" ? (0, import_node_fs2.readFileSync)(0, "utf8") : (0, import_node_fs2.readFileSync)((0, import_node_path3.resolve)(input), "utf8");
539
947
  const result = store.importJsonl(jsonl);
540
948
  emit(result, true);
541
949
  store.close();
@@ -547,6 +955,21 @@ program.command("gc").description("Delete expired entries").option("--now <iso>"
547
955
  emit(result, true);
548
956
  store.close();
549
957
  });
958
+ program.command("mcp").description("Run the Chrona MCP server").option("--db <path>", "Path to the SQLite database").option("--stdio", "Use stdio transport").option("--port <number>", "Serve MCP over Streamable HTTP on the given port").action(async (commandOptions) => {
959
+ const options = program.opts();
960
+ const dbPath = commandOptions.db ?? options.db ?? process.env.CHRONA_DB ?? ".chrona/chrona.db";
961
+ const port = commandOptions.port === void 0 ? void 0 : Number(commandOptions.port);
962
+ if (commandOptions.stdio && port !== void 0) {
963
+ throw new Error("Choose either --stdio or --port, not both");
964
+ }
965
+ if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) {
966
+ throw new Error(`Invalid port: ${String(commandOptions.port)}`);
967
+ }
968
+ await startChronaMcpServer({
969
+ dbPath,
970
+ port
971
+ });
972
+ });
550
973
  program.parseAsync(process.argv).catch((error) => {
551
974
  const message = error instanceof Error ? error.message : String(error);
552
975
  console.error(message);