@totemsdk/mcp-server 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1 +1,12 @@
1
- export {};
1
+ import type { SdkIndex } from './types.js';
2
+ declare const index: SdkIndex;
3
+ export declare const SERVER_INFO: {
4
+ readonly name: "@totemsdk/mcp-server";
5
+ readonly version: "0.2.0";
6
+ readonly capabilities: {
7
+ readonly resources: {};
8
+ readonly tools: {};
9
+ readonly prompts: {};
10
+ };
11
+ };
12
+ export { index as sdkIndex };
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sdkIndex = exports.SERVER_INFO = void 0;
3
4
  const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
4
5
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
5
6
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
@@ -7,6 +8,7 @@ const indexer_js_1 = require("./indexer.js");
7
8
  const resources_js_1 = require("./resources.js");
8
9
  const tools_js_1 = require("./tools.js");
9
10
  const index = (0, indexer_js_1.buildIndex)();
11
+ exports.sdkIndex = index;
10
12
  const server = new index_js_1.Server({ name: '@totemsdk/mcp-server', version: '0.1.0' }, { capabilities: { resources: {}, tools: {}, prompts: {} } });
11
13
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
12
14
  resources: (0, resources_js_1.listResources)(index),
@@ -111,6 +113,17 @@ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
111
113
  required: ['package'],
112
114
  },
113
115
  },
116
+ {
117
+ name: 'suggest-template',
118
+ description: 'Suggest KISSVM script templates matching a use case — describes what you want to do and returns matching templates with import paths',
119
+ inputSchema: {
120
+ type: 'object',
121
+ properties: {
122
+ usecase: { type: 'string', description: 'Describe what you want to do (e.g. "time-lock funds until a block height", "vote tally with quorum", "identity verification")' },
123
+ },
124
+ required: ['usecase'],
125
+ },
126
+ },
114
127
  ],
115
128
  }));
116
129
  server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
@@ -209,6 +222,11 @@ server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request) => {
209
222
  }
210
223
  throw new Error(`Prompt not found: ${name}`);
211
224
  });
