@ulrichc1/sparn 1.1.0 → 1.2.0

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.
package/dist/index.d.cts CHANGED
@@ -1,3 +1,5 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+
1
3
  /**
2
4
  * Core memory entry types for Sparn's context optimization engine.
3
5
  * Maps to neuroscience-inspired memory model with decay and state transitions.
@@ -241,6 +243,8 @@ interface RealtimeConfig {
241
243
  incremental: boolean;
242
244
  /** Sliding window size for context entries (default: 500) */
243
245
  windowSize: number;
246
+ /** Consolidation interval in hours, or null for disabled (default: null) */
247
+ consolidationInterval: number | null;
244
248
  }
245
249
  /**
246
250
  * Complete Sparn configuration.
@@ -906,6 +910,35 @@ interface SessionWatcher {
906
910
  */
907
911
  declare function createSessionWatcher(config: SessionWatcherConfig): SessionWatcher;
908
912
 
913
+ /**
914
+ * Sparn MCP Server - Model Context Protocol server implementation
915
+ *
916
+ * Exposes Sparn's neuroscience-inspired context optimization as MCP tools,
917
+ * enabling integration with Claude Desktop, VS Code, and other MCP clients.
918
+ *
919
+ * Tools:
920
+ * - sparn_optimize: Optimize context with configurable options
921
+ * - sparn_stats: Get optimization statistics
922
+ * - sparn_consolidate: Run memory consolidation (sleep replay)
923
+ */
924
+
925
+ /**
926
+ * Options for creating the Sparn MCP server.
927
+ */
928
+ interface SparnMcpServerOptions {
929
+ /** KV memory store instance */
930
+ memory: KVMemory;
931
+ /** Sparn configuration (defaults to DEFAULT_CONFIG) */
932
+ config?: SparnConfig;
933
+ }
934
+ /**
935
+ * Create and configure the Sparn MCP server with all tools registered.
936
+ *
937
+ * @param options - Server options including memory store and config
938
+ * @returns Configured McpServer instance ready to connect to a transport
939
+ */
940
+ declare function createSparnMcpServer(options: SparnMcpServerOptions): McpServer;
941
+
909
942
  /**
910
943
  * Context Parser - Shared utilities for parsing agent contexts into memory entries
911
944
  *
@@ -1003,4 +1036,4 @@ declare function createLogger(verbose?: boolean): Logger;
1003
1036
  */
1004
1037
  declare function estimateTokens(text: string): number;
1005
1038
 
1006
- export { type AgentAdapter, type AgentType, type BTSPEmbedder, type BlockType, type BudgetPruner, type BudgetPrunerConfig, type ConfidenceState, type ConfidenceStates, type ConfidenceStatesConfig, type ConsolidateResult, type ContextPipeline, type ContextPipelineConfig, type ContextPipelineStats, DEFAULT_CONFIG, type DaemonCommand, type DaemonStartResult, type DaemonStatusResult, type DaemonStopResult, type DecayConfig, type DuplicateGroup, type EngramScorer, type EngramScorerConfig, type FilePosition, type FileTracker, type IncrementalOptimizer, type IncrementalOptimizerConfig, type IncrementalOptimizerState, type KVMemory, type LogLevel, type Logger, type MemoryEntry, type MemoryQueryFilters, type OptimizationResult, type OptimizeOptions, type PruneResult, type PruningConfig, type RealtimeConfig, type SessionStats, type SessionWatcher, type SessionWatcherConfig, type SleepCompressor, type SparnConfig, type SparsePruner, type SparsePrunerConfig, type StateDistribution, type StatesConfig, type UIConfig, createBTSPEmbedder, createBudgetPruner, createBudgetPrunerFromConfig, createClaudeCodeAdapter, createConfidenceStates, createContextPipeline, createDaemonCommand, createEngramScorer, createEntry, createFileTracker, createGenericAdapter, createIncrementalOptimizer, createKVMemory, createLogger, createSessionWatcher, createSleepCompressor, createSparsePruner, estimateTokens, hashContent, parseClaudeCodeContext, parseGenericContext };
1039
+ export { type AgentAdapter, type AgentType, type BTSPEmbedder, type BlockType, type BudgetPruner, type BudgetPrunerConfig, type ConfidenceState, type ConfidenceStates, type ConfidenceStatesConfig, type ConsolidateResult, type ContextPipeline, type ContextPipelineConfig, type ContextPipelineStats, DEFAULT_CONFIG, type DaemonCommand, type DaemonStartResult, type DaemonStatusResult, type DaemonStopResult, type DecayConfig, type DuplicateGroup, type EngramScorer, type EngramScorerConfig, type FilePosition, type FileTracker, type IncrementalOptimizer, type IncrementalOptimizerConfig, type IncrementalOptimizerState, type KVMemory, type LogLevel, type Logger, type MemoryEntry, type MemoryQueryFilters, type OptimizationResult, type OptimizeOptions, type PruneResult, type PruningConfig, type RealtimeConfig, type SessionStats, type SessionWatcher, type SessionWatcherConfig, type SleepCompressor, type SparnConfig, type SparnMcpServerOptions, type SparsePruner, type SparsePrunerConfig, type StateDistribution, type StatesConfig, type UIConfig, createBTSPEmbedder, createBudgetPruner, createBudgetPrunerFromConfig, createClaudeCodeAdapter, createConfidenceStates, createContextPipeline, createDaemonCommand, createEngramScorer, createEntry, createFileTracker, createGenericAdapter, createIncrementalOptimizer, createKVMemory, createLogger, createSessionWatcher, createSleepCompressor, createSparnMcpServer, createSparsePruner, estimateTokens, hashContent, parseClaudeCodeContext, parseGenericContext };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+
1
3
  /**
2
4
  * Core memory entry types for Sparn's context optimization engine.
3
5
  * Maps to neuroscience-inspired memory model with decay and state transitions.
@@ -241,6 +243,8 @@ interface RealtimeConfig {
241
243
  incremental: boolean;
242
244
  /** Sliding window size for context entries (default: 500) */
