@iworkforces/tracelattice 2.0.8 → 2.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.
- package/README.md +88 -64
- package/dist/ServerConfig.d.ts +1 -1
- package/dist/ServerConfig.js.map +1 -1
- package/dist/cli.js +18 -73
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigLoader.d.ts +29 -26
- package/dist/config/ConfigLoader.d.ts.map +1 -1
- package/dist/config/ConfigLoader.js +40 -36
- package/dist/config/ConfigLoader.js.map +1 -1
- package/dist/contracts/PersistenceBackend.d.ts +7 -108
- package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
- package/dist/contracts/PersistenceBackend.js +1 -6
- package/dist/contracts/calibrator.d.ts +6 -6
- package/dist/contracts/calibrator.d.ts.map +1 -1
- package/dist/contracts/ids.d.ts +1 -8
- package/dist/contracts/ids.d.ts.map +1 -1
- package/dist/contracts/ids.js +2 -3
- package/dist/contracts/ids.js.map +1 -1
- package/dist/contracts/interfaces.d.ts +4 -6
- package/dist/contracts/interfaces.d.ts.map +1 -1
- package/dist/contracts/persistence-work.d.ts +2 -3
- package/dist/contracts/persistence-work.d.ts.map +1 -1
- package/dist/core/HistoryManager.d.ts +12 -16
- package/dist/core/HistoryManager.d.ts.map +1 -1
- package/dist/core/HistoryManager.js +19 -40
- package/dist/core/HistoryManager.js.map +1 -1
- package/dist/core/IHistoryManager.d.ts +22 -30
- package/dist/core/IHistoryManager.d.ts.map +1 -1
- package/dist/core/InputNormalizer.d.ts +7 -24
- package/dist/core/InputNormalizer.d.ts.map +1 -1
- package/dist/core/InputNormalizer.js +3 -9
- package/dist/core/InputNormalizer.js.map +1 -1
- package/dist/core/PersistenceBuffer.d.ts +3 -20
- package/dist/core/PersistenceBuffer.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.js +1 -4
- package/dist/core/PersistenceBuffer.js.map +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js +4 -10
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/PersistenceWriter.d.ts.map +1 -1
- package/dist/core/PersistenceWriter.js +3 -12
- package/dist/core/PersistenceWriter.js.map +1 -1
- package/dist/core/SessionErrors.d.ts +0 -11
- package/dist/core/SessionErrors.d.ts.map +1 -1
- package/dist/core/SessionErrors.js +1 -14
- package/dist/core/SessionErrors.js.map +1 -1
- package/dist/core/SessionLock.d.ts +4 -5
- package/dist/core/SessionLock.d.ts.map +1 -1
- package/dist/core/SessionLock.js +5 -10
- package/dist/core/SessionLock.js.map +1 -1
- package/dist/core/SessionManager.d.ts +0 -2
- package/dist/core/SessionManager.d.ts.map +1 -1
- package/dist/core/SessionManager.js +3 -5
- package/dist/core/SessionManager.js.map +1 -1
- package/dist/core/SessionResetCoordinator.d.ts +10 -7
- package/dist/core/SessionResetCoordinator.d.ts.map +1 -1
- package/dist/core/SessionResetCoordinator.js +10 -28
- package/dist/core/SessionResetCoordinator.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts +5 -5
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js +4 -40
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts +10 -3
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js +34 -38
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/VerificationOutcomeAdmission.d.ts.map +1 -1
- package/dist/core/VerificationOutcomeAdmission.js +5 -7
- package/dist/core/VerificationOutcomeAdmission.js.map +1 -1
- package/dist/core/evaluator/Calibrator.d.ts +1 -1
- package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
- package/dist/core/evaluator/Calibrator.js +2 -5
- package/dist/core/evaluator/Calibrator.js.map +1 -1
- package/dist/core/evaluator/internals.d.ts +0 -4
- package/dist/core/evaluator/internals.d.ts.map +1 -1
- package/dist/core/evaluator/internals.js +1 -3
- package/dist/core/evaluator/internals.js.map +1 -1
- package/dist/core/graph/Edge.d.ts +1 -1
- package/dist/core/graph/EdgeEmitter.d.ts +2 -4
- package/dist/core/graph/EdgeEmitter.d.ts.map +1 -1
- package/dist/core/graph/EdgeEmitter.js +2 -4
- package/dist/core/graph/EdgeEmitter.js.map +1 -1
- package/dist/core/reasoning/OutcomeRecorder.d.ts +0 -1
- package/dist/core/reasoning/OutcomeRecorder.d.ts.map +1 -1
- package/dist/core/reasoning/OutcomeRecorder.js.map +1 -1
- package/dist/core/reasoning/strategies/SequentialStrategy.d.ts +3 -3
- package/dist/core/reasoning/strategies/SequentialStrategy.js.map +1 -1
- package/dist/core/thought.d.ts +2 -1
- package/dist/core/thought.d.ts.map +1 -1
- package/dist/errors.d.ts +4 -20
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -28
- package/dist/errors.js.map +1 -1
- package/dist/lib.d.ts +13 -20
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +4 -7
- package/dist/lib.js.map +1 -1
- package/dist/logger/NullLogger.d.ts +9 -11
- package/dist/logger/NullLogger.d.ts.map +1 -1
- package/dist/logger/NullLogger.js.map +1 -1
- package/dist/persistence/FilePersistence.d.ts +3 -12
- package/dist/persistence/FilePersistence.d.ts.map +1 -1
- package/dist/persistence/FilePersistence.js +9 -61
- package/dist/persistence/FilePersistence.js.map +1 -1
- package/dist/persistence/FileSnapshotV2.d.ts +2 -2
- package/dist/persistence/FileSnapshotV2.js +2 -2
- package/dist/persistence/FileSnapshotV2.js.map +1 -1
- package/dist/persistence/FileWriter.d.ts +1 -0
- package/dist/persistence/FileWriter.d.ts.map +1 -1
- package/dist/persistence/FileWriter.js +3 -3
- package/dist/persistence/FileWriter.js.map +1 -1
- package/dist/persistence/MemoryPersistence.d.ts +5 -15
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
- package/dist/persistence/MemoryPersistence.js +6 -40
- package/dist/persistence/MemoryPersistence.js.map +1 -1
- package/dist/persistence/PersistenceCodec.js +1 -3
- package/dist/persistence/PersistenceCodec.js.map +1 -1
- package/dist/persistence/PersistenceErrors.d.ts +0 -6
- package/dist/persistence/PersistenceErrors.d.ts.map +1 -1
- package/dist/persistence/PersistenceErrors.js +1 -9
- package/dist/persistence/PersistenceErrors.js.map +1 -1
- package/dist/persistence/PersistenceScope.d.ts.map +1 -1
- package/dist/persistence/PersistenceScope.js +2 -2
- package/dist/persistence/PersistenceScope.js.map +1 -1
- package/dist/persistence/SqlitePersistence.d.ts +3 -10
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
- package/dist/persistence/SqlitePersistence.js +2 -26
- package/dist/persistence/SqlitePersistence.js.map +1 -1
- package/dist/persistence/SqliteSchemaV2.d.ts.map +1 -1
- package/dist/persistence/SqliteSchemaV2.js +3 -12
- package/dist/persistence/SqliteSchemaV2.js.map +1 -1
- package/dist/pool/ConnectionPool.d.ts +3 -12
- package/dist/pool/ConnectionPool.d.ts.map +1 -1
- package/dist/pool/ConnectionPool.js +5 -8
- package/dist/pool/ConnectionPool.js.map +1 -1
- package/dist/pool/IConnectionPool.d.ts +3 -9
- package/dist/pool/IConnectionPool.d.ts.map +1 -1
- package/dist/registry/SkillRegistry.d.ts +1 -7
- package/dist/registry/SkillRegistry.d.ts.map +1 -1
- package/dist/registry/SkillRegistry.js +0 -15
- package/dist/registry/SkillRegistry.js.map +1 -1
- package/dist/registry/ToolRegistry.d.ts +1 -9
- package/dist/registry/ToolRegistry.d.ts.map +1 -1
- package/dist/registry/ToolRegistry.js +0 -21
- package/dist/registry/ToolRegistry.js.map +1 -1
- package/dist/schema.d.ts +2 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +3 -3
- package/dist/schema.js.map +1 -1
- package/dist/transport/BaseTransport.d.ts +0 -9
- package/dist/transport/BaseTransport.d.ts.map +1 -1
- package/dist/transport/BaseTransport.js +0 -11
- package/dist/transport/BaseTransport.js.map +1 -1
- package/dist/watchers/SkillWatcher.d.ts.map +1 -1
- package/dist/watchers/SkillWatcher.js +1 -1
- package/dist/watchers/SkillWatcher.js.map +1 -1
- package/package.json +1 -1
- package/dist/contracts/PersistenceBackend.js.map +0 -1
- package/dist/persistence/FileLegacyImport.d.ts +0 -2
- package/dist/persistence/FileLegacyImport.d.ts.map +0 -1
- package/dist/persistence/FileLegacyImport.js +0 -183
- package/dist/persistence/FileLegacyImport.js.map +0 -1
- package/dist/persistence/SessionScopedPersistence.d.ts +0 -4
- package/dist/persistence/SessionScopedPersistence.d.ts.map +0 -1
- package/dist/persistence/SessionScopedPersistence.js +0 -9
- package/dist/persistence/SessionScopedPersistence.js.map +0 -1
- package/dist/persistence/SqliteLegacyImport.d.ts +0 -14
- package/dist/persistence/SqliteLegacyImport.d.ts.map +0 -1
- package/dist/persistence/SqliteLegacyImport.js +0 -136
- package/dist/persistence/SqliteLegacyImport.js.map +0 -1
- package/dist/persistence/SqliteLegacySchema.d.ts +0 -15
- package/dist/persistence/SqliteLegacySchema.d.ts.map +0 -1
- package/dist/persistence/SqliteLegacySchema.js +0 -72
- package/dist/persistence/SqliteLegacySchema.js.map +0 -1
|
@@ -66,21 +66,6 @@ class SkillRegistry extends BaseRegistry {
|
|
|
66
66
|
allowed_tools: parsed.allowed_tools
|
|
67
67
|
};
|
|
68
68
|
}
|
|
69
|
-
addSkill(skill) {
|
|
70
|
-
this.add(skill);
|
|
71
|
-
}
|
|
72
|
-
updateSkill(name, updates) {
|
|
73
|
-
this.update(name, updates);
|
|
74
|
-
}
|
|
75
|
-
hasSkill(name) {
|
|
76
|
-
return this.has(name);
|
|
77
|
-
}
|
|
78
|
-
getSkill(name) {
|
|
79
|
-
return this.get(name);
|
|
80
|
-
}
|
|
81
|
-
setSkills(skills) {
|
|
82
|
-
this.setAll(skills);
|
|
83
|
-
}
|
|
84
69
|
}
|
|
85
70
|
export { SkillRegistry };
|
|
86
71
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry/SkillRegistry.js","sources":["../../src/registry/SkillRegistry.ts"],"sourcesContent":["/**\n * Skill registry for managing and discovering Claude Code skills.\n *\n * This module provides the `SkillRegistry` class which manages skill registration,\n * discovery from filesystem directories, and CRUD operations. Skills are higher-level\n * workflows that coordinate multiple tools and operations.\n *\n * @module registry\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { DiscoveryCache } from '../cache/DiscoveryCache.js';\nimport { DuplicateSkillError, InvalidSkillError, SkillNotFoundError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { Skill } from '../types/skill.js';\nimport { BaseRegistry } from './BaseRegistry.js';\n\n/**\n * Configuration options for creating a `SkillRegistry` instance.\n *\n * @example\n * ```typescript\n * const options: SkillRegistryOptions = {\n * logger: new StructuredLogger({ context: 'SkillRegistry' }),\n * cache: new DiscoveryCache({ ttl: 300000, maxSize: 100 }),\n * skillDirs: ['./custom-skills', '~/.claude/skills'],\n * lazyDiscovery: true\n * };\n * ```\n */\nexport interface SkillRegistryOptions {\n\t/** Optional logger for diagnostics. */\n\tlogger?: Logger;\n\n\t/** Optional cache for skill lookups. */\n\tcache?: DiscoveryCache<Skill>;\n\n\t/**\n\t * Directory paths to search for skills.\n\t * @default ['.claude/skills', '~/.claude/skills', '.agents/skills', '~/.agents/skills']\n\t */\n\tskillDirs?: string[];\n\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup).\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n}\n\n/**\n * Registry for managing Claude Code skill operations.\n *\n * Extends `BaseRegistry<Skill>` with skill-specific frontmatter parsing
|
|
1
|
+
{"version":3,"file":"registry/SkillRegistry.js","sources":["../../src/registry/SkillRegistry.ts"],"sourcesContent":["/**\n * Skill registry for managing and discovering Claude Code skills.\n *\n * This module provides the `SkillRegistry` class which manages skill registration,\n * discovery from filesystem directories, and CRUD operations. Skills are higher-level\n * workflows that coordinate multiple tools and operations.\n *\n * @module registry\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { DiscoveryCache } from '../cache/DiscoveryCache.js';\nimport { DuplicateSkillError, InvalidSkillError, SkillNotFoundError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { Skill } from '../types/skill.js';\nimport { BaseRegistry } from './BaseRegistry.js';\n\n/**\n * Configuration options for creating a `SkillRegistry` instance.\n *\n * @example\n * ```typescript\n * const options: SkillRegistryOptions = {\n * logger: new StructuredLogger({ context: 'SkillRegistry' }),\n * cache: new DiscoveryCache({ ttl: 300000, maxSize: 100 }),\n * skillDirs: ['./custom-skills', '~/.claude/skills'],\n * lazyDiscovery: true\n * };\n * ```\n */\nexport interface SkillRegistryOptions {\n\t/** Optional logger for diagnostics. */\n\tlogger?: Logger;\n\n\t/** Optional cache for skill lookups. */\n\tcache?: DiscoveryCache<Skill>;\n\n\t/**\n\t * Directory paths to search for skills.\n\t * @default ['.claude/skills', '~/.claude/skills', '.agents/skills', '~/.agents/skills']\n\t */\n\tskillDirs?: string[];\n\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup).\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n}\n\n/**\n * Registry for managing Claude Code skill operations.\n *\n * Extends `BaseRegistry<Skill>` with skill-specific frontmatter parsing.\n */\nexport class SkillRegistry extends BaseRegistry<Skill> {\n\tprotected override readonly _fileExtensions = ['.md', '.yml', '.yaml'];\n\tprotected override readonly _entityName = 'skill';\n\n\tconstructor(options: SkillRegistryOptions = {}) {\n\t\tsuper({\n\t\t\tlogger: options.logger,\n\t\t\tcache: options.cache,\n\t\t\tsearchDirs: options.skillDirs ?? [\n\t\t\t\t'.claude/skills',\n\t\t\t\tjoin(homedir(), '.claude/skills'),\n\t\t\t\t'.agents/skills',\n\t\t\t\tjoin(homedir(), '.agents/skills'),\n\t\t\t],\n\t\t\tlazyDiscovery: options.lazyDiscovery,\n\t\t});\n\t}\n\n\t// --- Error factories ---\n\n\tprotected override _createInvalidError(reason: string): Error {\n\t\treturn new InvalidSkillError(reason);\n\t}\n\n\tprotected override _createDuplicateError(name: string): Error {\n\t\treturn new DuplicateSkillError(name);\n\t}\n\n\tprotected override _createNotFoundError(name: string, action: string): Error {\n\t\treturn new SkillNotFoundError(name, action);\n\t}\n\n\t// --- Discovery ---\n\n\tprotected override _shouldSkipFile(fileName: string): boolean {\n\t\treturn fileName === '.DS_Store';\n\t}\n\n\tprotected override _parseFrontmatter(content: string): Partial<Skill> & { _error?: string } {\n\t\tconst frontmatter = this._extractFrontmatter(content);\n\t\tif (!frontmatter) {\n\t\t\treturn {};\n\t\t}\n\n\t\ttry {\n\t\t\tconst result: Partial<Skill> = {\n\t\t\t\tname: typeof frontmatter.name === 'string' ? frontmatter.name : undefined,\n\t\t\t\tdescription: typeof frontmatter.description === 'string' ? frontmatter.description : '',\n\t\t\t\tuser_invocable: frontmatter['user-invocable'] === true,\n\t\t\t\tallowed_tools: Array.isArray(frontmatter['allowed-tools'])\n\t\t\t\t\t? frontmatter['allowed-tools'].map(String)\n\t\t\t\t\t: undefined,\n\t\t\t};\n\n\t\t\tif (!result.name) {\n\t\t\t\treturn { _error: 'Missing required field: name' };\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tthis.log('Error parsing YAML frontmatter:', {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t\treturn { _error: 'YAML parse error' };\n\t\t}\n\t}\n\n\tprotected override _buildItem(parsed: Partial<Skill>): Skill | null {\n\t\tif (!parsed.name) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tname: parsed.name,\n\t\t\tdescription: parsed.description || '',\n\t\t\tuser_invocable: parsed.user_invocable ?? false,\n\t\t\tallowed_tools: parsed.allowed_tools,\n\t\t};\n\t}\n}\n"],"names":["SkillRegistry","BaseRegistry","options","join","homedir","reason","InvalidSkillError","name","DuplicateSkillError","action","SkillNotFoundError","fileName","content","frontmatter","result","undefined","Array","String","error","Error","parsed"],"mappings":";;;;AAwDO,M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AM,OAAO,GAAGD,OAAOC;YACxD;YACA,OAAO;gBAAE,QAAQ;YAAmB;QACrC;IACD;IAEmB,WAAWE,MAAsB,EAAgB;QACnE,IAAI,CAACA,OAAO,IAAI,EACf,OAAO;QAER,OAAO;YACN,MAAMA,OAAO,IAAI;YACjB,aAAaA,OAAO,WAAW,IAAI;YACnC,gBAAgBA,OAAO,cAAc,IAAI;YACzC,eAAeA,OAAO,aAAa;QACpC;IACD;AACD"}
|
|
@@ -43,8 +43,7 @@ export interface ToolRegistryOptions {
|
|
|
43
43
|
/**
|
|
44
44
|
* Registry for managing MCP tool operations.
|
|
45
45
|
*
|
|
46
|
-
* Extends `BaseRegistry<Tool>` with tool-specific frontmatter parsing
|
|
47
|
-
* and backward-compatible aliases (`addTool`, `removeTool`, etc.).
|
|
46
|
+
* Extends `BaseRegistry<Tool>` with tool-specific frontmatter parsing.
|
|
48
47
|
*/
|
|
49
48
|
export declare class ToolRegistry extends BaseRegistry<Tool> {
|
|
50
49
|
protected readonly _fileExtensions: string[];
|
|
@@ -59,12 +58,5 @@ export declare class ToolRegistry extends BaseRegistry<Tool> {
|
|
|
59
58
|
};
|
|
60
59
|
protected _buildItem(parsed: Partial<Tool>): Tool | null;
|
|
61
60
|
get(name: string): Tool | undefined;
|
|
62
|
-
addTool(tool: Tool): void;
|
|
63
|
-
removeTool(name: string): void;
|
|
64
|
-
updateTool(name: string, updates: Partial<Tool>): void;
|
|
65
|
-
hasTool(name: string): boolean;
|
|
66
|
-
getTool(name: string): Tool | undefined;
|
|
67
|
-
list(): string[];
|
|
68
|
-
setTools(tools: Tool[]): void;
|
|
69
61
|
}
|
|
70
62
|
//# sourceMappingURL=ToolRegistry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolRegistry.d.ts","sourceRoot":"","sources":["../../src/registry/ToolRegistry.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4B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BAAwB;cAW1B,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,KAAK;cAI1C,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK;cAI1C,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK;cAMzD,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;cAI3C,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE;cA0BvE,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,IAAI;IAajD,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;CASnD"}
|
|
@@ -69,27 +69,6 @@ class ToolRegistry extends BaseRegistry {
|
|
|
69
69
|
}
|
|
70
70
|
return this._items.get(name);
|
|
71
71
|
}
|
|
72
|
-
addTool(tool) {
|
|
73
|
-
this.add(tool);
|
|
74
|
-
}
|
|
75
|
-
removeTool(name) {
|
|
76
|
-
this.remove(name);
|
|
77
|
-
}
|
|
78
|
-
updateTool(name, updates) {
|
|
79
|
-
this.update(name, updates);
|
|
80
|
-
}
|
|
81
|
-
hasTool(name) {
|
|
82
|
-
return this.has(name);
|
|
83
|
-
}
|
|
84
|
-
getTool(name) {
|
|
85
|
-
return this.get(name);
|
|
86
|
-
}
|
|
87
|
-
list() {
|
|
88
|
-
return this.getNames();
|
|
89
|
-
}
|
|
90
|
-
setTools(tools) {
|
|
91
|
-
this.setAll(tools);
|
|
92
|
-
}
|
|
93
72
|
}
|
|
94
73
|
export { ToolRegistry };
|
|
95
74
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry/ToolRegistry.js","sources":["../../src/registry/ToolRegistry.ts"],"sourcesContent":["/**\n * Tool registry for managing MCP tool CRUD operations.\n *\n * This module provides the `ToolRegistry` class which manages the registration,\n * retrieval, update, and removal of MCP tools. It supports optional caching\n * for improved performance, filesystem discovery, and integrates with the logging system.\n *\n * @module registry\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { DiscoveryCache } from '../cache/DiscoveryCache.js';\nimport { DuplicateToolError, InvalidToolError, ToolNotFoundError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { Tool } from '../types/tool.js';\nimport { BaseRegistry } from './BaseRegistry.js';\n\n/**\n * Configuration options for creating a `ToolRegistry` instance.\n *\n * @example\n * ```typescript\n * const options: ToolRegistryOptions = {\n * logger: new StructuredLogger({ context: 'ToolRegistry' }),\n * cache: new DiscoveryCache({ ttl: 300000, maxSize: 100 }),\n * toolDirs: ['./custom-tools', '~/.claude/tools'],\n * lazyDiscovery: true\n * };\n * ```\n */\nexport interface ToolRegistryOptions {\n\t/** Optional logger for diagnostics. */\n\tlogger?: Logger;\n\n\t/** Optional cache for tool lookups. */\n\tcache?: DiscoveryCache<Tool>;\n\n\t/**\n\t * Directory paths to search for tools.\n\t * @default ['.claude/tools', '~/.claude/tools']\n\t */\n\ttoolDirs?: string[];\n\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup).\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n}\n\n/**\n * Registry for managing MCP tool operations.\n *\n * Extends `BaseRegistry<Tool>` with tool-specific frontmatter parsing
|
|
1
|
+
{"version":3,"file":"registry/ToolRegistry.js","sources":["../../src/registry/ToolRegistry.ts"],"sourcesContent":["/**\n * Tool registry for managing MCP tool CRUD operations.\n *\n * This module provides the `ToolRegistry` class which manages the registration,\n * retrieval, update, and removal of MCP tools. It supports optional caching\n * for improved performance, filesystem discovery, and integrates with the logging system.\n *\n * @module registry\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { DiscoveryCache } from '../cache/DiscoveryCache.js';\nimport { DuplicateToolError, InvalidToolError, ToolNotFoundError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { Tool } from '../types/tool.js';\nimport { BaseRegistry } from './BaseRegistry.js';\n\n/**\n * Configuration options for creating a `ToolRegistry` instance.\n *\n * @example\n * ```typescript\n * const options: ToolRegistryOptions = {\n * logger: new StructuredLogger({ context: 'ToolRegistry' }),\n * cache: new DiscoveryCache({ ttl: 300000, maxSize: 100 }),\n * toolDirs: ['./custom-tools', '~/.claude/tools'],\n * lazyDiscovery: true\n * };\n * ```\n */\nexport interface ToolRegistryOptions {\n\t/** Optional logger for diagnostics. */\n\tlogger?: Logger;\n\n\t/** Optional cache for tool lookups. */\n\tcache?: DiscoveryCache<Tool>;\n\n\t/**\n\t * Directory paths to search for tools.\n\t * @default ['.claude/tools', '~/.claude/tools']\n\t */\n\ttoolDirs?: string[];\n\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup).\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n}\n\n/**\n * Registry for managing MCP tool operations.\n *\n * Extends `BaseRegistry<Tool>` with tool-specific frontmatter parsing.\n */\nexport class ToolRegistry extends BaseRegistry<Tool> {\n\tprotected override readonly _fileExtensions = ['.tool.md'];\n\tprotected override readonly _entityName = 'tool';\n\n\tconstructor(options: ToolRegistryOptions = {}) {\n\t\tsuper({\n\t\t\tlogger: options.logger,\n\t\t\tcache: options.cache,\n\t\t\tsearchDirs: options.toolDirs ?? ['.claude/tools', join(homedir(), '.claude/tools')],\n\t\t\tlazyDiscovery: options.lazyDiscovery,\n\t\t});\n\t}\n\n\t// --- Error factories ---\n\n\tprotected override _createInvalidError(reason: string): Error {\n\t\treturn new InvalidToolError(reason);\n\t}\n\n\tprotected override _createDuplicateError(name: string): Error {\n\t\treturn new DuplicateToolError(name);\n\t}\n\n\tprotected override _createNotFoundError(name: string, action: string): Error {\n\t\treturn new ToolNotFoundError(name, action);\n\t}\n\n\t// --- Discovery ---\n\n\tprotected override _shouldSkipFile(_fileName: string): boolean {\n\t\treturn false;\n\t}\n\n\tprotected override _parseFrontmatter(content: string): Partial<Tool> & { _error?: string } {\n\t\tconst frontmatter = this._extractFrontmatter(content);\n\t\tif (!frontmatter) {\n\t\t\treturn { _error: 'No YAML frontmatter found' };\n\t\t}\n\n\t\ttry {\n\t\t\tconst result: Partial<Tool> = {\n\t\t\t\tname: typeof frontmatter.name === 'string' ? frontmatter.name : undefined,\n\t\t\t\tdescription: typeof frontmatter.description === 'string' ? frontmatter.description : '',\n\t\t\t\tinputSchema: frontmatter.inputSchema as Tool['inputSchema'],\n\t\t\t};\n\n\t\t\tif (!result.name) {\n\t\t\t\treturn { _error: 'Missing required field: name' };\n\t\t\t}\n\t\t\tif (!result.inputSchema) {\n\t\t\t\treturn { _error: 'Missing required field: inputSchema' };\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch {\n\t\t\treturn { _error: 'YAML parse error' };\n\t\t}\n\t}\n\n\tprotected override _buildItem(parsed: Partial<Tool>): Tool | null {\n\t\tif (!parsed.name || !parsed.inputSchema) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tname: parsed.name,\n\t\t\tdescription: parsed.description || '',\n\t\t\tinputSchema: parsed.inputSchema,\n\t\t};\n\t}\n\n\t// --- Tool-specific get with cache lookup ---\n\n\tpublic override get(name: string): Tool | undefined {\n\t\tif (this._cache) {\n\t\t\tconst cached = this._cache.get(`tool:${name}`);\n\t\t\tif (cached && cached.length > 0) {\n\t\t\t\treturn cached[0];\n\t\t\t}\n\t\t}\n\t\treturn this._items.get(name);\n\t}\n}\n"],"names":["ToolRegistry","BaseRegistry","options","join","homedir","reason","InvalidToolError","name","DuplicateToolError","action","ToolNotFoundError","_fileName","content","frontmatter","result","undefined","parsed","cached"],"mappings":";;;;AAwDO,MAAMA,qBAAqBC;IACL,kBAAkB;QAAC;KAAW,CAAC;IAC/B,cAAc,OAAO;IAEjD,YAAYC,UAA+B,CAAC,CAAC,CAAE;QAC9C,KAAK,CAAC;YACL,QAAQA,QAAQ,MAAM;YACtB,OAAOA,QAAQ,KAAK;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AAC,KAAK,EAAEV,MAAM;YAC7C,IAAIU,UAAUA,OAAO,MAAM,GAAG,GAC7B,OAAOA,MAAM,CAAC,EAAE;QAElB;QACA,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAACV;IACxB;AACD"}
|
package/dist/schema.d.ts
CHANGED
|
@@ -315,6 +315,7 @@ export declare const PartialStepRecommendationSchema: v.ObjectSchema<{
|
|
|
315
315
|
* thought: 'I need to analyze the problem',
|
|
316
316
|
* thought_number: 1,
|
|
317
317
|
* total_thoughts: 5,
|
|
318
|
+
* session_id: 'analysis-task',
|
|
318
319
|
* next_thought_needed: true,
|
|
319
320
|
* available_mcp_tools: ['Read', 'Write', 'Grep']
|
|
320
321
|
* });
|
|
@@ -479,7 +480,7 @@ export declare const SequentialThinkingSchema: v.ObjectSchema<{
|
|
|
479
480
|
readonly merge_branch_ids: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>, v.MaxLengthAction<string, 50, undefined>]>, undefined>, v.DescriptionAction<string[], "Branch IDs being merged into current context">]>, undefined>;
|
|
480
481
|
readonly meta_observation: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Metacognitive observation about reasoning process">]>, undefined>;
|
|
481
482
|
readonly reasoning_depth: v.OptionalSchema<v.SchemaWithPipe<readonly [v.PicklistSchema<["shallow", "moderate", "deep"], undefined>, v.DescriptionAction<"shallow" | "moderate" | "deep", "Effort signal: how deep reasoning should go">]>, undefined>;
|
|
482
|
-
readonly session_id: v.
|
|
483
|
+
readonly session_id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "Session ID must contain only letters, numbers, hyphens, and underscores">, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 100, undefined>, v.NotValueAction<string, "__global__", "Session ID '__global__' is retired; use an explicit named session">, v.DescriptionAction<string, "Required session identifier for state isolation. Thought history, branches, and statistics are scoped to this explicit named session.">]>;
|
|
483
484
|
readonly reset_state: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.">]>, undefined>;
|
|
484
485
|
readonly tool_name: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.DescriptionAction<string, "Name of the tool being invoked (for tool_call thoughts)">]>, undefined>;
|
|
485
486
|
readonly tool_arguments: v.OptionalSchema<v.SchemaWithPipe<readonly [v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>, v.DescriptionAction<{
|
package/dist/schema.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAC7B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAoH5C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;aAqBnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,yBAAyB;;;;;;;;
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAC7B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAoH5C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;aAqBnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,yBAAyB;;;;;;;;aAgCpC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAanC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,eAAO,MAAM,+BAA+B;;;;;;;;;aA6B1C,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAe1C,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aA0OnC,CAAC;AAEH,6FAA6F;AAC7F,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAE1E;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,wBAAwB,EAAE,IAItC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,oBAAoB;;;;;;;aAmB/B,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,cAAc,kWASW,CAAC;AAEvC;;GAEG;AACH,eAAO,MAAM,UAAU;;;;;;;;aAetB,CAAC"}
|
package/dist/schema.js
CHANGED
|
@@ -73,8 +73,8 @@ Reasoning Enhancement Parameters:
|
|
|
73
73
|
- merge_branch_ids: Branch IDs merged into current context
|
|
74
74
|
- meta_observation: Observation about reasoning process (with thought_type 'meta')
|
|
75
75
|
- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)
|
|
76
|
-
- session_id:
|
|
77
|
-
- reset_state: (Optional) When true, clears all state for the
|
|
76
|
+
- session_id: Required unique identifier that scopes thought history, branches, and statistics to an explicit session. Format: alphanumeric, hyphens, underscores, 1-100 chars; the retired value __global__ is rejected.
|
|
77
|
+
- reset_state: (Optional) When true, clears all state for the required session_id before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.
|
|
78
78
|
|
|
79
79
|
Response Enrichment:
|
|
80
80
|
- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)
|
|
@@ -201,7 +201,7 @@ const SequentialThinkingSchema = __rspack_external_valibot.object({
|
|
|
201
201
|
'moderate',
|
|
202
202
|
'deep'
|
|
203
203
|
]), __rspack_external_valibot.description('Effort signal: how deep reasoning should go'))),
|
|
204
|
-
session_id: __rspack_external_valibot.
|
|
204
|
+
session_id: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.regex(/^[a-zA-Z0-9_-]+$/, 'Session ID must contain only letters, numbers, hyphens, and underscores'), __rspack_external_valibot.minLength(1), __rspack_external_valibot.maxLength(100), __rspack_external_valibot.notValue('__global__', "Session ID '__global__' is retired; use an explicit named session"), __rspack_external_valibot.description('Required session identifier for state isolation. Thought history, branches, and statistics are scoped to this explicit named session.')),
|
|
205
205
|
reset_state: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'))),
|
|
206
206
|
tool_name: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.minLength(1), __rspack_external_valibot.description('Name of the tool being invoked (for tool_call thoughts)'))),
|
|
207
207
|
tool_arguments: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.record(__rspack_external_valibot.string(), __rspack_external_valibot.unknown()), __rspack_external_valibot.description('Arguments passed to the tool (for tool_call thoughts)'))),
|
package/dist/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\nimport type { Edge, EdgeKind } from './core/graph/Edge.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nEach invocation records exactly one authored thought and returns. When strategy_hint.action is continue, invoke this tool again with the next thought; do not stop or provide a final answer. terminate permits stopping. The server does not author later thoughts or call itself.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end. Omission defaults to true; the effective next action is in strategy_hint.\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call' (requires toolInterleave flag), 'tool_observation' (requires toolInterleave flag), 'assumption' (requires newThoughtTypes flag), 'decomposition' (requires newThoughtTypes flag), 'backtrack' (requires newThoughtTypes flag; logically retracts the thought referenced by backtrack_target - the target remains in history but is excluded from quality calculations)\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.\n- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). Weights: type_diversity=0.3, verification_coverage=0.3, depth_efficiency=0.2, confidence_stability=0.2 (weighted geometric mean). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5, null when fewer than 2 confidence values)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Hints are prioritized: confidence_drift > unverified_hypothesis > no_alternatives_explored > consecutive_without_verification, so the most actionable patterns fill the cap first. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts after it), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (5+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this skill is recommended (default: empty string)'))\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended (default: empty string)'))\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(30),\n\t\t\tv.description('Unique identifier for this thought. Auto-generated if not provided.')\n\t\t)\n\t),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'Omission defaults to true; the effective next action is returned in strategy_hint.'\n\t\t\t)\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['regular', 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call', 'tool_observation', 'assumption', 'decomposition', 'backtrack']),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular (default), hypothesis, verification, critique, synthesis, meta, tool_call (requires toolInterleave), tool_observation (requires toolInterleave), assumption (requires newThoughtTypes), decomposition (requires newThoughtTypes), backtrack (requires newThoughtTypes)'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1),\n\t\t\tv.description('Thought number being verified or critiqued')\n\t\t)\n\t),\n\tverification_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.literal(0), v.literal(1)]),\n\t\t\tv.description('Exact verification outcome label: 0 for incorrect, 1 for correct')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(100),\n\t\t\tv.description(\n\t\t\t\t'Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'\n\t\t\t)\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n\ttool_name: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Name of the tool being invoked (for tool_call thoughts)'))),\n\ttool_arguments: v.optional(v.pipe(v.record(v.string(), v.unknown()), v.description('Arguments passed to the tool (for tool_call thoughts)'))),\n\ttool_result: v.optional(v.pipe(v.unknown(), v.description('Result returned by the tool (for tool_observation thoughts)'))),\n\tcontinuation_token: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Token for resuming long-running tool invocations'))),\n\tdecomposition_children: v.optional(v.pipe(v.array(v.string()), v.description('Child thought IDs produced by decomposition'))),\n\tbacktrack_target: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.description('Thought number to backtrack to. When the parent thought has thought_type=backtrack, this thought is logically retracted: it remains in history but is excluded from quality signals and reasoning stats.'))),\n\tregister_branch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'register_branch_id must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description(\n\t\t\t\t'Pre-declares a branch ID for this session before any thoughts reference it. Useful so that subsequent thoughts using merge_branch_ids can target a branch that has not yet received any thoughts.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/** Inferred output type of the sequential thinking schema (string IDs, no branded types). */\nexport type SchemaOutput = v.InferOutput<typeof SequentialThinkingSchema>;\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.array(v.unknown()), v.record(v.string(), v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n\n/**\n * Schema for {@link EdgeKind} — the semantic relationship between two thoughts.\n */\nexport const EdgeKindSchema = v.union([\n\tv.literal('sequence'),\n\tv.literal('branch'),\n\tv.literal('merge'),\n\tv.literal('verifies'),\n\tv.literal('critiques'),\n\tv.literal('derives_from'),\n\tv.literal('tool_invocation'),\n\tv.literal('revises'),\n]) satisfies v.GenericSchema<EdgeKind>;\n\n/**\n * Schema for {@link Edge} — a directed edge in the thought DAG.\n */\nexport const EdgeSchema = v.object({\n\tid: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tfrom: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tto: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tkind: EdgeKindSchema,\n\tsessionId: v.pipe(v.string(), v.minLength(1)),\n\tcreatedAt: v.number(),\n\tmetadata: v.optional(v.record(v.string(), v.unknown())),\n}) satisfies v.GenericSchema<Omit<Edge, 'id' | 'from' | 'to' | 'sessionId'> & { id: string; from: string; to: string; sessionId: string }>;\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationSchema","PartialStepRecommendationSchema","SequentialThinkingSchema","SEQUENTIAL_THINKING_TOOL","JsonRpcRequestSchema","EdgeKindSchema","EdgeSchema"],"mappings":";AAyCA,MAAMA,mBAAmB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yHA0G+F,CAAC;AA0BnH,MAAMC,2BAA2BC,0BAAAA,MAAQ,CAAC;IAChD,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAI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Q,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,OAAS;AACpD"}
|
|
1
|
+
{"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\nimport type { Edge, EdgeKind } from './core/graph/Edge.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nEach invocation records exactly one authored thought and returns. When strategy_hint.action is continue, invoke this tool again with the next thought; do not stop or provide a final answer. terminate permits stopping. The server does not author later thoughts or call itself.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end. Omission defaults to true; the effective next action is in strategy_hint.\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call' (requires toolInterleave flag), 'tool_observation' (requires toolInterleave flag), 'assumption' (requires newThoughtTypes flag), 'decomposition' (requires newThoughtTypes flag), 'backtrack' (requires newThoughtTypes flag; logically retracts the thought referenced by backtrack_target - the target remains in history but is excluded from quality calculations)\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: Required unique identifier that scopes thought history, branches, and statistics to an explicit session. Format: alphanumeric, hyphens, underscores, 1-100 chars; the retired value __global__ is rejected.\n- reset_state: (Optional) When true, clears all state for the required session_id before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). Weights: type_diversity=0.3, verification_coverage=0.3, depth_efficiency=0.2, confidence_stability=0.2 (weighted geometric mean). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5, null when fewer than 2 confidence values)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Hints are prioritized: confidence_drift > unverified_hypothesis > no_alternatives_explored > consecutive_without_verification, so the most actionable patterns fill the cap first. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts after it), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (5+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.maxLength(2000),\n\t\t\tv.description('Why this skill is recommended (default: empty string)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.maxLength(2000),\n\t\t\tv.description('Why this tool is recommended (default: empty string)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * session_id: 'analysis-task',\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(30),\n\t\t\tv.description('Unique identifier for this thought. Auto-generated if not provided.')\n\t\t)\n\t),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'Omission defaults to true; the effective next action is returned in strategy_hint.'\n\t\t\t)\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist([\n\t\t\t\t'regular',\n\t\t\t\t'hypothesis',\n\t\t\t\t'verification',\n\t\t\t\t'critique',\n\t\t\t\t'synthesis',\n\t\t\t\t'meta',\n\t\t\t\t'tool_call',\n\t\t\t\t'tool_observation',\n\t\t\t\t'assumption',\n\t\t\t\t'decomposition',\n\t\t\t\t'backtrack',\n\t\t\t]),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular (default), hypothesis, verification, critique, synthesis, meta, tool_call (requires toolInterleave), tool_observation (requires toolInterleave), assumption (requires newThoughtTypes), decomposition (requires newThoughtTypes), backtrack (requires newThoughtTypes)'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Thought number being verified or critiqued'))\n\t),\n\tverification_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.literal(0), v.literal(1)]),\n\t\t\tv.description('Exact verification outcome label: 0 for incorrect, 1 for correct')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.pipe(\n\t\tv.string(),\n\t\tv.regex(\n\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t),\n\t\tv.minLength(1),\n\t\tv.maxLength(100),\n\t\tv.notValue('__global__', \"Session ID '__global__' is retired; use an explicit named session\"),\n\t\tv.description(\n\t\t\t'Required session identifier for state isolation. Thought history, branches, and statistics are scoped to this explicit named session.'\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n\ttool_name: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.description('Name of the tool being invoked (for tool_call thoughts)')\n\t\t)\n\t),\n\ttool_arguments: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.unknown()),\n\t\t\tv.description('Arguments passed to the tool (for tool_call thoughts)')\n\t\t)\n\t),\n\ttool_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.unknown(),\n\t\t\tv.description('Result returned by the tool (for tool_observation thoughts)')\n\t\t)\n\t),\n\tcontinuation_token: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.description('Token for resuming long-running tool invocations')\n\t\t)\n\t),\n\tdecomposition_children: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Child thought IDs produced by decomposition'))\n\t),\n\tbacktrack_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.integer(),\n\t\t\tv.minValue(1),\n\t\t\tv.description(\n\t\t\t\t'Thought number to backtrack to. When the parent thought has thought_type=backtrack, this thought is logically retracted: it remains in history but is excluded from quality signals and reasoning stats.'\n\t\t\t)\n\t\t)\n\t),\n\tregister_branch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'register_branch_id must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description(\n\t\t\t\t'Pre-declares a branch ID for this session before any thoughts reference it. Useful so that subsequent thoughts using merge_branch_ids can target a branch that has not yet received any thoughts.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/** Inferred output type of the sequential thinking schema (string IDs, no branded types). */\nexport type SchemaOutput = v.InferOutput<typeof SequentialThinkingSchema>;\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.array(v.unknown()), v.record(v.string(), v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n\n/**\n * Schema for {@link EdgeKind} — the semantic relationship between two thoughts.\n */\nexport const EdgeKindSchema = v.union([\n\tv.literal('sequence'),\n\tv.literal('branch'),\n\tv.literal('merge'),\n\tv.literal('verifies'),\n\tv.literal('critiques'),\n\tv.literal('derives_from'),\n\tv.literal('tool_invocation'),\n\tv.literal('revises'),\n]) satisfies v.GenericSchema<EdgeKind>;\n\n/**\n * Schema for {@link Edge} — a directed edge in the thought DAG.\n */\nexport const EdgeSchema = v.object({\n\tid: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tfrom: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tto: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tkind: EdgeKindSchema,\n\tsessionId: v.pipe(v.string(), v.minLength(1)),\n\tcreatedAt: v.number(),\n\tmetadata: v.optional(v.record(v.string(), v.unknown())),\n}) satisfies v.GenericSchema<\n\tOmit<Edge, 'id' | 'from' | 'to' | 'sessionId'> & {\n\t\tid: string;\n\t\tfrom: string;\n\t\tto: string;\n\t\tsessionId: string;\n\t}\n>;\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationS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ACnD,MAAMA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACrD,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMQ;IACN,WAAWR,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC;IAC1C,WAAWA,0BAAAA,MAAQ;IACnB,UAAUA,0BAAAA,QAAU,CAACA,0BAAAA,MAAQ,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,OAAS;AACpD"}
|
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
* @remarks
|
|
8
8
|
* **Security Features:**
|
|
9
9
|
* - Session ID validation (alphanumeric, max 64 chars)
|
|
10
|
-
* - Query parameter sanitization (whitelist allowed keys)
|
|
11
10
|
* - Rate limiting per IP (configurable, default 100 req/min)
|
|
12
11
|
* - CORS origin validation
|
|
13
12
|
*
|
|
@@ -17,7 +16,6 @@
|
|
|
17
16
|
* - Can be disabled via `enableRateLimit: false`
|
|
18
17
|
*/
|
|
19
18
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
20
|
-
import type { URL } from 'node:url';
|
|
21
19
|
import type { HealthChecker } from '../health/HealthChecker.js';
|
|
22
20
|
import type { Logger } from '../logger/StructuredLogger.js';
|
|
23
21
|
import type { McpServer } from 'tmcp';
|
|
@@ -62,13 +60,6 @@ export declare abstract class BaseTransport {
|
|
|
62
60
|
* @returns true if valid, false otherwise
|
|
63
61
|
*/
|
|
64
62
|
protected validateSessionId(sessionId: string): boolean;
|
|
65
|
-
/**
|
|
66
|
-
* Sanitize query parameters by removing any not in whitelist.
|
|
67
|
-
*
|
|
68
|
-
* @param url - The URL object containing query parameters
|
|
69
|
-
* @returns A sanitized record of allowed query parameters
|
|
70
|
-
*/
|
|
71
|
-
protected sanitizeQueryParams(url: URL): Record<string, string>;
|
|
72
63
|
/**
|
|
73
64
|
* Check rate limit for a given IP address.
|
|
74
65
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseTransport.d.ts","sourceRoot":"","sources":["../../src/transport/BaseTransport.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"BaseTransport.d.ts","sourceRoot":"","sources":["../../src/transport/BaseTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,MAAM,EAAY,MAAM,+BAA+B,CAAC;AAEtE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AA0BtC,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACjC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IAC9B,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IACnC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,aAAa,CAAC,EAAE,aAAa,CAAC;CACvC;AAED,8BAAsB,aAAa;IAClC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,WAAW,EAAE,MAAM,CAAC;IAC9B,SAAS,CAAC,WAAW,EAAE,OAAO,CAAC;IAC/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;IAmB1B;;;;;;OAMG;IACH,SAAS,CAAC,GAAG,CACZ,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAChC,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,IAAI;IAUP;;;OAGG;IACH,IAAW,cAAc,IAAI,OAAO,CAEnC;IAED;;;;;;;;OAQG;IACH,SAAS,CAAC,oBAAoB,CAAC,GAAG,EAAE,cAAc,EAAE,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAU9F;;;;;;OAMG;cACa,uBAAuB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAc3E;;;;;;;OAOG;IACH,SAAS,CAAC,qBAAqB,CAAC,GAAG,EAAE,cAAc,EAAE,eAAe,EAAE,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,GAAG,IAAI;IAUlG;;OAEG;IACH,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAErD;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAE9C;;OAEG;IACH,QAAQ,KAAK,WAAW,IAAI,MAAM,CAAC;CAEnC"}
|
|
@@ -12,12 +12,6 @@ class NoopLogger {
|
|
|
12
12
|
return this._level;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
const ALLOWED_QUERY_PARAMS = new Set([
|
|
16
|
-
'session',
|
|
17
|
-
'sessionId',
|
|
18
|
-
'client',
|
|
19
|
-
'clientId'
|
|
20
|
-
]);
|
|
21
15
|
const RATE_LIMIT_REQUESTS = 100;
|
|
22
16
|
const RATE_LIMIT_WINDOW_MS = 60000;
|
|
23
17
|
class BaseTransport {
|
|
@@ -56,11 +50,6 @@ class BaseTransport {
|
|
|
56
50
|
if (sessionId.length > MAX_SESSION_ID_LENGTH) return false;
|
|
57
51
|
return SESSION_ID_PATTERN.test(sessionId);
|
|
58
52
|
}
|
|
59
|
-
sanitizeQueryParams(url) {
|
|
60
|
-
const sanitized = {};
|
|
61
|
-
for (const [key, value] of url.searchParams.entries())if (ALLOWED_QUERY_PARAMS.has(key)) sanitized[key] = value;
|
|
62
|
-
return sanitized;
|
|
63
|
-
}
|
|
64
53
|
checkRateLimit(ip) {
|
|
65
54
|
if (!this._rateLimitEnabled) return false;
|
|
66
55
|
const now = Date.now();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport/BaseTransport.js","sources":["../../src/transport/BaseTransport.ts"],"sourcesContent":["/**\n * Base transport implementation.\n *\n * This class provides shared functionality for all transport implementations,\n * including session validation, rate limiting, CORS handling, and IP extraction.\n *\n * @remarks\n * **Security Features:**\n * - Session ID validation (alphanumeric, max 64 chars)\n * - Query parameter sanitization (whitelist allowed keys)\n * - Rate limiting per IP (configurable, default 100 req/min)\n * - CORS origin validation\n *\n * **Rate Limiting:**\n * - Tracks requests per IP address within a time window\n * - Returns 429 Too Many Requests when limit exceeded\n * - Can be disabled via `enableRateLimit: false`\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { URL } from 'node:url';\nimport type { HealthChecker } from '../health/HealthChecker.js';\nimport type { Logger, LogLevel } from '../logger/StructuredLogger.js';\nimport { SESSION_ID_PATTERN, MAX_SESSION_ID_LENGTH } from '../core/ids.js';\nimport type { McpServer } from 'tmcp';\n\n/**\n * No-op logger that does nothing. Used when no logger is provided.\n */\nclass NoopLogger implements Logger {\n\tprivate _level: LogLevel = 'info';\n\n\tinfo(_message: string, _meta?: Record<string, unknown>): void {}\n\twarn(_message: string, _meta?: Record<string, unknown>): void {}\n\terror(_message: string, _meta?: Record<string, unknown>): void {}\n\tdebug(_message: string, _meta?: Record<string, unknown>): void {}\n\tsetLevel(level: LogLevel): void {\n\t\tthis._level = level;\n\t}\n\tgetLevel(): LogLevel {\n\t\treturn this._level;\n\t}\n}\n\n/**\n * Allowed query parameter names (whitelist for security).\n */\nconst ALLOWED_QUERY_PARAMS = new Set(['session', 'sessionId', 'client', 'clientId']);\n\n\n\n/**\n * Rate limit settings (requests per minute per IP).\n */\nconst RATE_LIMIT_REQUESTS = 100;\nconst RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute\n\nexport interface TransportOptions {\n\treadonly port?: number;\n\treadonly host?: string;\n\treadonly allowedHosts?: string[];\n\treadonly corsOrigin?: string;\n\treadonly enableCors?: boolean;\n\treadonly enableRateLimit?: boolean;\n\treadonly maxRequestsPerMinute?: number;\n\treadonly logger?: Logger;\n\treadonly healthChecker?: HealthChecker;\n}\n\nexport abstract class BaseTransport {\n\tprotected _port: number;\n\tprotected _host: string;\n\tprotected _corsOrigin: string;\n\tprotected _enableCors: boolean;\n\tprotected _rateLimitEnabled: boolean;\n\tprotected _maxRequestsPerMinute: number;\n\tprotected _allowedHosts: Set<string>;\n\tprotected _rateLimitMap: Map<string, { count: number; resetTime: number }> = new Map();\n\tprotected _rateLimitCleanupIntervalId: NodeJS.Timeout | null = null;\n\tprotected _wasHostExplicitlySet: boolean;\n\t/** Shutdown state for graceful shutdown. */\n\tprotected _isShuttingDown: boolean = false;\n\tprivate _logger: Logger | NoopLogger;\n\tprotected _healthChecker: HealthChecker | null;\n\n\tconstructor(options: TransportOptions = {}) {\n\t\tthis._port = options.port ?? 9108;\n\t\tthis._host = options.host ?? '127.0.0.1';\n\t\tthis._wasHostExplicitlySet = options.host !== undefined;\n\t\tthis._corsOrigin = options.corsOrigin ?? '*';\n\t\tthis._enableCors = options.enableCors ?? true;\n\t\tthis._rateLimitEnabled = options.enableRateLimit ?? true;\n\t\tthis._maxRequestsPerMinute = options.maxRequestsPerMinute ?? RATE_LIMIT_REQUESTS;\n\t\tthis._allowedHosts = this._buildAllowedHosts(options.allowedHosts);\n\t\tthis._isShuttingDown = false;\n\t\tthis._logger = options.logger ?? new NoopLogger();\n\t\tthis._healthChecker = options.healthChecker ?? null;\n\n\t\tif (this._rateLimitEnabled) {\n\t\t\tthis._startRateLimitCleanup();\n\t\t}\n\t}\n\n\t/**\n\t * Get the server URL with localhost substitution for default host.\n\t */\n\tget serverUrl(): string {\n\t\tconst host =\n\t\t\t!this._wasHostExplicitlySet && this._host === '127.0.0.1' ? 'localhost' : this._host;\n\t\treturn `http://${host}:${this._port}`;\n\t}\n\n\t/**\n\t * Validate session ID format.\n\t *\n\t * @param sessionId - The session ID to validate\n\t * @returns true if valid, false otherwise\n\t */\n\tprotected validateSessionId(sessionId: string): boolean {\n\t\tif (sessionId.length > MAX_SESSION_ID_LENGTH) {\n\t\t\treturn false;\n\t\t}\n\t\treturn SESSION_ID_PATTERN.test(sessionId);\n\t}\n\n\t/**\n\t * Sanitize query parameters by removing any not in whitelist.\n\t *\n\t * @param url - The URL object containing query parameters\n\t * @returns A sanitized record of allowed query parameters\n\t */\n\tprotected sanitizeQueryParams(url: URL): Record<string, string> {\n\t\tconst sanitized: Record<string, string> = {};\n\n\t\tfor (const [key, value] of url.searchParams.entries()) {\n\t\t\tif (ALLOWED_QUERY_PARAMS.has(key)) {\n\t\t\t\tsanitized[key] = value;\n\t\t\t}\n\t\t}\n\n\t\treturn sanitized;\n\t}\n\n\t/**\n\t * Check rate limit for a given IP address.\n\t *\n\t * @param ip - The IP address to check\n\t * @returns true if rate limit exceeded, false otherwise\n\t */\n\tprotected checkRateLimit(ip: string): boolean {\n\t\tif (!this._rateLimitEnabled) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst now = Date.now();\n\t\tthis._cleanupExpiredRateLimitEntries(now);\n\t\tconst record = this._rateLimitMap.get(ip);\n\n\t\tif (!record || now > record.resetTime) {\n\t\t\tthis._rateLimitMap.set(ip, {\n\t\t\t\tcount: 1,\n\t\t\t\tresetTime: now + RATE_LIMIT_WINDOW_MS,\n\t\t\t});\n\t\t\treturn false;\n\t\t}\n\n\t\tif (record.count >= this._maxRequestsPerMinute) {\n\t\t\treturn true; // Rate limit exceeded\n\t\t}\n\n\t\trecord.count++;\n\t\treturn false;\n\t}\n\n\tprotected _cleanupExpiredRateLimitEntries(now = Date.now()): void {\n\t\tfor (const [ip, record] of this._rateLimitMap.entries()) {\n\t\t\tif (record.resetTime <= now) {\n\t\t\t\tthis._rateLimitMap.delete(ip);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected _startRateLimitCleanup(): void {\n\t\tif (this._rateLimitCleanupIntervalId !== null) {\n\t\t\tclearInterval(this._rateLimitCleanupIntervalId);\n\t\t}\n\n\t\tthis._rateLimitCleanupIntervalId = setInterval(() => {\n\t\t\tthis._cleanupExpiredRateLimitEntries();\n\t\t}, RATE_LIMIT_WINDOW_MS);\n\t}\n\n\tprotected _stopRateLimitCleanup(): void {\n\t\tif (this._rateLimitCleanupIntervalId !== null) {\n\t\t\tclearInterval(this._rateLimitCleanupIntervalId);\n\t\t\tthis._rateLimitCleanupIntervalId = null;\n\t\t}\n\t}\n\n\t/**\n\t * Get client IP address from request.\n\t *\n\t * @param req - The incoming request\n\t * @returns The client IP address\n\t */\n\tprotected getClientIp(req: IncomingMessage): string {\n\t\tconst forwardedFor = req.headers['x-forwarded-for'];\n\t\tif (forwardedFor && typeof forwardedFor === 'string') {\n\t\t\treturn forwardedFor.split(',')[0]!.trim();\n\t\t}\n\t\tconst remoteAddress = req.socket.remoteAddress;\n\t\treturn remoteAddress || 'unknown';\n\t}\n\n\t/**\n\t * Validate CORS origin from request headers.\n\t *\n\t * @param req - The incoming request\n\t * @returns true if origin is valid, false otherwise\n\t */\n\tprotected validateCorsOrigin(req: IncomingMessage): boolean {\n\t\tif (this._corsOrigin === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst origin = req.headers.origin;\n\t\tif (!origin) {\n\t\t\treturn true; // No origin header is acceptable\n\t\t}\n\n\t\t// Exact match\n\t\tif (this._corsOrigin === origin) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check if configured origin is a wildcard pattern\n\t\tif (this._corsOrigin.includes('*')) {\n\t\t\t// Escape all regex metacharacters EXCEPT *,\n\t\t\t// then replace * with a hostname-safe pattern (alphanumeric, hyphens, dots)\n\t\t\tconst escaped = this._corsOrigin\n\t\t\t\t.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // escape metacharacters (not *)\n\t\t\t\t.replace(/\\*/g, '[a-zA-Z0-9.-]*'); // * matches valid hostname chars only\n\t\t\tconst regex = new RegExp(`^${escaped}$`);\n\t\t\treturn regex.test(origin);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Set CORS headers on response.\n\t *\n\t * @param res - The server response\n\t */\n\tprotected setCorsHeaders(res: ServerResponse): void {\n\t\tif (this._enableCors) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', this._corsOrigin);\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\t\t}\n\t}\n\n\tprotected validateHostHeader(req: IncomingMessage): boolean {\n\t\tconst rawHost = req.headers.host;\n\t\tif (!rawHost) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst hostWithoutPort = rawHost.split(':')[0]!.trim().toLowerCase();\n\t\tif (!hostWithoutPort) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (this._allowedHosts.size === 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn this._allowedHosts.has(hostWithoutPort);\n\t}\n\n\tprivate _buildAllowedHosts(configuredHosts?: string[]): Set<string> {\n\t\tif (configuredHosts && configuredHosts.length > 0) {\n\t\t\treturn new Set(configuredHosts.map((host) => host.toLowerCase().trim()).filter(Boolean));\n\t\t}\n\n\t\tconst boundHost = this._host.toLowerCase();\n\t\tconst localHosts = ['localhost', '127.0.0.1', '::1'];\n\n\t\tif (localHosts.includes(boundHost)) {\n\t\t\treturn new Set(localHosts);\n\t\t}\n\n\t\tif (boundHost === '0.0.0.0' || boundHost === '::') {\n\t\t\treturn new Set(localHosts);\n\t\t}\n\n\t\treturn new Set([boundHost]);\n\t}\n\n\t/**\n\t * Log a message using the configured logger.\n\t *\n\t * @param level - Log level\n\t * @param message - Message to log\n\t * @param meta - Optional metadata\n\t */\n\tprotected log(\n\t\tlevel: 'info' | 'warn' | 'error',\n\t\tmessage: string,\n\t\tmeta?: Record<string, unknown>\n\t): void {\n\t\tif (level === 'info') {\n\t\t\tthis._logger.info(message, meta);\n\t\t} else if (level === 'warn') {\n\t\t\tthis._logger.warn(message, meta);\n\t\t} else {\n\t\t\tthis._logger.error(message, meta);\n\t\t}\n\t}\n\n\t/**\n\t * Check if transport is shutting down.\n\t * @returns true if in shutdown phase\n\t */\n\tpublic get isShuttingDown(): boolean {\n\t\treturn this._isShuttingDown;\n\t}\n\n\t/**\n\t * Handle GET /health endpoint — liveness check.\n\t *\n\t * Builds a standard health response with optional liveness data from the health checker.\n\t * Transports can pass extra data (e.g. client counts, session info).\n\t *\n\t * @param res - The server response\n\t * @param extraData - Optional additional health metadata\n\t */\n\tprotected handleHealthEndpoint(res: ServerResponse, extraData?: Record<string, unknown>): void {\n\t\tconst healthData: Record<string, unknown> = { status: 'healthy', ...extraData };\n\t\tif (this._healthChecker) {\n\t\t\tconst liveness = this._healthChecker.checkLiveness();\n\t\t\thealthData.liveness = liveness;\n\t\t}\n\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\tres.end(JSON.stringify(healthData));\n\t}\n\n\t/**\n\t * Handle GET /ready endpoint — readiness check.\n\t *\n\t * Delegates to the health checker if available, otherwise returns a default OK response.\n\t *\n\t * @param res - The server response\n\t */\n\tprotected async handleReadinessEndpoint(res: ServerResponse): Promise<void> {\n\t\tif (this._healthChecker) {\n\t\t\tconst readiness = await this._healthChecker.checkReadiness();\n\t\t\tconst statusCode = readiness.status === 'ok' ? 200 : 503;\n\t\t\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\t\t\tres.end(JSON.stringify(readiness));\n\t\t} else {\n\t\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({ status: 'ok', timestamp: new Date().toISOString(), components: {} })\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Handle GET /metrics endpoint — Prometheus metrics.\n\t *\n\t * Returns 404 if no metrics provider is configured.\n\t *\n\t * @param res - The server response\n\t * @param metricsProvider - Function that returns Prometheus-format metrics text\n\t */\n\tprotected handleMetricsEndpoint(res: ServerResponse, metricsProvider: (() => string) | null): void {\n\t\tif (!metricsProvider) {\n\t\t\tres.writeHead(404, { 'Content-Type': 'text/plain' });\n\t\t\tres.end('Not Found');\n\t\t\treturn;\n\t\t}\n\t\tres.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8' });\n\t\tres.end(metricsProvider());\n\t}\n\n\t/**\n\t * Connect to MCP server.\n\t */\n\tabstract connect(mcpServer: McpServer): Promise<void>;\n\n\t/**\n\t * Stop transport server with graceful shutdown.\n\t *\n\t * This method should:\n\t * 1. Set shutdown flag to prevent new connections\n\t * 2. Wait for in-flight requests to complete (configurable timeout)\n\t * 3. Close server connections\n\t * 4. Release resources\n\t *\n\t * @param timeout - Maximum time to wait for requests to drain (default: 30 seconds)\n\t * @returns Promise that resolves when shutdown is complete\n\t */\n\tabstract stop(timeout?: number): Promise<void>;\n\n\t/**\n\t * Get number of clients connected.\n\t */\n\tabstract get clientCount(): number;\n\n}\n"],"names":["NoopLogger","_message","_meta","level","ALLOWED_QUERY_PARAMS","Set","RATE_LIMIT_REQUESTS","RATE_LIMIT_WINDOW_MS","BaseTransport","Map","options","undefined","host","sessionId","MAX_SESSION_ID_LENGTH","SESSION_ID_PATTERN","url","sanitized","key","value","ip","now","Date","record","clearInterval","setInterval","req","forwardedFor","remoteAddress","origin","escaped","regex","RegExp","res","rawHost","hostWithoutPort","configuredHosts","Boolean","boundHost","localHosts","message","meta","extraData","healthData","liveness","JSON","readiness","statusCode","metricsProvider"],"m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C,OAAO,IAAI,CAAC,eAAe;IAC5B;IAWU,qBAAqBR,GAAmB,EAAES,SAAmC,EAAQ;QAC9F,MAAMC,aAAsC;YAAE,QAAQ;YAAW,GAAGD,SAAS;QAAC;QAC9E,IAAI,IAAI,CAAC,cAAc,EAAE;YACxB,MAAME,WAAW,IAAI,CAAC,cAAc,CAAC,aAAa;YAClDD,WAAW,QAAQ,GAAGC;QACvB;QACAX,IAAI,SAAS,CAAC,KAAK;YAAE,gBAAgB;QAAmB;QACxDA,IAAI,GAAG,CAACY,KAAK,SAAS,CAACF;IACxB;IASA,MAAgB,wBAAwBV,GAAmB,EAAiB;QAC3E,IAAI,IAAI,CAAC,cAAc,EAAE;YACxB,MAAMa,YAAY,MAAM,IAAI,CAAC,cAAc,CAAC,cAAc;YAC1D,MAAMC,aAAaD,AAAqB,SAArBA,UAAU,MAAM,GAAY,MAAM;YACrDb,IAAI,SAAS,CAACc,YAAY;gBAAE,gBAAgB;YAAmB;YAC/Dd,IAAI,GAAG,CAACY,KAAK,SAAS,CAACC;QACxB,OAAO;YACNb,IAAI,SAAS,CAAC,KAAK;gBAAE,gBAAgB;YAAmB;YACxDA,IAAI,GAAG,CACNY,KAAK,SAAS,CAAC;gBAAE,QAAQ;gBAAM,WAAW,IAAIvB,OAAO,WAAW;gBAAI,YAAY,CAAC;YAAE;QAErF;IACD;IAUU,sBAAsBW,GAAmB,EAAEe,eAAsC,EAAQ;QAClG,IAAI,CAACA,iBAAiB;YACrBf,IAAI,SAAS,CAAC,KAAK;gBAAE,gBAAgB;YAAa;YAClDA,IAAI,GAAG,CAAC;YACR;QACD;QACAA,IAAI,SAAS,CAAC,KAAK;YAAE,gBAAgB;QAA2C;QAChFA,IAAI,GAAG,CAACe;IACT;AA0BD"}
|
|
1
|
+
{"version":3,"file":"transport/BaseTransport.js","sources":["../../src/transport/BaseTransport.ts"],"sourcesContent":["/**\n * Base transport implementation.\n *\n * This class provides shared functionality for all transport implementations,\n * including session validation, rate limiting, CORS handling, and IP extraction.\n *\n * @remarks\n * **Security Features:**\n * - Session ID validation (alphanumeric, max 64 chars)\n * - Rate limiting per IP (configurable, default 100 req/min)\n * - CORS origin validation\n *\n * **Rate Limiting:**\n * - Tracks requests per IP address within a time window\n * - Returns 429 Too Many Requests when limit exceeded\n * - Can be disabled via `enableRateLimit: false`\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { HealthChecker } from '../health/HealthChecker.js';\nimport type { Logger, LogLevel } from '../logger/StructuredLogger.js';\nimport { SESSION_ID_PATTERN, MAX_SESSION_ID_LENGTH } from '../core/ids.js';\nimport type { McpServer } from 'tmcp';\n\n/**\n * No-op logger that does nothing. Used when no logger is provided.\n */\nclass NoopLogger implements Logger {\n\tprivate _level: LogLevel = 'info';\n\n\tinfo(_message: string, _meta?: Record<string, unknown>): void {}\n\twarn(_message: string, _meta?: Record<string, unknown>): void {}\n\terror(_message: string, _meta?: Record<string, unknown>): void {}\n\tdebug(_message: string, _meta?: Record<string, unknown>): void {}\n\tsetLevel(level: LogLevel): void {\n\t\tthis._level = level;\n\t}\n\tgetLevel(): LogLevel {\n\t\treturn this._level;\n\t}\n}\n\n/**\n * Rate limit settings (requests per minute per IP).\n */\nconst RATE_LIMIT_REQUESTS = 100;\nconst RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute\n\nexport interface TransportOptions {\n\treadonly port?: number;\n\treadonly host?: string;\n\treadonly allowedHosts?: string[];\n\treadonly corsOrigin?: string;\n\treadonly enableCors?: boolean;\n\treadonly enableRateLimit?: boolean;\n\treadonly maxRequestsPerMinute?: number;\n\treadonly logger?: Logger;\n\treadonly healthChecker?: HealthChecker;\n}\n\nexport abstract class BaseTransport {\n\tprotected _port: number;\n\tprotected _host: string;\n\tprotected _corsOrigin: string;\n\tprotected _enableCors: boolean;\n\tprotected _rateLimitEnabled: boolean;\n\tprotected _maxRequestsPerMinute: number;\n\tprotected _allowedHosts: Set<string>;\n\tprotected _rateLimitMap: Map<string, { count: number; resetTime: number }> = new Map();\n\tprotected _rateLimitCleanupIntervalId: NodeJS.Timeout | null = null;\n\tprotected _wasHostExplicitlySet: boolean;\n\t/** Shutdown state for graceful shutdown. */\n\tprotected _isShuttingDown: boolean = false;\n\tprivate _logger: Logger | NoopLogger;\n\tprotected _healthChecker: HealthChecker | null;\n\n\tconstructor(options: TransportOptions = {}) {\n\t\tthis._port = options.port ?? 9108;\n\t\tthis._host = options.host ?? '127.0.0.1';\n\t\tthis._wasHostExplicitlySet = options.host !== undefined;\n\t\tthis._corsOrigin = options.corsOrigin ?? '*';\n\t\tthis._enableCors = options.enableCors ?? true;\n\t\tthis._rateLimitEnabled = options.enableRateLimit ?? true;\n\t\tthis._maxRequestsPerMinute = options.maxRequestsPerMinute ?? RATE_LIMIT_REQUESTS;\n\t\tthis._allowedHosts = this._buildAllowedHosts(options.allowedHosts);\n\t\tthis._isShuttingDown = false;\n\t\tthis._logger = options.logger ?? new NoopLogger();\n\t\tthis._healthChecker = options.healthChecker ?? null;\n\n\t\tif (this._rateLimitEnabled) {\n\t\t\tthis._startRateLimitCleanup();\n\t\t}\n\t}\n\n\t/**\n\t * Get the server URL with localhost substitution for default host.\n\t */\n\tget serverUrl(): string {\n\t\tconst host =\n\t\t\t!this._wasHostExplicitlySet && this._host === '127.0.0.1' ? 'localhost' : this._host;\n\t\treturn `http://${host}:${this._port}`;\n\t}\n\n\t/**\n\t * Validate session ID format.\n\t *\n\t * @param sessionId - The session ID to validate\n\t * @returns true if valid, false otherwise\n\t */\n\tprotected validateSessionId(sessionId: string): boolean {\n\t\tif (sessionId.length > MAX_SESSION_ID_LENGTH) {\n\t\t\treturn false;\n\t\t}\n\t\treturn SESSION_ID_PATTERN.test(sessionId);\n\t}\n\n\t/**\n\t * Check rate limit for a given IP address.\n\t *\n\t * @param ip - The IP address to check\n\t * @returns true if rate limit exceeded, false otherwise\n\t */\n\tprotected checkRateLimit(ip: string): boolean {\n\t\tif (!this._rateLimitEnabled) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst now = Date.now();\n\t\tthis._cleanupExpiredRateLimitEntries(now);\n\t\tconst record = this._rateLimitMap.get(ip);\n\n\t\tif (!record || now > record.resetTime) {\n\t\t\tthis._rateLimitMap.set(ip, {\n\t\t\t\tcount: 1,\n\t\t\t\tresetTime: now + RATE_LIMIT_WINDOW_MS,\n\t\t\t});\n\t\t\treturn false;\n\t\t}\n\n\t\tif (record.count >= this._maxRequestsPerMinute) {\n\t\t\treturn true; // Rate limit exceeded\n\t\t}\n\n\t\trecord.count++;\n\t\treturn false;\n\t}\n\n\tprotected _cleanupExpiredRateLimitEntries(now = Date.now()): void {\n\t\tfor (const [ip, record] of this._rateLimitMap.entries()) {\n\t\t\tif (record.resetTime <= now) {\n\t\t\t\tthis._rateLimitMap.delete(ip);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected _startRateLimitCleanup(): void {\n\t\tif (this._rateLimitCleanupIntervalId !== null) {\n\t\t\tclearInterval(this._rateLimitCleanupIntervalId);\n\t\t}\n\n\t\tthis._rateLimitCleanupIntervalId = setInterval(() => {\n\t\t\tthis._cleanupExpiredRateLimitEntries();\n\t\t}, RATE_LIMIT_WINDOW_MS);\n\t}\n\n\tprotected _stopRateLimitCleanup(): void {\n\t\tif (this._rateLimitCleanupIntervalId !== null) {\n\t\t\tclearInterval(this._rateLimitCleanupIntervalId);\n\t\t\tthis._rateLimitCleanupIntervalId = null;\n\t\t}\n\t}\n\n\t/**\n\t * Get client IP address from request.\n\t *\n\t * @param req - The incoming request\n\t * @returns The client IP address\n\t */\n\tprotected getClientIp(req: IncomingMessage): string {\n\t\tconst forwardedFor = req.headers['x-forwarded-for'];\n\t\tif (forwardedFor && typeof forwardedFor === 'string') {\n\t\t\treturn forwardedFor.split(',')[0]!.trim();\n\t\t}\n\t\tconst remoteAddress = req.socket.remoteAddress;\n\t\treturn remoteAddress || 'unknown';\n\t}\n\n\t/**\n\t * Validate CORS origin from request headers.\n\t *\n\t * @param req - The incoming request\n\t * @returns true if origin is valid, false otherwise\n\t */\n\tprotected validateCorsOrigin(req: IncomingMessage): boolean {\n\t\tif (this._corsOrigin === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst origin = req.headers.origin;\n\t\tif (!origin) {\n\t\t\treturn true; // No origin header is acceptable\n\t\t}\n\n\t\t// Exact match\n\t\tif (this._corsOrigin === origin) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check if configured origin is a wildcard pattern\n\t\tif (this._corsOrigin.includes('*')) {\n\t\t\t// Escape all regex metacharacters EXCEPT *,\n\t\t\t// then replace * with a hostname-safe pattern (alphanumeric, hyphens, dots)\n\t\t\tconst escaped = this._corsOrigin\n\t\t\t\t.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // escape metacharacters (not *)\n\t\t\t\t.replace(/\\*/g, '[a-zA-Z0-9.-]*'); // * matches valid hostname chars only\n\t\t\tconst regex = new RegExp(`^${escaped}$`);\n\t\t\treturn regex.test(origin);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Set CORS headers on response.\n\t *\n\t * @param res - The server response\n\t */\n\tprotected setCorsHeaders(res: ServerResponse): void {\n\t\tif (this._enableCors) {\n\t\t\tres.setHeader('Access-Control-Allow-Origin', this._corsOrigin);\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\t\t}\n\t}\n\n\tprotected validateHostHeader(req: IncomingMessage): boolean {\n\t\tconst rawHost = req.headers.host;\n\t\tif (!rawHost) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst hostWithoutPort = rawHost.split(':')[0]!.trim().toLowerCase();\n\t\tif (!hostWithoutPort) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (this._allowedHosts.size === 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn this._allowedHosts.has(hostWithoutPort);\n\t}\n\n\tprivate _buildAllowedHosts(configuredHosts?: string[]): Set<string> {\n\t\tif (configuredHosts && configuredHosts.length > 0) {\n\t\t\treturn new Set(configuredHosts.map((host) => host.toLowerCase().trim()).filter(Boolean));\n\t\t}\n\n\t\tconst boundHost = this._host.toLowerCase();\n\t\tconst localHosts = ['localhost', '127.0.0.1', '::1'];\n\n\t\tif (localHosts.includes(boundHost)) {\n\t\t\treturn new Set(localHosts);\n\t\t}\n\n\t\tif (boundHost === '0.0.0.0' || boundHost === '::') {\n\t\t\treturn new Set(localHosts);\n\t\t}\n\n\t\treturn new Set([boundHost]);\n\t}\n\n\t/**\n\t * Log a message using the configured logger.\n\t *\n\t * @param level - Log level\n\t * @param message - Message to log\n\t * @param meta - Optional metadata\n\t */\n\tprotected log(\n\t\tlevel: 'info' | 'warn' | 'error',\n\t\tmessage: string,\n\t\tmeta?: Record<string, unknown>\n\t): void {\n\t\tif (level === 'info') {\n\t\t\tthis._logger.info(message, meta);\n\t\t} else if (level === 'warn') {\n\t\t\tthis._logger.warn(message, meta);\n\t\t} else {\n\t\t\tthis._logger.error(message, meta);\n\t\t}\n\t}\n\n\t/**\n\t * Check if transport is shutting down.\n\t * @returns true if in shutdown phase\n\t */\n\tpublic get isShuttingDown(): boolean {\n\t\treturn this._isShuttingDown;\n\t}\n\n\t/**\n\t * Handle GET /health endpoint — liveness check.\n\t *\n\t * Builds a standard health response with optional liveness data from the health checker.\n\t * Transports can pass extra data (e.g. client counts, session info).\n\t *\n\t * @param res - The server response\n\t * @param extraData - Optional additional health metadata\n\t */\n\tprotected handleHealthEndpoint(res: ServerResponse, extraData?: Record<string, unknown>): void {\n\t\tconst healthData: Record<string, unknown> = { status: 'healthy', ...extraData };\n\t\tif (this._healthChecker) {\n\t\t\tconst liveness = this._healthChecker.checkLiveness();\n\t\t\thealthData.liveness = liveness;\n\t\t}\n\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\tres.end(JSON.stringify(healthData));\n\t}\n\n\t/**\n\t * Handle GET /ready endpoint — readiness check.\n\t *\n\t * Delegates to the health checker if available, otherwise returns a default OK response.\n\t *\n\t * @param res - The server response\n\t */\n\tprotected async handleReadinessEndpoint(res: ServerResponse): Promise<void> {\n\t\tif (this._healthChecker) {\n\t\t\tconst readiness = await this._healthChecker.checkReadiness();\n\t\t\tconst statusCode = readiness.status === 'ok' ? 200 : 503;\n\t\t\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\t\t\tres.end(JSON.stringify(readiness));\n\t\t} else {\n\t\t\tres.writeHead(200, { 'Content-Type': 'application/json' });\n\t\t\tres.end(\n\t\t\t\tJSON.stringify({ status: 'ok', timestamp: new Date().toISOString(), components: {} })\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Handle GET /metrics endpoint — Prometheus metrics.\n\t *\n\t * Returns 404 if no metrics provider is configured.\n\t *\n\t * @param res - The server response\n\t * @param metricsProvider - Function that returns Prometheus-format metrics text\n\t */\n\tprotected handleMetricsEndpoint(res: ServerResponse, metricsProvider: (() => string) | null): void {\n\t\tif (!metricsProvider) {\n\t\t\tres.writeHead(404, { 'Content-Type': 'text/plain' });\n\t\t\tres.end('Not Found');\n\t\t\treturn;\n\t\t}\n\t\tres.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8' });\n\t\tres.end(metricsProvider());\n\t}\n\n\t/**\n\t * Connect to MCP server.\n\t */\n\tabstract connect(mcpServer: McpServer): Promise<void>;\n\n\t/**\n\t * Stop transport server with graceful shutdown.\n\t *\n\t * This method should:\n\t * 1. Set shutdown flag to prevent new connections\n\t * 2. Wait for in-flight requests to complete (configurable timeout)\n\t * 3. Close server connections\n\t * 4. Release resources\n\t *\n\t * @param timeout - Maximum time to wait for requests to drain (default: 30 seconds)\n\t * @returns Promise that resolves when shutdown is complete\n\t */\n\tabstract stop(timeout?: number): Promise<void>;\n\n\t/**\n\t * Get number of clients connected.\n\t */\n\tabstract get clientCount(): number;\n\n}\n"],"names":["NoopLogger","_message","_meta","level","RATE_LIMIT_REQUESTS","RATE_LIMIT_WINDOW_MS","BaseTransport","Map","options","undefined","host","sessionId","MAX_SESSION_ID_LENGTH","SESSION_ID_PATTERN","ip","now","Date","record","clearInterval","setInterval","req","forwardedFor","remoteAddress","origin","escaped","regex","RegExp","res","rawHost","hostWithoutPort","configuredHosts","Set","Boolean","boundHost","localHosts","message","meta","extraData","healthData","liveness","JSON","readiness","statusCode","metricsProvider"],"mappings":";AA2BA,MAAMA;IACG,SAAmB,OAAO;IAElC,KAAKC,QAAgB,EAAEC,KAA+B,EAAQ,CAAC;IAC/D,KAAKD,QAAgB,EAAEC,KAA+B,EAAQ,CAAC;IAC/D,MAAMD,QAAgB,EAAEC,KAA+B,EAAQ,CAAC;IAChE,MAAMD,QAAgB,EAAEC,KAA+B,EAAQ,CAAC;IAChE,SAASC,KAAe,EAAQ;QAC/B,IAAI,CAAC,MAAM,GAAGA;IACf;IACA,WAAqB;QACpB,OAAO,IAAI,CAAC,MAAM;IACnB;AACD;AAKA,MAAMC,sBAAsB;AAC5B,MAAMC,uBAAuB;AActB,MAAeC;IACX,MAAc;IACd,MAAc;IACd,YAAoB;IACpB,YAAqB;IACrB,kBAA2B;IAC3B,sBAA8B;IAC9B,cAA2B;IAC3B,gBAAmE,IAAIC,MAAM;IAC7E,8BAAqD,KAAK;IAC1D,sBAA+B;IAE/B,kBAA2B,MAAM;IACnC,QAA6B;IAC3B,eAAqC;IAE/C,YAAYC,UAA4B,CAAC,CAAC,CAAE;QAC3C,IAAI,CAAC,KAAK,GAAGA,QAAQ,IAAI,IAAI;QAC7B,IAAI,CAAC,KAAK,GAAGA,QAAQ,IAAI,IAAI;QAC7B,IAAI,CAAC,qBAAqB,GAAGA,AAAiBC,WAAjBD,QAAQ,IAAI;QACzC,IAAI,CAAC,WAAW,GAAGA,QAAQ,UAAU,IAAI;QACzC,IAAI,CAAC,WAAW,GAAGA,QAAQ,UAAU,IAAI;QACzC,IAAI,CAAC,iBAAiB,GAAGA,QAAQ,eAAe,IAAI;QACpD,IAAI,CAAC,qBAAqB,GAA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AAiB;IAWzB,OAAO,CAAC,aAAa;IAcrB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,gBAAgB;YAUV,eAAe;IAc7B,OAAO,CAAC,IAAI;IAMZ,6DAA6D;IACtD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI7B,sEAAsE;IAC/D,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAS5B"}
|
|
@@ -73,7 +73,7 @@ class SkillWatcher {
|
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
75
|
_log(message) {
|
|
76
|
-
if ('true' === process.env.
|
|
76
|
+
if ('true' === process.env.TRACELATTICE_WATCHER_VERBOSE) this._logger.debug(`[Watcher] ${message}`);
|
|
77
77
|
}
|
|
78
78
|
ready() {
|
|
79
79
|
return this._readyPromise;
|