225
+ exports.SERVER_INFO = {
226
+ name: '@totemsdk/mcp-server',
227
+ version: '0.2.0',
228
+ capabilities: { resources: {}, tools: {}, prompts: {} },
229
+ };
212
230
  async function main() {
213
231
  const transport = new stdio_js_1.StdioServerTransport();
214
232
  await server.connect(transport);
package/dist/indexer.js CHANGED
@@ -37,7 +37,16 @@ exports.buildIndex = buildIndex;
37
37
  exports.readSourceFile = readSourceFile;
38
38
  const fs = __importStar(require("fs"));
39
39
  const path = __importStar(require("path"));
40
- const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..', '..', '..');
40
+ function findRepoRoot() {
41
+ let dir = path.resolve(__dirname);
42
+ while (dir !== path.dirname(dir)) {
43
+ if (fs.existsSync(path.join(dir, 'pnpm-workspace.yaml')))
44
+ return dir;
45
+ dir = path.dirname(dir);
46
+ }
47
+ return dir;
48
+ }
49
+ const REPO_ROOT = findRepoRoot();
41
50
  const PKG_DIR = path.join(REPO_ROOT, 'packages', 'totem-sdk', 'packages');
42
51
  const TOP_PKG_DIR = path.join(REPO_ROOT, 'packages');
43
52
  const DOMAIN_GROUPS = [
@@ -45,11 +54,11 @@ const DOMAIN_GROUPS = [
45
54
  [/^identity$|^root-identity$|^authority$|^proof$|^proof-integritas$|^proofgraph$|^manifest$/, 'identity/authority'],
46
55
  [/^governance$|^recursive-mast$/, 'governance'],
47
56
  [/^edge$|^edge-adapters$|^industrial-action$|^agent-policy$/, 'edge/runtime'],
48
- [/^edge-(bacnet|ble|can|coap|grpc|lorawan|matter|modbus|mqtt|opcua|ros2)$/, 'edge/protocols'],
49
- [/^omnia(-factory|-router|-splice|-vtxo)?$/, 'blockchain/omnia'],
57
+ [/^edge-(bacnet|ble|can|coap|email|grpc|lorawan|matter|modbus|mqtt|opcua|ros2)$/, 'edge/protocols'],
58
+ [/^omnia(-factory|-router|-splice|-vtxo|-host)?$/, 'blockchain/omnia'],
50
59
  [/^statechain$|^tx-builder$|^chain-provider$|^wots-lease$|^liquidity-bond$|^provider-bond$/, 'blockchain/infra'],
51
60
  [/^lookup-(client|node|protocol)$/, 'lookup/p2p'],
52
- [/^stream-transport$|^pubsub-transport$|^pureminima-rpc$|^server$|^se-server$|^realtime$|^connect$|^wallet-adapter$|^pear$|^observability$/, 'utilities'],
61
+ [/^stream-transport$|^pubsub-transport$|^minima-rpc$|^server$|^se-server$|^realtime$|^connect$|^wallet-adapter$|^pear$|^mcp-server$|^observability$/, 'utilities'],
53
62
  [/^sdk-tests$/, 'testing'],
54
63
  ];
55
64
  function classifyDomain(dirName) {
@@ -109,11 +118,13 @@ function parseExports(dir, pkgName) {
109
118
  if (!content)
110
119
  return exports;
111
120
  const lines = content.split('\n');
112
- for (const line of lines) {
113
- const trimmed = line.trim();
121
+ let i = 0;
122
+ while (i < lines.length) {
123
+ const trimmed = lines[i].trim();
114
124
  const fnMatch = trimmed.match(/^export (async )?function (\w+)/);
115
125
  if (fnMatch) {
116
126
  exports.functions.push(fnMatch[2]);
127
+ i++;
117
128
  continue;
118
129
  }
119
130
  const typeMatch = trimmed.match(/^export type \{ ([^}]+) \}/);
@@ -123,37 +134,58 @@ function parseExports(dir, pkgName) {
123
134
  if (name)
124
135
  exports.types.push(name);
125
136
  });
137
+ i++;
126
138
  continue;
127
139
  }
128
140
  const clsMatch = trimmed.match(/^export class (\w+)/);
129
141
  if (clsMatch) {
130
142
  exports.classes.push(clsMatch[1]);
143
+ i++;
131
144
  continue;
132
145
  }
133
146
  const ifaceMatch = trimmed.match(/^export interface (\w+)/);
134
147
  if (ifaceMatch) {
135
148
  exports.interfaces.push(ifaceMatch[1]);
149
+ i++;
136
150
  continue;
137
151
  }
138
152
  const constMatch = trimmed.match(/^export (const|let|var) (\w+)/);
139
153
  if (constMatch) {
140
154
  exports.consts.push(constMatch[2]);
155
+ i++;
141
156
  continue;
142
157
  }
143
- const namedExport = trimmed.match(/^export \{ ([^}]+) \}/);
144
- if (namedExport) {
145
- for (const part of namedExport[1].split(',')) {
146
- const name = part.trim().split(/\s+as\s+/).pop()?.trim() || '';
147
- if (name && !name.startsWith('type ') && name !== 'type') {
148
- if (name.endsWith('}'))
158
+ // Handle multi-line export { ... } from '...' blocks
159
+ if (trimmed.startsWith('export {') || trimmed.startsWith('export type {')) {
160
+ const isType = trimmed.startsWith('export type {');
161
+ let block = trimmed;
162
+ let j = i;
163
+ while (!block.includes('}') && j < lines.length - 1) {
164
+ j++;
165
+ block += ' ' + lines[j].trim();
166
+ }
167
+ // Extract name list between { and }
168
+ const braceMatch = block.match(/\{([^}]+)\}/);
169
+ if (braceMatch) {
170
+ for (const part of braceMatch[1].split(',')) {
171
+ const name = part.trim().split(/\s+as\s+/).pop()?.trim() || '';
172
+ if (!name || name.endsWith('}'))
149
173
  continue;
150
- if (/^[A-Z]/.test(name))
174
+ if (isType) {
151
175
  exports.types.push(name);
152
- else
153
- exports.functions.push(name);
176
+ }
177
+ else {
178
+ if (/^[A-Z]/.test(name))
179
+ exports.types.push(name);
180
+ else
181
+ exports.functions.push(name);
182
+ }
154
183
  }
155
184
  }
185
+ i = j + 1;
186
+ continue;
156
187
  }
188
+ i++;
157
189
  }
158
190
  return exports;
159
191
  }
package/dist/resources.js CHANGED
@@ -1,7 +1,91 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.handleResourceRead = handleResourceRead;
4
37
  exports.listResources = listResources;
38
+ const template_catalog_js_1 = require("./template-catalog.js");
39
+ const fs = __importStar(require("fs"));
40
+ const path = __importStar(require("path"));
41
+ function findRepoRoot() {
42
+ let dir = path.resolve(__dirname);
43
+ while (dir !== path.dirname(dir)) {
44
+ if (fs.existsSync(path.join(dir, 'pnpm-workspace.yaml')))
45
+ return dir;
46
+ dir = path.dirname(dir);
47
+ }
48
+ return dir;
49
+ }
50
+ const REPO_ROOT = findRepoRoot();
51
+ const PAPERS = [
52
+ {
53
+ uri: 'totemsdk://papers/yellow',
54
+ name: 'Core Yellow Paper',
55
+ description: 'WOTS+ signatures, TreeKey hierarchy, MMR proofs, byte-exact serialization, lease/watermark coordination, Rust/WASM engine',
56
+ file: 'TOTEM_CORE_YELLOW_PAPER.md',
57
+ },
58
+ {
59
+ uri: 'totemsdk://papers/red',
60
+ name: 'Connect Red Paper',
61
+ description: 'dApp-wallet wire protocol specification — all 49 methods, every parameter, every response shape, error codes, security model',
62
+ file: 'TOTEM_CONNECT_RED_PAPER.md',
63
+ },
64
+ {
65
+ uri: 'totemsdk://papers/blue',
66
+ name: 'Omnia Blue Paper',
67
+ description: 'P2P payment channels, eltoo state machine, multi-hop routing, channel factories, VTXO accounting, statechain prepaid passes, lending/borrowing, off-chain tokens, privacy by design, scaling to billions of devices',
68
+ file: 'TOTEM_OMNIA_BLUE_PAPER.md',
69
+ },
70
+ {
71
+ uri: 'totemsdk://papers/green',
72
+ name: 'Governance Green Paper',
73
+ description: 'Authority mandates, delegation chains, recursive MAST 7-layer policy trees, quadratic voting, liquid democracy, QVAC agent policy, modular governance patterns',
74
+ file: 'TOTEM_GOVERNANCE_GREEN_PAPER.md',
75
+ },
76
+ {
77
+ uri: 'totemsdk://papers/grey',
78
+ name: 'Edge Grey Paper',
79
+ description: 'Port-injected transport-agnostic edge runtime, 11 protocol adapters, MachinePay credit gating, offline operation, industrial action, sensor-to-settlement bridge',
80
+ file: 'TOTEM_EDGE_GREY_PAPER.md',
81
+ },
82
+ {
83
+ uri: 'totemsdk://papers/gold',
84
+ name: 'Tokenomics Gold Paper',
85
+ description: 'Two-asset model — MINIMA as sovereign collateral backbone (Colour Coins, The Burn, Provider Bonds), TOTEM as service revenue token (staking, fee distribution, slashing, treasury)',
86
+ file: 'TOTEM_TOKENOMICS_GOLD_PAPER.md',
87
+ },
88
+ ];
5
89
  const CONVENTIONS = `# Totem SDK Conventions
6
90
 
7
91
  ## Package Structure
@@ -46,6 +130,18 @@ const CONVENTIONS = `# Totem SDK Conventions
46
130
  - Promise<T> everywhere, typed event emitters, no Observables
47
131
  - Action lifecycle: propose -> reserve -> execute -> confirm/fail/unknown`;
48
132
  function handleResourceRead(uri, index) {
133
+ const paperMatch = uri.match(/^totemsdk:\/\/papers\/(\w+)$/);
134
+ if (paperMatch) {
135
+ const paper = PAPERS.find(p => p.uri === uri);
136
+ if (paper) {
137
+ const filePath = path.join(REPO_ROOT, paper.file);
138
+ if (fs.existsSync(filePath)) {
139
+ return fs.readFileSync(filePath, 'utf-8');
140
+ }
141
+ return `Paper file not found: ${paper.file}`;
142
+ }
143
+ return null;
144
+ }
49
145
  if (uri === 'totemsdk://packages') {
50
146
  return JSON.stringify(Object.values(index.packages).map(p => ({
51
147
  name: p.name,
@@ -59,6 +155,19 @@ function handleResourceRead(uri, index) {
59
155
  }
60
156
  if (uri === 'totemsdk://conventions')
61
157
  return CONVENTIONS;
158
+ if (uri === 'totemsdk://templates') {
159
+ const all = (0, template_catalog_js_1.getAllTemplates)();
160
+ return all.map(t => {
161
+ const pkgs = Array.isArray(t.package) ? t.package : t.package ? [t.package] : [];
162
+ return {
163
+ template: t.template,
164
+ functions: t.functions,
165
+ configTypes: t.configTypes,
166
+ package: pkgs.length > 0 ? pkgs.map(p => `@totemsdk/${p}`) : ['@totemsdk/kissvm'],
167
+ description: t.description,
168
+ };
169
+ }).map(t => `## ${t.template}\n\n${t.description}\n\n**Package:** ${t.package.join(', ')}\n\n**Functions:**\n${t.functions.map(f => ` - \`import { ${f} } from '@totemsdk/kissvm'\``).join('\n')}\n`).join('\n---\n');
170
+ }
62
171
  if (uri === 'totemsdk://domain-map') {
63
172
  return JSON.stringify(index.domainMap, null, 2);
64
173
  }
@@ -93,9 +202,11 @@ function handleResourceRead(uri, index) {
93
202
  }
94
203
  function listResources(index) {
95
204
  const resources = [
96
- { uri: 'totemsdk://packages', name: 'All Packages', description: 'List of all 53 SDK packages with metadata' },
205
+ { uri: 'totemsdk://packages', name: 'All Packages', description: `List of all ${Object.keys(index.packages).length} SDK packages with metadata` },
206
+ { uri: 'totemsdk://templates', name: 'All KISSVM Templates', description: 'All 45 KISSVM script templates with import paths and descriptions' },
97
207
  { uri: 'totemsdk://conventions', name: 'Coding Conventions', description: 'Totem SDK coding conventions and patterns' },
98
208
  { uri: 'totemsdk://domain-map', name: 'Domain Map', description: 'Packages grouped by domain layer' },
209
+ ...PAPERS.map(p => ({ uri: p.uri, name: p.name, description: p.description })),
99
210
  ];
100
211
  for (const [domain, pkgs] of Object.entries(index.domainMap)) {
101
212
  resources.push({
@@ -0,0 +1,12 @@
1
+ export interface TemplateEntry {
2
+ template: string;
3
+ functions: string[];
4
+ configTypes: string[];
5
+ package: string | string[] | null;
6
+ keywords: string[];
7
+ description: string;
8
+ }
9
+ export declare const TEMPLATE_CATALOG: TemplateEntry[];
10
+ export declare function getTemplatesForPackage(pkgName: string): TemplateEntry[];
11
+ export declare function searchTemplates(query: string): TemplateEntry[];
12
+ export declare function getAllTemplates(): TemplateEntry[];
@@ -0,0 +1,406 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEMPLATE_CATALOG = void 0;
4
+ exports.getTemplatesForPackage = getTemplatesForPackage;
5
+ exports.searchTemplates = searchTemplates;
6
+ exports.getAllTemplates = getAllTemplates;
7
+ exports.TEMPLATE_CATALOG = [
8
+ {
9
+ template: 'authority',
10
+ functions: ['buildMandateEnforcementScript', 'buildActionAuthorizationScript', 'buildAuthorityRevocationScript', 'buildUsageTrackingScript'],
11
+ configTypes: ['MandateEnforcementConfig', 'ActionAuthorizationConfig', 'AuthorityRevocationConfig', 'UsageTrackingConfig'],
12
+ package: 'authority',
13
+ keywords: ['mandate', 'authorization', 'replay protection', 'nonce', 'usage tracking', 'revocation epoch', 'scope', 'action auth', 'governance authority'],
14
+ description: 'Mandate enforcement, action authorization with nonce replay protection, usage tracking against limits, and revocation epoch scripts',
15
+ },
16
+ {
17
+ template: 'agent-policy',
18
+ functions: ['buildPaymentIntentScript', 'buildAgentProposalScript', 'buildPolicyEnforcementScript'],
19
+ configTypes: ['PaymentIntentConfig', 'AgentProposalConfig', 'PolicyEnforcementConfig'],
20
+ package: 'agent-policy',
21
+ keywords: ['payment intent', 'agent proposal', 'policy enforcement', 'risk threshold', 'confidence', 'status transition', 'autonomous agent', 'policy rules'],
22
+ description: 'Autonomous agent payment intents, proposal state machines with confidence thresholds, and policy rule enforcement',
23
+ },
24
+ {
25
+ template: 'eltoo',
26
+ functions: ['buildEltooChannelScript', 'buildEltooFundingScript', 'buildEltooSettlementScript', 'buildFactoryFundingScript'],
27
+ configTypes: ['EltooConfig', 'FactoryConfig'],
28
+ package: ['omnia', 'omnia-factory'],
29
+ keywords: ['eltoo', 'ln symmetry', 'channel', 'payment channel', 'funding', 'settlement', 'sequence', 'coinage', 'multisig', 'n-of-n', 'factory', 'channel factory'],
30
+ description: 'Eltoo/LN-Symmetry channel scripts with settlement/update paths, channel funding scripts, and N-of-N factory funding scripts',
31
+ },
32
+ {
33
+ template: 'governance',
34
+ functions: ['buildProposalStateMachineScript', 'buildVoteSubmissionScript', 'buildVoteTallyScript', 'buildExecutionMandateScript', 'buildTreasuryExecutionScript', 'computeScriptHash'],
35
+ configTypes: ['ProposalConfig', 'VoteSubmissionConfig', 'VoteTallyConfig', 'ExecutionMandateConfig', 'TreasuryExecutionConfig'],
36
+ package: 'governance',
37
+ keywords: ['proposal', 'state machine', 'vote submit', 'vote tally', 'quorum', 'execution mandate', 'treasury', 'execution delay', 'multisig', 'governance', 'dao', 'voting', 'commitments'],
38
+ description: 'Proposal lifecycle 7-status state machine, vote submission with nonce/weight/window, on-chain vote tally with batch delta ports, execution mandate with timelock+multisig+commitments, and treasury fund release',
39
+ },
40
+ {
41
+ template: 'industrial-action',
42
+ functions: ['buildCommitScript', 'buildRevealScript', 'buildActionStateMachineScript', 'buildEscrowEnforcementScript'],
43
+ configTypes: ['CommitConfig', 'RevealConfig', 'ActionStateMachineConfig', 'EscrowEnforcementConfig'],
44
+ package: 'industrial-action',
45
+ keywords: ['industrial action', 'strike', 'commit reveal', 'hash commit', 'preimage reveal', 'state machine', 'notice period', 'max duration', 'escrow', 'condition enforcement'],
46
+ description: 'Industrial action scripts: hash-commit and preimage reveal, 6-status action FSM (proposed/noticed/active/resolved/escalated/expired) with notice period and max duration, and condition-based escrow enforcement',
47
+ },
48
+ {
49
+ template: 'identity',
50
+ functions: ['buildIdentityVerificationScript', 'buildDelegationProofScript', 'buildRotationScript', 'buildRevocationScript'],
51
+ configTypes: ['IdentityVerificationConfig', 'DelegationProofConfig', 'RotationConfig', 'RevocationConfig'],
52
+ package: 'identity',
53
+ keywords: ['identity', 'verification', 'delegation', 'proof', 'key rotation', 'revocation', 'claim', 'did', 'public key'],
54
+ description: 'Identity verification with claim hashing, delegation proofs with expiry, key rotation with delay, and revocation with epoch',
55
+ },
56
+ {
57
+ template: 'liquidity-bond',
58
+ functions: ['buildLiquidityLockScript', 'buildFeeAccrualScript', 'buildWithdrawalScript', 'buildPositionStateMachineScript'],
59
+ configTypes: ['LiquidityLockConfig', 'PositionStateMachineConfig'],
60
+ package: 'liquidity-bond',
61
+ keywords: ['liquidity', 'bond', 'lock', 'unlock after block', 'cliff', 'fee accrual', 'pro rata', 'withdrawal', 'position', 'vesting', 'state machine'],
62
+ description: 'Liquidity lock terms with status-gated cliffs, time-pro-rated fee accrual with VERIFYOUT to governance, bounded withdrawal count, and 5-active-status position FSM',
63
+ },
64
+ {
65
+ template: 'lookup-protocol',
66
+ functions: ['buildLeaseMessageScript', 'buildCoinUpdateScript', 'buildTrustMessageScript'],
67
+ configTypes: ['LeaseMessageConfig', 'CoinUpdateConfig', 'TrustMessageConfig'],
68
+ package: 'lookup-protocol',
69
+ keywords: ['lease message', 'coin update', 'trust message', 'event type', 'new spent confirmed', 'expiry', 'state machine', 'lookup', 'p2p'],
70
+ description: 'Lease message validation with temporal deadline, coin update event type state machine, and trust message validation with expiry window',
71
+ },
72
+ {
73
+ template: 'manifest',
74
+ functions: ['buildManifestBindingScript', 'buildCapabilityScript', 'buildManifestExpiryScript'],
75
+ configTypes: ['ManifestBindingConfig', 'CapabilityConfig', 'ManifestExpiryConfig'],
76
+ package: 'manifest',
77
+ keywords: ['manifest', 'binding', 'capability', 'permission', 'expiry', 'subscription interval', 'signed at', 'publisher', 'app manifest'],
78
+ description: 'Manifest-to-identity binding with SHA3 hash, capability permission enforcement, and manifest expiry with subscription interval rate-limit',
79
+ },
80
+ {
81
+ template: 'proof',
82
+ functions: ['buildProofAnchorScript', 'buildCapabilityProofScript', 'buildRevocationProofScript', 'buildProofDelegationScript'],
83
+ configTypes: ['ProofConfig'],
84
+ package: 'proof',
85
+ keywords: ['proof', 'anchor', 'capability', 'revocation', 'delegation', 'confirm at', 'expires at', 'proof chain'],
86
+ description: 'Proof anchoring with confirmed-at block, capability/revocation/delegation proof scripts with temporal expiry',
87
+ },
88
+ {
89
+ template: 'provider-bond',
90
+ functions: ['buildBondLockupScript', 'buildHeartbeatScript', 'buildBondStateMachineScript', 'buildChallengeScript', 'buildBondReleaseScript'],
91
+ configTypes: ['ProviderBondConfig', 'BondStateMachineConfig', 'ChallengeConfig'],
92
+ package: 'provider-bond',
93
+ keywords: ['provider bond', 'stake', 'lockup', 'heartbeat', 'sla', 'bond release', 'unbonding', 'slashing', 'challenge deadline', 'state machine', 'challenge commit', 'file uphold dismiss'],
94
+ description: 'Provider bond lockup with status-gated cliffs, heartbeat enforcement with PREVSTATE elapsed tracking, 7-status bond FSM, commit/file/uphold/dismiss challenge cycle with VERIFYOUT, and bond release with governance override',
95
+ },
96
+ {
97
+ template: 'statechain',
98
+ functions: ['buildStatechainScript', 'buildStatechainOwnerRotationScript'],
99
+ configTypes: ['StateChainConfig'],
100
+ package: 'statechain',
101
+ keywords: ['statechain', 'owner rotation', 'state utxo', 'coinage reclaim', 'owner transfer', 'multisig state'],
102
+ description: 'Statechain UTXO locking script with owner rotation via STATE(0), MULTISIG(2) path, and coinage-based unilateral reclaim',
103
+ },
104
+ {
105
+ template: 'temporal',
106
+ functions: ['buildLinearRelease', 'buildCliffRelease', 'buildDeadlineScript', 'buildWindowScript', 'buildRateLimitScript', 'buildDecayScript', 'buildTemporalScript', 'computeRelease'],
107
+ configTypes: ['TemporalConfig'],
108
+ package: null,
109
+ keywords: ['temporal', 'linear release', 'vesting', 'cliff', 'deadline', 'window', 'rate limit', 'decay', 'hyperbolic', 'time lock', 'block arithmetic', 'release curve'],
110
+ description: 'Six temporal release curves: linear (vestr), cliff (delayed start), deadline (must claim before), window (valid between blocks), rate-limit (max per period), decay (hyperbolic). Includes off-chain computeRelease mirror',
111
+ },
112
+ {
113
+ template: 'txpow',
114
+ functions: ['buildTxPoWValidationScript', 'buildMagicConstantsScript'],
115
+ configTypes: ['TxPoWValidationConfig'],
116
+ package: 'txpow',
117
+ keywords: ['txpow', 'transaction validation', 'magic constants', 'max size', 'max ops', 'min work', 'protocol constants'],
118
+ description: 'TxPoW validation scripts for max transaction size, max KISSVM ops, minimum work threshold, and magic protocol constant enforcement',
119
+ },
120
+ {
121
+ template: 'wots-lease',
122
+ functions: ['buildLeaseCertificateScript', 'buildWatermarkTrackingScript', 'buildLeaseStateMachineScript'],
123
+ configTypes: ['LeaseCertificateConfig'],
124
+ package: 'wots-lease',
125
+ keywords: ['wots', 'lease', 'certificate', 'watermark', 'key lease', 'state machine', 'pending active expired', 'tree id', 'device id'],
126
+ description: 'WOTS lease certificate validation with temporal expiry, monotonically advancing watermark tracking, and lease state machine with pending/active/expired transitions',
127
+ },
128
+ {
129
+ template: 'commercial',
130
+ functions: ['maasLayer', 'payPerUseLayer', 'featureLicenseLayer', 'warrantyLayer', 'escrowLayer', 'leasingLayer', 'telemetryLicenseLayer', 'carbonProgrammeLayer', 'usageBasedInsuranceLayer', 'vehicleToGridLayer'],
131
+ configTypes: [],
132
+ package: null,
133
+ keywords: ['commercial', 'maas', 'pay per use', 'feature license', 'warranty', 'escrow', 'leasing', 'telemetry', 'carbon', 'insurance', 'v2g', 'monetization'],
134
+ description: 'Commercial MAST policy layers for MaaS, pay-per-use, feature licensing, warranty, escrow, leasing, telemetry, carbon programmes, usage-based insurance, and vehicle-to-grid',
135
+ },
136
+ {
137
+ template: 'compliance',
138
+ functions: ['buildCompliancePipeline', 'buildStandardCompliancePipeline', 'buildSupplyChainPipeline'],
139
+ configTypes: ['ComplianceStage', 'CompliancePipelineConfig'],
140
+ package: null,
141
+ keywords: ['compliance', 'pipeline', 'kyc', 'aml', 'sanctions', 'regulatory', 'supply chain compliance', 'audit'],
142
+ description: 'Compliance pipeline builder for regulatory stages, KYC/AML checks, and supply chain compliance verification',
143
+ },
144
+ {
145
+ template: 'data-privacy',
146
+ functions: ['buildDataAccessConsentScript', 'buildGdprSubjectRequestScript', 'buildDataPortabilityScript', 'buildZkProofIntegrationScript', 'buildDataEscrowScript'],
147
+ configTypes: [],
148
+ package: null,
149
+ keywords: ['data privacy', 'gdpr', 'consent', 'subject request', 'data portability', 'zk proof', 'escrow', 'personal data'],
150
+ description: 'Data privacy scripts for GDPR consent management, subject access requests, data portability, zero-knowledge proof integration, and data escrow',
151
+ },
152
+ {
153
+ template: 'device-lifecycle',
154
+ functions: ['commissioningLayer', 'transferLayer', 'keyRotationLayer', 'recoveryLayer', 'decommissioningLayer', 'remoteSupportLayer', 'configurationProfileLayer', 'certificateIssuanceLayer'],
155
+ configTypes: [],
156
+ package: null,
157
+ keywords: ['device lifecycle', 'commissioning', 'transfer', 'key rotation', 'recovery', 'decommissioning', 'remote support', 'config profile', 'certificate'],
158
+ description: 'Device lifecycle MAST policy layers for commissioning, ownership transfer, key rotation, recovery, decommissioning, remote support, configuration profiles, and certificate issuance',
159
+ },
160
+ {
161
+ template: 'energy',
162
+ functions: ['buildRecTradingScript', 'buildMicrogridScript', 'buildP2PEnergyScript', 'buildDemandResponseScript', 'buildNetMeteringScript'],
163
+ configTypes: [],
164
+ package: null,
165
+ keywords: ['energy', 'rec', 'renewable energy certificate', 'microgrid', 'p2p energy', 'demand response', 'net metering', 'smart grid'],
166
+ description: 'Energy trading scripts for REC trading, microgrid management, peer-to-peer energy, demand response, and net metering',
167
+ },
168
+ {
169
+ template: 'firmware-update',
170
+ functions: ['buildFirmwareUpdateScript'],
171
+ configTypes: ['FirmwareUpdateConfig'],
172
+ package: null,
173
+ keywords: ['firmware update', 'ota', 'over the air', 'signed update', 'version verification'],
174
+ description: 'Secure firmware update script with signed update verification and version enforcement',
175
+ },
176
+ {
177
+ template: 'healthcare',
178
+ functions: ['buildMedicalDeviceRegulationScript', 'buildPatientConsentScript', 'buildClinicalTrialScript', 'buildPrescriptionScript', 'buildHealthDataAccessScript'],
179
+ configTypes: [],
180
+ package: null,
181
+ keywords: ['healthcare', 'medical device', 'regulation', 'patient consent', 'clinical trial', 'prescription', 'health data', 'hipaa'],
182
+ description: 'Healthcare scripts for medical device regulation compliance, patient consent management, clinical trial data, prescription verification, and health data access',
183
+ },
184
+ {
185
+ template: 'layers',
186
+ functions: ['assetLayer', 'manufacturerLayer', 'productLayer', 'regulatoryLayer', 'ownerLayer', 'siteLayer', 'operatorLayer', 'emergencyLayer'],
187
+ configTypes: [],
188
+ package: null,
189
+ keywords: ['mast layer', 'policy layer', 'asset', 'manufacturer', 'product', 'regulatory', 'owner', 'site', 'operator', 'emergency', 'layered policy'],
190
+ description: 'Standard 7-layer MAST policy chain: asset → manufacturer → product → regulatory → owner → site → operator, plus emergency override layer',
191
+ },
192
+ {
193
+ template: 'legal',
194
+ functions: ['buildDocumentNotarizationScript', 'buildTimestampVerificationScript', 'buildSmartContractExecutionScript', 'buildPowerOfAttorneyScript', 'buildMultiJurisdictionScript'],
195
+ configTypes: [],
196
+ package: null,
197
+ keywords: ['legal', 'notarization', 'timestamp', 'smart contract', 'power of attorney', 'multi jurisdiction', 'document'],
198
+ description: 'Legal scripts for document notarization, timestamp verification, smart contract execution, power of attorney, and multi-jurisdiction enforcement',
199
+ },
200
+ {
201
+ template: 'payment-channel',
202
+ functions: ['buildPaymentChannelScript', 'buildChannelFactoryScript'],
203
+ configTypes: ['PaymentChannelConfig'],
204
+ package: null,
205
+ keywords: ['payment channel', 'channel factory', 'micro payment', 'state channel', 'off chain', 'layer 2'],
206
+ description: 'Payment channel script with MAST-based state updates and channel factory for N-of-N funding with settlement paths',
207
+ },
208
+ {
209
+ template: 'recovery',
210
+ functions: ['buildThresholdRecoveryScript', 'buildEpochRotationScript', 'buildDelegatedCredentialScript', 'buildInstitutionalHierarchy', 'buildSuccessionScript'],
211
+ configTypes: ['ThresholdRecoveryConfig', 'EpochRotationConfig', 'DelegatedCredentialConfig', 'InstitutionalHierarchyConfig', 'SuccessionConfig'],
212
+ package: null,
213
+ keywords: ['recovery', 'threshold', 'social recovery', 'epoch rotation', 'delegated credential', 'institutional hierarchy', 'succession', 'key recovery'],
214
+ description: 'Key recovery scripts: threshold/social recovery, epoch-based key rotation, delegated credentials, institutional hierarchy, and succession planning',
215
+ },
216
+ {
217
+ template: 'rwa-lifecycle',
218
+ functions: ['buildAssetTokenizationScript', 'buildFractionalizationScript', 'buildAuditTrailScript', 'buildDistributionScript', 'buildShareTransferScript', 'buildRedemptionScript', 'buildAssetDisposalScript', 'buildRwaPolicyTree'],
219
+ configTypes: [],
220
+ package: null,
221
+ keywords: ['rwa', 'real world asset', 'tokenization', 'fractionalization', 'audit trail', 'distribution', 'share transfer', 'redemption', 'disposal'],
222
+ description: 'Real-world asset lifecycle scripts for tokenization, fractionalization, audit trails, distribution, share transfer, redemption, and asset disposal',
223
+ },
224
+ {
225
+ template: 'sensor-proof',
226
+ functions: ['buildSensorProofScript', 'buildSensorFleetPolicy', 'buildSensorProofChain'],
227
+ configTypes: ['SensorProofConfig'],
228
+ package: null,
229
+ keywords: ['sensor', 'proof', 'iot', 'data proof', 'sensor fleet', 'proof chain', 'telemetry'],
230
+ description: 'Sensor data proof scripts for individual sensor attestations, fleet-wide policies, and chained multi-sensor proofs',
231
+ },
232
+ {
233
+ template: 'state-machine',
234
+ functions: ['buildStateMachineScript', 'buildStateMachineWorkflow', 'onOffStateMachine', 'hvacStateMachine', 'productionStateMachine', 'robotArmStateMachine'],
235
+ configTypes: ['StateMachineConfig'],
236
+ package: null,
237
+ keywords: ['state machine', 'workflow', 'on off', 'hvac', 'production', 'robot arm', 'iot state', 'device state'],
238
+ description: 'Generic state machine template with predefined workflows for on/off devices, HVAC systems, production lines, and robot arms',
239
+ },
240
+ {
241
+ template: 'supply-chain',
242
+ functions: ['buildProvenanceScript', 'buildColdChainScript', 'buildBillOfLadingScript', 'buildCustomsClearanceScript', 'buildInventoryScript', 'buildQualityInspectionScript'],
243
+ configTypes: [],
244
+ package: null,
245
+ keywords: ['supply chain', 'provenance', 'cold chain', 'bill of lading', 'customs clearance', 'inventory', 'quality inspection', 'logistics'],
246
+ description: 'Supply chain scripts for provenance tracking, cold chain monitoring, bills of lading, customs clearance, inventory management, and quality inspection',
247
+ },
248
+ {
249
+ template: 'treasury',
250
+ functions: ['buildMultiSigTreasuryScript', 'buildBudgetAllocationScript', 'buildTimeLockedReserveScript', 'buildProposalExecutionScript', 'buildStreamingPaymentScript', 'buildTreasuryDelegationChain'],
251
+ configTypes: [],
252
+ package: null,
253
+ keywords: ['treasury', 'multisig', 'budget', 'time lock', 'reserve', 'proposal execution', 'streaming payment', 'delegation chain', 'fund management'],
254
+ description: 'Treasury management scripts for multi-sig control, budget allocation, time-locked reserves, proposal execution, streaming payments, and delegation chains',
255
+ },
256
+ {
257
+ template: 'voting',
258
+ functions: ['buildWeightedVotingScript', 'buildLiquidDemocracyScript', 'buildQuadraticVotingScript', 'buildElectionVerificationScript', 'buildDelegateRecallScript'],
259
+ configTypes: [],
260
+ package: null,
261
+ keywords: ['voting', 'weighted', 'liquid democracy', 'quadratic', 'election', 'delegate recall', 'governance vote', 'ballot'],
262
+ description: 'Voting scripts for weighted voting, liquid democracy delegation, quadratic voting, election verification, and delegate recall',
263
+ },
264
+ {
265
+ template: 'recursive-mast-delegation',
266
+ functions: ['buildDelegationLink', 'buildDelegationScript', 'buildDelegationChain', 'verifyDelegationChain', 'toDelegationChainScript'],
267
+ configTypes: [],
268
+ package: 'recursive-mast',
269
+ keywords: ['delegation chain', 'delegation link', 'authority delegation', 'nested mast delegation', 'policy delegation', 'recursive mast'],
270
+ description: 'Recursive MAST delegation chain builder — hierarchical authority delegation with proof-of-delegation via nested MAST. Builds on top of KISSVM policy-tree and proof-chain primitives',
271
+ },
272
+ {
273
+ template: 'recursive-mast-cross-domain',
274
+ functions: ['buildCrossDomainBridge', 'buildAcceptanceScript', 'buildBidirectionalBridge', 'buildTrustNetwork'],
275
+ configTypes: [],
276
+ package: 'recursive-mast',
277
+ keywords: ['cross domain', 'trust bridge', 'inter policy', 'acceptance script', 'bidirectional bridge', 'trust network', 'domain trust'],
278
+ description: 'Cross-domain trust bridge for inter-policy-space trust — enables policies in different domains to recognise and verify each other through acceptance scripts and bidirectional bridges',
279
+ },
280
+ {
281
+ template: 'recursive-mast-migration',
282
+ functions: ['buildMigrationStep', 'buildMigrationScript', 'buildMigrationPath', 'isMigrationActive', 'isMigrationComplete', 'getActivePolicyRoot', 'toMigrationPathScript'],
283
+ configTypes: [],
284
+ package: 'recursive-mast',
285
+ keywords: ['migration path', 'policy migration', 'upgradeable policy', 'migration step', 'policy root rotation', 'version upgrade'],
286
+ description: 'Policy migration path constructor — upgradeable policy systems with step-by-step migration scripts, active root tracking, and version transitions via the policy anchor coin',
287
+ },
288
+ {
289
+ template: 'recursive-mast-signing',
290
+ functions: ['createSigningRequest', 'createSigningResponse', 'collectSigningResponses', 'buildRecursiveWitnessPlan', 'verifySigningRequest'],
291
+ configTypes: ['CreateSigningRequestConfig', 'CreateSigningResponseConfig', 'SigningRoundResult', 'PolicySigningRequest', 'PolicySigningResponse', 'ScriptDisclosure', 'SignedEvidence', 'PolicyPathDescriptor'],
292
+ package: 'recursive-mast',
293
+ keywords: ['signing request', 'signing response', 'witness plan', 'multi party signing', 'transaction signing', 'policy signing', 'collect signatures'],
294
+ description: 'Policy signing request/response coordination — multi-party signing with recursive witness planning, script disclosure, and signed evidence collection for nested MAST transactions',
295
+ },
296
+ {
297
+ template: 'recursive-mast-session',
298
+ functions: ['createSigningSession', 'advanceSession', 'acceptResponse', 'recordEvidence', 'submitSession', 'confirmSession', 'cancelSession', 'sessionSummary'],
299
+ configTypes: ['SigningSession', 'SigningSessionConfig', 'SigningSessionStatus', 'RequiredRoleState', 'EvidenceState'],
300
+ package: 'recursive-mast',
301
+ keywords: ['signing session', 'multi party', 'state machine', 'evidence collection', 'transaction coordination', 'signing round', 'session management'],
302
+ description: 'Multi-party signing session state machine — manages the full lifecycle of a coordinated signing round: create, advance through required roles, accept responses, record evidence, submit, confirm, or cancel',
303
+ },
304
+ {
305
+ template: 'recursive-mast-discovery',
306
+ functions: ['announcePolicy', 'queryPolicies', 'resolvePolicyForSubject', 'watchPolicy'],
307
+ configTypes: ['PolicyLookupClient', 'PolicyQueryResult', 'PolicyUpdateNotification', 'AnnouncePolicyConfig', 'QueryPolicyConfig', 'ResolvePolicyConfig', 'ResolvedPolicy', 'WatchPolicyConfig'],
308
+ package: 'recursive-mast',
309
+ keywords: ['policy discovery', 'announce', 'query', 'resolve', 'watch', 'policy lookup', 'service discovery', 'policy registry'],
310
+ description: 'Policy discovery protocol — announce policies to a lookup client, query available policies, resolve policies for specific subjects, and watch for updates',
311
+ },
312
+ {
313
+ template: 'recursive-mast-branch-capsule',
314
+ functions: ['serializeBranchPackage', 'deserializeBranchPackage', 'verifyBranchPackage', 'createBranchPackage', 'branchSummary'],
315
+ configTypes: ['MastBranchPackage', 'BranchFilter', 'MastBranchSummary'],
316
+ package: 'recursive-mast',
317
+ keywords: ['branch capsule', 'branch package', 'serialize', 'deserialize', 'verify branch', 'self contained', 'script proof package'],
318
+ description: 'Branch capsule — self-contained MAST script+proof packages that can be serialised, verified, and transferred as a unit',
319
+ },
320
+ {
321
+ template: 'recursive-mast-policy-manifest',
322
+ functions: ['computePolicyPackageHash', 'signPolicyManifest', 'splitPolicyManifest'],
323
+ configTypes: ['RecursiveMastPolicyManifest', 'PolicyAction', 'PolicyRole', 'PolicyEndpoint', 'RestrictedBranchPackage'],
324
+ package: 'recursive-mast',
325
+ keywords: ['policy manifest', 'policy metadata', 'signed policy', 'policy hash', 'policy split', 'discoverable policy'],
326
+ description: 'Policy manifest — signed, discoverable policy metadata with package hashing, signing, and splitting for nested MAST governance structures',
327
+ },
328
+ {
329
+ template: 'recursive-mast-store',
330
+ functions: [],
331
+ configTypes: ['RecursiveMastPolicyStore', 'MirrorResult', 'MemoryPolicyStore', 'MemoryStoreOptions', 'HttpPolicyStore', 'HttpStoreOptions'],
332
+ package: 'recursive-mast',
333
+ keywords: ['policy store', 'memory store', 'http store', 'storage', 'mirror', 'policy persistence', 'policy storage'],
334
+ description: 'Policy store interface with in-memory and HTTP implementations — storage-agnostic persistence for policy trees, proofs, and manifests',
335
+ },
336
+ {
337
+ template: 'recursive-mast-encrypted-branch',
338
+ functions: ['createEncryptedBranch', 'decryptBranch', 'isEncryptedBranch', 'encryptedBranchPublicMetadata'],
339
+ configTypes: ['EncryptedBranchPackage', 'DecryptedBranchResult'],
340
+ package: 'recursive-mast',
341
+ keywords: ['encrypted branch', 'private policy', 'decrypt', 'confidential', 'encrypted mast', 'private script'],
342
+ description: 'Encrypted branch packages — private policy branches with public metadata, encryption, and decryption for confidential MAST structures',
343
+ },
344
+ {
345
+ template: 'recursive-mast-inventory',
346
+ functions: ['computeBranchInventoryHash', 'getCriticalBranches', 'getRecoveryBranches', 'getBranchesByAction', 'getBranchesByRole', 'validateInventoryCoverage'],
347
+ configTypes: ['BranchInventory', 'BranchInventoryEntry'],
348
+ package: 'recursive-mast',
349
+ keywords: ['branch inventory', 'critical branches', 'recovery branches', 'inventory hash', 'coverage validation', 'branch audit'],
350
+ description: 'Branch inventory management — compute inventory hashes, categorize branches by criticality, recovery, action, and role, and validate inventory coverage',
351
+ },
352
+ {
353
+ template: 'recursive-mast-availability',
354
+ functions: ['auditPolicyAvailability', 'createAvailabilityReceipt', 'signAvailabilityReceipt', 'verifyAvailabilityReceipt', 'receiptCoversBranch', 'receiptCoversInventory'],
355
+ configTypes: ['AvailabilityPolicy', 'PolicyAvailabilityReport', 'AuditConfig', 'AvailabilityReceipt'],
356
+ package: 'recursive-mast',
357
+ keywords: ['availability audit', 'data availability', 'availability receipt', 'receipt verification', 'policy availability', 'availability report'],
358
+ description: 'Policy availability auditing and receipts — audit which policies, proofs, and branches are available, issue signed availability receipts, and verify coverage',
359
+ },
360
+ {
361
+ template: 'recursive-mast-content-keys',
362
+ functions: ['policyManifestKey', 'scriptKey', 'proofKey', 'bundleKey', 'parseContentKey', 'computeBundleHash', 'computeScriptHash'],
363
+ configTypes: ['ContentKey'],
364
+ package: 'recursive-mast',
365
+ keywords: ['content key', 'content addressed', 'key scheme', 'bundle hash', 'script hash', 'policy manifest key', 'content addressing'],
366
+ description: 'Content-addressed key scheme for policy artifacts — deterministic key generation for manifests, scripts, proofs, and bundles using SHA3-256',
367
+ },
368
+ ];
369
+ const PACKAGE_TO_TEMPLATES = {};
370
+ for (const entry of exports.TEMPLATE_CATALOG) {
371
+ const pkgs = Array.isArray(entry.package) ? entry.package : entry.package ? [entry.package] : [];
372
+ for (const pkg of pkgs) {
373
+ if (!PACKAGE_TO_TEMPLATES[pkg])
374
+ PACKAGE_TO_TEMPLATES[pkg] = [];
375
+ PACKAGE_TO_TEMPLATES[pkg].push(entry);
376
+ }
377
+ }
378
+ function getTemplatesForPackage(pkgName) {
379
+ return PACKAGE_TO_TEMPLATES[pkgName] || [];
380
+ }
381
+ function searchTemplates(query) {
382
+ const q = query.toLowerCase();
383
+ const scored = [];
384
+ for (const entry of exports.TEMPLATE_CATALOG) {
385
+ let score = 0;
386
+ for (const kw of entry.keywords) {
387
+ if (kw.includes(q) || q.includes(kw))
388
+ score += 3;
389
+ }
390
+ for (const fn of entry.functions) {
391
+ if (fn.toLowerCase().includes(q))
392
+ score += 2;
393
+ }
394
+ if (entry.description.toLowerCase().includes(q))
395
+ score += 1;
396
+ if (entry.template.includes(q))
397
+ score += 2;
398
+ if (score > 0)
399
+ scored.push({ entry, score });
400
+ }
401
+ scored.sort((a, b) => b.score - a.score);
402
+ return scored.map(s => s.entry);
403
+ }
404
+ function getAllTemplates() {
405
+ return exports.TEMPLATE_CATALOG;
406
+ }
package/dist/tools.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleToolCall = handleToolCall;
4
+ const template_catalog_js_1 = require("./template-catalog.js");
4
5
  function handleToolCall(name, args, index) {
5
6
  switch (name) {
6
7
  case 'search-symbol': return searchSymbol(args, index);
@@ -11,6 +12,7 @@ function handleToolCall(name, args, index) {
11
12
  case 'scaffold-package': return scaffoldPackage(args);
12
13
  case 'package-stats': return packageStats(args, index);
13
14
  case 'list-exports': return listExports(args, index);
15
+ case 'suggest-template': return suggestTemplate(args);
14
16
  default: return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };
15
17
  }
16
18
  }
@@ -338,6 +340,40 @@ function scaffoldPackage(args) {
338
340
  }],
339
341
  };
340
342
  }
343
+ function suggestTemplate(args) {
344
+ const usecase = (args.usecase || '').toLowerCase();
345
+ if (!usecase) {
346
+ return { content: [{ type: 'text', text: 'usecase is required — describe what you want to do (e.g. "time-lock funds until a block height")' }], isError: true };
347
+ }
348
+ const results = (0, template_catalog_js_1.searchTemplates)(usecase);
349
+ if (results.length === 0) {
350
+ return { content: [{ type: 'text', text: `No templates found matching '${usecase}'. Try different keywords (e.g. "lock", "vote", "payment", "identity", "state machine").` }] };
351
+ }
352
+ const lines = [`Found ${results.length} template(s) matching '${args.usecase}':`, ''];
353
+ for (const r of results) {
354
+ lines.push(`## ${r.template}`);
355
+ lines.push(`${r.description}`);
356
+ lines.push('');
357
+ lines.push(`**Functions:**`);
358
+ for (const fn of r.functions) {
359
+ lines.push(` - \`import { ${fn} } from '@totemsdk/kissvm'\``);
360
+ }
361
+ if (r.configTypes.length > 0) {
362
+ lines.push('');
363
+ lines.push(`**Config types:**`);
364
+ for (const t of r.configTypes) {
365
+ lines.push(` - \`${t}\``);
366
+ }
367
+ }
368
+ if (r.package) {
369
+ const pkgs = Array.isArray(r.package) ? r.package : [r.package];
370
+ lines.push('');
371
+ lines.push(`**Related package(s):** ${pkgs.map(p => `\`@totemsdk/${p}\``).join(', ')}`);
372
+ }
373
+ lines.push('');
374
+ }
375
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
376
+ }
341
377
  function packageStats(args, index) {
342
378
  const pkgName = args.name;
343
379
  if (!pkgName || !index.packages[pkgName]) {
@@ -348,6 +384,18 @@ function packageStats(args, index) {
348
384
  pkg.exports.classes.length + pkg.exports.interfaces.length + pkg.exports.consts.length;
349
385
  const totemDeps = pkg.dependencies.filter(d => d.startsWith('@totemsdk/'));
350
386
  const externalDeps = pkg.dependencies.filter(d => !d.startsWith('@totemsdk/'));
387
+ const pkgDir = pkg.name.replace('@totemsdk/', '');
388
+ const templates = (0, template_catalog_js_1.getTemplatesForPackage)(pkgDir);
389
+ const templateSection = templates.length > 0
390
+ ? [
391
+ ``,
392
+ `**KISSVM Templates:**`,
393
+ ...templates.flatMap(t => [
394
+ ` - **${t.template}** — ${t.description}`,
395
+ ...t.functions.map(fn => ` - \`import { ${fn} } from '@totemsdk/kissvm'\``),
396
+ ]),
397
+ ]
398
+ : [];
351
399
  return {
352
400
  content: [{
353
401
  type: 'text',
@@ -371,6 +419,7 @@ function packageStats(args, index) {
371
419
  `| Tests | ${pkg.hasTests ? 'Yes' : 'No'} |`,
372
420
  `| @totemsdk/* deps | ${totemDeps.length} |`,
373
421
  `| External deps | ${externalDeps.length} |`,
422
+ ...templateSection,
374
423
  ``,
375
424
  ].join('\n'),
376
425
  }],
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@totemsdk/mcp-server",
3
- "version": "0.1.0",
4
- "description": "MCP server exposing the full Totem SDK package set — metadata, types, exports, dependency graphs, and scaffolding tools for 53 packages",
3
+ "version": "0.2.0",
4
+ "description": "MCP server exposing the full Totem SDK package set — metadata, types, exports, dependency graphs, and scaffolding tools for 55 packages",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "bin": {
@@ -14,18 +14,19 @@
14
14
  "import": "./dist/index.js"
15
15
  }
16
16
  },