243
245
  windowSize: number;
246
+ /** Consolidation interval in hours, or null for disabled (default: null) */
247
+ consolidationInterval: number | null;
244
248
  }
245
249
  /**
246
250
  * Complete Sparn configuration.
@@ -906,6 +910,35 @@ interface SessionWatcher {
906
910
  */
907
911
  declare function createSessionWatcher(config: SessionWatcherConfig): SessionWatcher;
908
912
 
913
+ /**
914
+ * Sparn MCP Server - Model Context Protocol server implementation
915
+ *
916
+ * Exposes Sparn's neuroscience-inspired context optimization as MCP tools,
917
+ * enabling integration with Claude Desktop, VS Code, and other MCP clients.
918
+ *
919
+ * Tools:
920
+ * - sparn_optimize: Optimize context with configurable options
921
+ * - sparn_stats: Get optimization statistics
922
+ * - sparn_consolidate: Run memory consolidation (sleep replay)
923
+ */
924
+
925
+ /**
926
+ * Options for creating the Sparn MCP server.
927
+ */
928
+ interface SparnMcpServerOptions {
929
+ /** KV memory store instance */
930
+ memory: KVMemory;
931
+ /** Sparn configuration (defaults to DEFAULT_CONFIG) */
932
+ config?: SparnConfig;
933
+ }
934
+ /**
935
+ * Create and configure the Sparn MCP server with all tools registered.
936
+ *
937
+ * @param options - Server options including memory store and config
938
+ * @returns Configured McpServer instance ready to connect to a transport
939
+ */
940
+ declare function createSparnMcpServer(options: SparnMcpServerOptions): McpServer;
941
+
909
942
  /**
910
943
  * Context Parser - Shared utilities for parsing agent contexts into memory entries
911
944
  *
@@ -1003,4 +1036,4 @@ declare function createLogger(verbose?: boolean): Logger;
1003
1036
  */
1004
1037
  declare function estimateTokens(text: string): number;
1005
1038
 
