molecule-mcp 0.0.0-stage → 0.3.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.
@@ -0,0 +1,241 @@
1
+ // GENERATED FILE — DO NOT EDIT.
2
+ //
3
+ // Byte-for-byte copy of `mlcl/src/lib/package-search.ts` (the canonical search
4
+ // owner shared with `mlcl search` and the stdio MCP), made standalone so this
5
+ // package keeps its own build/deploy closure: mcp/Dockerfile builds `mcp/`
6
+ // alone and mcp/scripts/deploy-remote.sh ships only this package, so this file
7
+ // must not import the CLI, oclif, node:fs or any @molecule/* package.
8
+ //
9
+ // Regenerate after ANY edit to the owner:
10
+ // node scripts/generate-mcp-package-search.mjs
11
+ // Drift fails src/lib/__tests__/mcp-search-owner-drift.test.ts.
12
+ /**
13
+ * The package frameworks a project of one app framework can import.
14
+ *
15
+ * Its own, the UI set it renders with (`uiFramework`), and every framework whose
16
+ * identifying runtime the project installs in full. A framework is identified by
17
+ * its `dependencies`, or by its `devDependencies` when it has none (the rule
18
+ * `getAppFrameworkDeps` reads). A framework that renders with another
19
+ * framework's UI set is identified by that set, so its packages are never
20
+ * accepted by runtime alone. So a react-native-web project (react, react-dom,
21
+ * react-router) imports React packages, a react-native one (no react-dom) does
22
+ * not, and a React project does not import react-native-web packages.
23
+ *
24
+ * @param project - The project's framework key (`molecule.framework`).
25
+ * @param appFrameworks - The registry's `appFrameworks`.
26
+ * @returns The accepted package frameworks, the project's own first; just the
27
+ * project's key when the registry does not know it.
28
+ */
29
+ export function frameworksAcceptedBy(project, appFrameworks) {
30
+ const own = appFrameworks[project];
31
+ // The hosted reader passes an unvalidated registry document.
32
+ if (!own || typeof own !== 'object')
33
+ return [project];
34
+ const installed = new Set([
35
+ ...Object.keys(own.dependencies ?? {}),
36
+ ...Object.keys(own.devDependencies ?? {}),
37
+ ]);
38
+ const accepted = [project];
39
+ if (own.uiFramework && own.uiFramework !== project)
40
+ accepted.push(own.uiFramework);
41
+ for (const [key, identifying] of runtimeFrameworks(appFrameworks)) {
42
+ if (accepted.includes(key))
43
+ continue;
44
+ if ([...identifying].every((dep) => installed.has(dep)))
45
+ accepted.push(key);
46
+ }
47
+ return accepted;
48
+ }
49
+ /**
50
+ * The frameworks that are a runtime of their own, each with the dependencies that
51
+ * identify it: its `dependencies`, or its `devDependencies` when it has none (the
52
+ * rule `getAppFrameworkDeps` reads). A framework that renders with another
53
+ * framework's UI set (react-native-web) is not one: it is identified by that set.
54
+ *
55
+ * @param appFrameworks - The registry's `appFrameworks` (unvalidated on the hosted side).
56
+ * @returns Framework key → identifying dependency names, frameworks with none left out.
57
+ */
58
+ function runtimeFrameworks(appFrameworks) {
59
+ const runtimes = [];
60
+ for (const [key, fw] of Object.entries(appFrameworks)) {
61
+ if (!fw || typeof fw !== 'object')
62
+ continue;
63
+ if (fw.uiFramework && fw.uiFramework !== key)
64
+ continue;
65
+ const runtime = Object.keys(fw.dependencies ?? {});
66
+ const identifying = runtime.length > 0 ? runtime : Object.keys(fw.devDependencies ?? {});
67
+ if (identifying.length > 0)
68
+ runtimes.push([key, new Set(identifying)]);
69
+ }
70
+ return runtimes;
71
+ }
72
+ /**
73
+ * The framework a package is written for: its registry `framework`, else the one
74
+ * its `runtimeDependencies` (dependencies and peers, as sync-registry records
75
+ * them) name.
76
+ *
77
+ * A dependency names a framework when it identifies a runtime framework (react,
78
+ * react-dom, vue, solid-js, svelte, …). The package is written for the framework
79
+ * with the fewest identifying dependencies that still has every one the package
80
+ * names: `react` alone is react, `react` with `react-native` is react-native.
81
+ * The registry `framework` covers a package whose dependencies name none, like a
82
+ * bond over `@react-native-clipboard/clipboard`.
83
+ *
84
+ * @param entry - The package's registry entry.
85
+ * @param appFrameworks - The registry's `appFrameworks`.
86
+ * @returns The framework key, or undefined for a framework-neutral package (and for
87
+ * dependencies two frameworks fit equally, which the registry tests refuse).
88
+ */
89
+ export function packageFramework(entry, appFrameworks) {
90
+ if (typeof entry.framework === 'string' && entry.framework)
91
+ return entry.framework;
92
+ // UI frameworks are the app stack's: an API package that peers react (to render an
93
+ // email, say) is not a React binding.
94
+ if (entry.stack === 'api' || !Array.isArray(entry.runtimeDependencies))
95
+ return undefined;
96
+ const runtimes = runtimeFrameworks(appFrameworks);
97
+ const named = entry.runtimeDependencies.filter((dep) => typeof dep === 'string' && runtimes.some(([, identifying]) => identifying.has(dep)));
98
+ if (named.length === 0)
99
+ return undefined;
100
+ const fits = runtimes
101
+ .filter(([, identifying]) => named.every((dep) => identifying.has(dep)))
102
+ .sort((a, b) => a[1].size - b[1].size);
103
+ if (fits.length === 0 || (fits.length > 1 && fits[1][1].size === fits[0][1].size))
104
+ return undefined;
105
+ return fits[0][0];
106
+ }
107
+ /** Result count both `mlcl search` and `search_packages` use when none is given. */
108
+ export const DEFAULT_SEARCH_LIMIT = 20;
109
+ /**
110
+ * The stack a hit reports. A declared stack wins; a legacy/malformed entry
111
+ * falls back to the package-name convention (the same rule both readers used
112
+ * before the contract was shared).
113
+ *
114
+ * @param entry - A registry-shaped package.
115
+ * @returns The stack to report on the hit.
116
+ */
117
+ function resolveStack(entry) {
118
+ return entry.stack ?? (entry.name.includes('/app-') ? 'app' : 'api');
119
+ }
120
+ /**
121
+ * Score a package against the query tokens. Higher = more relevant.
122
+ * Exact names, exported symbols and complete capability phrases outrank
123
+ * incidental name substrings ("form" in "formula"). The existing token scores
124
+ * remain useful for partial package names and broad category/provider queries.
125
+ *
126
+ * @param entry - A registry-shaped package.
127
+ * @param q - Package name, exported symbol or natural capability query.
128
+ * @returns Relevance score; zero means no match.
129
+ */
130
+ export function scoreSearchEntry(entry, q) {
131
+ const name = entry.name.replace('@molecule/', '');
132
+ const tokens = q.toLowerCase().split(/\s+/).filter(Boolean);
133
+ if (tokens.length === 0)
134
+ return 0;
135
+ let score = 0;
136
+ const phrase = (value) => value
137
+ .toLowerCase()
138
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
139
+ .trim();
140
+ const query = phrase(q);
141
+ const symbolQuery = q.trim().replace(/\(\)$/, '').toLowerCase();
142
+ // The hosted server scores an unvalidated document, so `exports` may not be
143
+ // the string[] the registry contract says: treat anything else as no export
144
+ // list rather than throwing inside the tool handler.
145
+ const exportsList = Array.isArray(entry.exports) ? entry.exports : [];
146
+ const exactSymbol = /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(symbolQuery) &&
147
+ exportsList.some((symbol) => typeof symbol === 'string' && symbol.toLowerCase() === symbolQuery);
148
+ if (!query && !exactSymbol)
149
+ return 0;
150
+ const containsPhrase = (text, candidate) => ` ${text} `.includes(` ${candidate} `);
151
+ const hints = (entry.intentHints ?? []).map(phrase);
152
+ if (q.trim().toLowerCase() === entry.name.toLowerCase() ||
153
+ q.trim().toLowerCase() === name.toLowerCase()) {
154
+ score += 400;
155
+ }
156
+ // Match the WHOLE symbol, never its prefix/substring; e.g. "use" must not
157
+ // match every hook, and "useProfileFormState" must not match useProfileForm.
158
+ if (exactSymbol)
159
+ score += 160;
160
+ // A short query can name both a category and a common export (e.g. query).
161
+ // Keep that category and its providers ahead of unrelated symbol owners.
162
+ if (entry.category && phrase(entry.category) === query)
163
+ score += 160;
164
+ if (query.includes(' ')) {
165
+ if (hints.includes(query))
166
+ score += 120;
167
+ else if (hints.some((hint) => hint.includes(' ') && (containsPhrase(query, hint) || containsPhrase(hint, query))))
168
+ score += 80;
169
+ else if ([name, entry.category, entry.label, entry.description].some((field) => field && containsPhrase(phrase(field), query)))
170
+ score += 60;
171
+ }
172
+ for (const tok of tokens) {
173
+ if (name === tok)
174
+ score += 40;
175
+ else if (name.includes(tok))
176
+ score += 20;
177
+ if (entry.category?.includes(tok))
178
+ score += 8;
179
+ if (entry.intentHints?.some((h) => h.includes(tok) || tok.includes(h)))
180
+ score += 6;
181
+ if (entry.description?.toLowerCase().includes(tok))
182
+ score += 3;
183
+ if (entry.label?.toLowerCase().includes(tok))
184
+ score += 3;
185
+ }
186
+ return score;
187
+ }
188
+ /**
189
+ * Rank a registry into the shared discovery DTO.
190
+ *
191
+ * The stack filter is applied to the SOURCE entries first — before any scoring,
192
+ * sorting or truncation — because the limit window is otherwise claimed by the
193
+ * highest-scoring packages of BOTH stacks and a stack-restricted caller can be
194
+ * left with none of its own.
195
+ *
196
+ * @param entries - Registry-shaped packages, from either reader.
197
+ * @param query - Package name, exported symbol or natural capability query.
198
+ * @param options - Optional stack and framework restrictions and result limit.
199
+ * @returns Ranked hits (score stripped), at most `limit` of them.
200
+ */
201
+ export function searchPackages(entries, query, options = {}) {
202
+ const { stack, framework, appFrameworks, limit = DEFAULT_SEARCH_LIMIT } = options;
203
+ const accepted = framework
204
+ ? new Set(appFrameworks ? frameworksAcceptedBy(framework, appFrameworks) : [framework])
205
+ : null;
206
+ const ranked = [];
207
+ for (const entry of entries) {
208
+ // The rule `loadRegistry(stack)` applies — declared stack equality — kept
209
+ // here so the transport that has no loader (hosted MCP) filters identically.
210
+ if (stack && entry.stack !== stack)
211
+ continue;
212
+ if (accepted) {
213
+ const written = appFrameworks
214
+ ? packageFramework(entry, appFrameworks)
215
+ : typeof entry.framework === 'string'
216
+ ? entry.framework
217
+ : undefined;
218
+ if (written && !accepted.has(written))
219
+ continue;
220
+ }
221
+ const score = scoreSearchEntry(entry, query);
222
+ if (score <= 0)
223
+ continue;
224
+ const configuration = Array.isArray(entry.decisionGuide?.configuration)
225
+ ? entry.decisionGuide.configuration.filter((line) => typeof line === 'string' && line.length > 0)
226
+ : [];
227
+ ranked.push({
228
+ name: entry.name,
229
+ stack: resolveStack(entry),
230
+ category: entry.category ?? '',
231
+ label: entry.label ?? entry.name,
232
+ description: entry.description ?? '',
233
+ ...(configuration.length > 0 ? { configuration } : {}),
234
+ score,
235
+ });
236
+ }
237
+ return ranked
238
+ .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))
239
+ .slice(0, limit)
240
+ .map(({ score: _score, ...hit }) => hit);
241
+ }
@@ -0,0 +1,85 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ /**
3
+ * Bound on every outbound fetch this server makes (the mlcl repo's
4
+ * registry/templates and the npm registry's package metadata). Node's undici
5
+ * defaults let an upstream that accepts and then stalls hold the call — and
6
+ * with it the client's whole HTTP request — for ~5 minutes; a hung
7
+ * raw.githubusercontent.com must fail the tool call in seconds instead. The
8
+ * failure is the caller's to surface: a timed-out fetch leaves the cache
9
+ * untouched, so the next call retries the network (and a stale entry keeps
10
+ * serving until its TTL, never a failed one).
11
+ */
12
+ export declare const FETCH_TIMEOUT_MS = 15000;
13
+ /** Cached packages kept before the least-recently-used entry is evicted (see the cap logic below). */
14
+ export declare const README_CACHE_LIMIT = 50;
15
+ /**
16
+ * Drop every cached registry/templates payload and package README.
17
+ *
18
+ * Both maps are process-global ON PURPOSE — a long-lived hosted server pays one
19
+ * outbound fetch per document per TTL window instead of one per call — which
20
+ * also means the state survives between callers in one process, INCLUDING
21
+ * between the tests that point `MOLECULE_REGISTRY_FILE` at a rewritten file and
22
+ * then assert the new bytes are what the tool read. Those suites have to say
23
+ * that reset out loud rather than depend on the order they happen to run in, so
24
+ * this is the reset they call (the same affordance `clearRegistryCache` gives
25
+ * mlcl's own registry.ts, for the same reason).
26
+ */
27
+ export declare function clearRemoteCaches(): void;
28
+ /**
29
+ * Fetch a package's published README from the npm registry, cached per package.
30
+ *
31
+ * The network branch is bounded by {@link FETCH_TIMEOUT_MS} (`timeoutMs`
32
+ * shortens it for tests, like {@link fetchJson}). A fetched body with no
33
+ * `readme` resolves to `undefined`; a rejected, aborted, or non-2xx fetch
34
+ * REJECTS, the same as {@link fetchJson} — the caller's own try/catch is the
35
+ * fallback (see the `read_package_doc` handler). Neither case caches anything,
36
+ * so the next call retries the network. Callers that arrive while this
37
+ * package's fetch is already in flight share that one request instead of
38
+ * starting another (see {@link inFlight}).
39
+ *
40
+ * @param short - Package name WITHOUT the `@molecule/` scope.
41
+ * @param timeoutMs - Abort bound for the outbound fetch.
42
+ * @returns The published README, or undefined when the registry has none.
43
+ */
44
+ export declare function fetchPackageReadme(short: string, timeoutMs?: number): Promise<string | undefined>;
45
+ /**
46
+ * A predicate a fetched payload must satisfy before it is handed to the caller
47
+ * as the shape that caller declared, or cached as one.
48
+ */
49
+ export type PayloadCheck = (data: unknown) => boolean;
50
+ /** Whether a payload is the package registry: an object carrying a `packages` object. */
51
+ export declare function isRegistryPayload(data: unknown): boolean;
52
+ /** Whether a payload is the templates index: an object carrying a `templates` object. */
53
+ export declare function isTemplatesPayload(data: unknown): boolean;
54
+ /**
55
+ * Fetch (and cache) the registry/templates JSON, or read it from a local file.
56
+ *
57
+ * The network branch is bounded by {@link FETCH_TIMEOUT_MS}; `timeoutMs`
58
+ * shortens that bound — the timeout regression test drives a never-responding
59
+ * local server through it with a 250 ms bound, well inside vitest's own 5 s
60
+ * default test timeout. The 15 s default would outlast that timeout, so the
61
+ * case could never pass without the seam.
62
+ * A failed (timed-out, rejected, non-2xx, or unrecognized) fetch throws without
63
+ * touching the cache, so the next call retries the network.
64
+ *
65
+ * `check` is what makes "recognized" mean anything. A 2xx (like a readable
66
+ * local file) proves only that bytes ARRIVED: `{"version":1}`, a proxy's
67
+ * 200 error page, a shrunken rewrite of the registry — each deserializes as
68
+ * happily as the real document and was then handed out as the caller's
69
+ * declared type and cached. The first reader of the missing section threw a
70
+ * bare `TypeError` from inside a tool handler (`search_packages` died on
71
+ * `Object.entries(undefined)`, reporting "Cannot convert undefined or null to
72
+ * object" to the client), and every call for the next 10 minutes was served
73
+ * the same non-payload. A payload that fails `check` is reported as the
74
+ * failure it is and caches nothing, exactly like a non-2xx answer. Callers that
75
+ * arrive while the same document is already being fetched share that one
76
+ * request instead of starting another (see {@link inFlight}).
77
+ *
78
+ * The check is the CALLER's, and it is re-applied to whatever the shortcuts
79
+ * hand over: a cache hit or a shared in-flight answer was validated by the
80
+ * FIRST reader's check, and the key is the document's SOURCE (url or file), not
81
+ * its shape — a second reader declaring a different shape for one source must
82
+ * not be handed a payload its own check refuses.
83
+ */
84
+ export declare function fetchJson<T>(url: string, file?: string, timeoutMs?: number, check?: PayloadCheck): Promise<T>;
85
+ export declare function buildRemoteServer(): McpServer;