17
- "scripts": {
18
- "build": "tsc",
19
- "prepare": "",
20
- "clean": "rm -rf dist",
21
- "start": "node dist/index.js"
22
- },
23
- "files": ["dist", "README.md", "LICENSE"],
17
+ "files": [
18
+ "dist",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
24
22
  "dependencies": {
25
- "@modelcontextprotocol/sdk": "^1.29.0"
23
+ "@modelcontextprotocol/sdk": "^1.30.0"
26
24
  },
27
25
  "devDependencies": {
26
+ "@types/jest": "^30.0.0",
28
27
  "@types/node": "^20.0.0",
28
+ "jest": "^30.4.2",
29
+ "ts-jest": "^29.0.0",
29
30
  "typescript": "^7.0.2"
30
31
  },
31
32
  "engines": {
@@ -38,12 +39,24 @@
38
39
  "author": "Totem SDK",
39
40
  "homepage": "https://totem.ing",
40
41
  "bugs": {
41
- "url": "https://github.com/totem-sdk/totem-sdk/issues"
42
+ "url": "https://github.com/Totem-Edge/totem-sdk/issues"
42
43
  },
43
44
  "repository": {
44
45
  "type": "git",
45
- "url": "git+https://github.com/totem-sdk/totem-sdk.git",
46
- "directory": "packages/totem-sdk/packages/mcp-server"
47
- },
48
- "keywords": ["totem", "totemsdk", "mcp", "model-context-protocol", "sdk-index"]
49
- }
46
+ "url": "git+https://github.com/Totem-Edge/totem-sdk.git",
47
+ "directory": "packages/mcp-server"
48
+ },
49
+ "keywords": [
50
+ "totem",
51
+ "totemsdk",
52
+ "mcp",
53
+ "model-context-protocol",
54
+ "sdk-index"
55
+ ],
56
+ "scripts": {
57
+ "build": "tsc",
58
+ "clean": "rm -rf dist",
59
+ "start": "node dist/index.js",
60
+ "test": "jest"
61
+ }
62
+ }