1006
- export { type AgentAdapter, type AgentType, type BTSPEmbedder, type BlockType, type BudgetPruner, type BudgetPrunerConfig, type ConfidenceState, type ConfidenceStates, type ConfidenceStatesConfig, type ConsolidateResult, type ContextPipeline, type ContextPipelineConfig, type ContextPipelineStats, DEFAULT_CONFIG, type DaemonCommand, type DaemonStartResult, type DaemonStatusResult, type DaemonStopResult, type DecayConfig, type DuplicateGroup, type EngramScorer, type EngramScorerConfig, type FilePosition, type FileTracker, type IncrementalOptimizer, type IncrementalOptimizerConfig, type IncrementalOptimizerState, type KVMemory, type LogLevel, type Logger, type MemoryEntry, type MemoryQueryFilters, type OptimizationResult, type OptimizeOptions, type PruneResult, type PruningConfig, type RealtimeConfig, type SessionStats, type SessionWatcher, type SessionWatcherConfig, type SleepCompressor, type SparnConfig, type SparsePruner, type SparsePrunerConfig, type StateDistribution, type StatesConfig, type UIConfig, createBTSPEmbedder, createBudgetPruner, createBudgetPrunerFromConfig, createClaudeCodeAdapter, createConfidenceStates, createContextPipeline, createDaemonCommand, createEngramScorer, createEntry, createFileTracker, createGenericAdapter, createIncrementalOptimizer, createKVMemory, createLogger, createSessionWatcher, createSleepCompressor, createSparsePruner, estimateTokens, hashContent, parseClaudeCodeContext, parseGenericContext };
1039
+ export { type AgentAdapter, type AgentType, type BTSPEmbedder, type BlockType, type BudgetPruner, type BudgetPrunerConfig, type ConfidenceState, type ConfidenceStates, type ConfidenceStatesConfig, type ConsolidateResult, type ContextPipeline, type ContextPipelineConfig, type ContextPipelineStats, DEFAULT_CONFIG, type DaemonCommand, type DaemonStartResult, type DaemonStatusResult, type DaemonStopResult, type DecayConfig, type DuplicateGroup, type EngramScorer, type EngramScorerConfig, type FilePosition, type FileTracker, type IncrementalOptimizer, type IncrementalOptimizerConfig, type IncrementalOptimizerState, type KVMemory, type LogLevel, type Logger, type MemoryEntry, type MemoryQueryFilters, type OptimizationResult, type OptimizeOptions, type PruneResult, type PruningConfig, type RealtimeConfig, type SessionStats, type SessionWatcher, type SessionWatcherConfig, type SleepCompressor, type SparnConfig, type SparnMcpServerOptions, type SparsePruner, type SparsePrunerConfig, type StateDistribution, type StatesConfig, type UIConfig, createBTSPEmbedder, createBudgetPruner, createBudgetPrunerFromConfig, createClaudeCodeAdapter, createConfidenceStates, createContextPipeline, createDaemonCommand, createEngramScorer, createEntry, createFileTracker, createGenericAdapter, createIncrementalOptimizer, createKVMemory, createLogger, createSessionWatcher, createSleepCompressor, createSparnMcpServer, createSparsePruner, estimateTokens, hashContent, parseClaudeCodeContext, parseGenericContext };
package/dist/index.js CHANGED
@@ -1,10 +1,3 @@
1
- // node_modules/tsup/assets/esm_shims.js
2
- import path from "path";
3
- import { fileURLToPath } from "url";
4
- var getFilename = () => fileURLToPath(import.meta.url);
5
- var getDirname = () => path.dirname(getFilename());
6
- var __dirname = /* @__PURE__ */ getDirname();
7
-
8
1
  // src/core/btsp-embedder.ts
9
2
  import { randomUUID } from "crypto";
10
3
 
@@ -1316,6 +1309,7 @@ function createSleepCompressor() {
1316
1309
  import { fork } from "child_process";
1317
1310
  import { existsSync as existsSync2, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
1318
1311
  import { dirname, join } from "path";
1312
+ import { fileURLToPath } from "url";
1319
1313
  function createDaemonCommand() {
1320
1314
  function isDaemonRunning(pidFile) {
1321
1315
  if (!existsSync2(pidFile)) {
@@ -1362,7 +1356,9 @@ function createDaemonCommand() {
1362
1356
  };
1363
1357
  }
1364
1358
  try {
1365
- const daemonPath = join(__dirname, "index.js");
1359
+ const __filename2 = fileURLToPath(import.meta.url);
1360
+ const __dirname2 = dirname(__filename2);
1361
+ const daemonPath = join(__dirname2, "index.js");
1366
1362
  const child = fork(daemonPath, [], {
1367
1363
  detached: true,
1368
1364
  stdio: "ignore",
@@ -1711,6 +1707,10 @@ function createSessionWatcher(config) {
1711
1707
  };
1712
1708
  }
1713
1709
 
1710
+ // src/mcp/server.ts
1711
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1712
+ import { z } from "zod";
1713
+
1714
1714
  // src/types/config.ts
1715
1715
  var DEFAULT_CONFIG = {
1716
1716
  pruning: {
@@ -1740,10 +1740,217 @@ var DEFAULT_CONFIG = {
1740
1740
  logFile: ".sparn/daemon.log",
1741
1741
  debounceMs: 5e3,
1742
1742
  incremental: true,
1743
- windowSize: 500
1743
+ windowSize: 500,
1744
+ consolidationInterval: null
1744
1745
  }
1745
1746
  };
1746
1747
 
1748
+ // src/mcp/server.ts
1749
+ function createSparnMcpServer(options) {
1750
+ const { memory, config = DEFAULT_CONFIG } = options;
1751
+ const server = new McpServer({
1752
+ name: "sparn",
1753
+ version: "1.1.1"
1754
+ });
1755
+ registerOptimizeTool(server, memory, config);
1756
+ registerStatsTool(server, memory);
1757
+ registerConsolidateTool(server, memory);
1758
+ return server;
1759
+ }
1760
+ function registerOptimizeTool(server, memory, config) {
1761
+ server.registerTool(
1762
+ "sparn_optimize",
1763
+ {
1764
+ title: "Sparn Optimize",
1765
+ description: "Optimize context using neuroscience-inspired pruning. Applies BTSP detection, engram scoring, confidence states, and sparse pruning to reduce token usage while preserving important information.",
1766
+ inputSchema: {
1767
+ context: z.string().describe("The context text to optimize"),
1768
+ dryRun: z.boolean().optional().default(false).describe("If true, do not persist changes to the memory store"),
1769
+ verbose: z.boolean().optional().default(false).describe("If true, include per-entry details in the response"),
1770
+ threshold: z.number().min(0).max(100).optional().describe("Custom pruning threshold (1-100, overrides config)")
1771
+ }
1772
+ },
1773
+ async ({ context, dryRun, verbose, threshold }) => {
1774
+ try {
1775
+ const effectiveConfig = threshold ? { ...config, pruning: { ...config.pruning, threshold } } : config;
1776
+ const adapter = createGenericAdapter(memory, effectiveConfig);
1777
+ const result = await adapter.optimize(context, {
1778
+ dryRun,
1779
+ verbose,
1780
+ threshold
1781
+ });
1782
+ const response = {
1783
+ optimizedContext: result.optimizedContext,
1784
+ tokensBefore: result.tokensBefore,
1785
+ tokensAfter: result.tokensAfter,
1786
+ reduction: `${(result.reduction * 100).toFixed(1)}%`,
1787
+ entriesProcessed: result.entriesProcessed,
1788
+ entriesKept: result.entriesKept,
1789
+ durationMs: result.durationMs,
1790
+ stateDistribution: result.stateDistribution,
1791
+ ...verbose && result.details ? { details: result.details } : {}
1792
+ };
1793
+ return {
1794
+ content: [
1795
+ {
1796
+ type: "text",
1797
+ text: JSON.stringify(response, null, 2)
1798
+ }
1799
+ ]
1800
+ };
1801
+ } catch (error) {
1802
+ const message = error instanceof Error ? error.message : String(error);
1803
+ return {
1804
+ content: [
1805
+ {
1806
+ type: "text",
1807
+ text: JSON.stringify({ error: message })
1808
+ }
1809
+ ],
1810
+ isError: true
1811
+ };
1812
+ }
1813
+ }
1814
+ );
1815
+ }
1816
+ function registerStatsTool(server, memory) {
1817
+ server.registerTool(
1818
+ "sparn_stats",
1819
+ {
1820
+ title: "Sparn Stats",
1821
+ description: "Get optimization statistics including total commands run, tokens saved, and average reduction percentage.",
1822
+ inputSchema: {
1823
+ reset: z.boolean().optional().default(false).describe("If true, reset all optimization statistics")
1824
+ }
1825
+ },
1826
+ async ({ reset }) => {
1827
+ try {
1828
+ if (reset) {
1829
+ await memory.clearOptimizationStats();
1830
+ return {
1831
+ content: [
1832
+ {
1833
+ type: "text",
1834
+ text: JSON.stringify(
1835
+ {
1836
+ message: "Optimization statistics have been reset.",
1837
+ totalCommands: 0,
1838
+ totalTokensSaved: 0,
1839
+ averageReduction: "0.0%"
1840
+ },
1841
+ null,
1842
+ 2
1843
+ )
1844
+ }
1845
+ ]
1846
+ };
1847
+ }
1848
+ const stats = await memory.getOptimizationStats();
1849
+ const totalCommands = stats.length;
1850
+ const totalTokensSaved = stats.reduce(
1851
+ (sum, s) => sum + (s.tokens_before - s.tokens_after),
1852
+ 0
1853
+ );
1854
+ const averageReduction = totalCommands > 0 ? stats.reduce((sum, s) => {
1855
+ const reduction = s.tokens_before > 0 ? (s.tokens_before - s.tokens_after) / s.tokens_before : 0;
1856
+ return sum + reduction;
1857
+ }, 0) / totalCommands : 0;
1858
+ const recentOptimizations = stats.slice(0, 10).map((s) => ({
1859
+ timestamp: new Date(s.timestamp).toISOString(),
1860
+ tokensBefore: s.tokens_before,
1861
+ tokensAfter: s.tokens_after,
1862
+ entriesPruned: s.entries_pruned,
1863
+ durationMs: s.duration_ms,
1864
+ reduction: `${((s.tokens_before - s.tokens_after) / Math.max(s.tokens_before, 1) * 100).toFixed(1)}%`
1865
+ }));
1866
+ const response = {
1867
+ totalCommands,
1868
+ totalTokensSaved,
1869
+ averageReduction: `${(averageReduction * 100).toFixed(1)}%`,
1870
+ recentOptimizations
1871
+ };
1872
+ return {
1873
+ content: [
1874
+ {
1875
+ type: "text",
1876
+ text: JSON.stringify(response, null, 2)
1877
+ }
1878
+ ]
1879
+ };
1880
+ } catch (error) {
1881
+ const message = error instanceof Error ? error.message : String(error);
1882
+ return {
1883
+ content: [
1884
+ {
1885
+ type: "text",
1886
+ text: JSON.stringify({ error: message })
1887
+ }
1888
+ ],
1889
+ isError: true
1890
+ };
1891
+ }
1892
+ }
1893
+ );
1894
+ }
1895
+ function registerConsolidateTool(server, memory) {
1896
+ server.registerTool(
1897
+ "sparn_consolidate",
1898
+ {
1899
+ title: "Sparn Consolidate",
1900
+ description: "Run memory consolidation (sleep replay). Removes decayed entries and merges duplicates to reclaim space. Inspired by the neuroscience principle of sleep-based memory consolidation."
1901
+ },
1902
+ async () => {
1903
+ try {
1904
+ const allIds = await memory.list();
1905
+ const allEntries = await Promise.all(
1906
+ allIds.map(async (id) => {
1907
+ const entry = await memory.get(id);
1908
+ return entry;
1909
+ })
1910
+ );
1911
+ const entries = allEntries.filter((e) => e !== null);
1912
+ const compressor = createSleepCompressor();
1913
+ const result = compressor.consolidate(entries);
1914
+ for (const removed of result.removed) {
1915
+ await memory.delete(removed.id);
1916
+ }
1917
+ for (const kept of result.kept) {
1918
+ await memory.put(kept);
1919
+ }
1920
+ await memory.compact();
1921
+ const response = {
1922
+ entriesBefore: result.entriesBefore,
1923
+ entriesAfter: result.entriesAfter,
1924
+ decayedRemoved: result.decayedRemoved,
1925
+ duplicatesRemoved: result.duplicatesRemoved,
1926
+ compressionRatio: `${(result.compressionRatio * 100).toFixed(1)}%`,
1927
+ durationMs: result.durationMs,
1928
+ vacuumCompleted: true
1929
+ };
1930
+ return {
1931
+ content: [
1932
+ {
1933
+ type: "text",
1934
+ text: JSON.stringify(response, null, 2)
1935
+ }
1936
+ ]
1937
+ };
1938
+ } catch (error) {
1939
+ const message = error instanceof Error ? error.message : String(error);
1940
+ return {
1941
+ content: [
1942
+ {
1943
+ type: "text",
1944
+ text: JSON.stringify({ error: message })
1945
+ }
1946
+ ],
1947
+ isError: true
1948
+ };
1949
+ }
1950
+ }
1951
+ );
1952
+ }
1953
+
1747
1954
  // src/utils/logger.ts
1748
1955
  function createLogger(verbose = false) {
1749
1956
  return {
@@ -1781,6 +1988,7 @@ export {
1781
1988
  createLogger,
1782
1989
  createSessionWatcher,
1783
1990
  createSleepCompressor,
1991
+ createSparnMcpServer,
1784
1992
  createSparsePruner,
1785
1993
  estimateTokens,
1786
1994
  hashContent,