claudepluginhub 0.16.0 → 0.17.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.
Files changed (55) hide show
  1. package/README.md +34 -1
  2. package/dist/args.js +0 -6
  3. package/dist/collection-install.d.ts +4 -23
  4. package/dist/collection-install.js +9 -45
  5. package/dist/component-install.js +8 -27
  6. package/dist/detect.d.ts +0 -2
  7. package/dist/detect.js +3 -7
  8. package/dist/doctor/claude-source.d.ts +4 -6
  9. package/dist/doctor/claude-source.js +1 -2
  10. package/dist/doctor/color.d.ts +0 -1
  11. package/dist/doctor/color.js +0 -1
  12. package/dist/doctor/equivalence.d.ts +1 -1
  13. package/dist/doctor/equivalence.js +68 -149
  14. package/dist/doctor/estimate.js +12 -61
  15. package/dist/doctor/html-report.d.ts +1 -6
  16. package/dist/doctor/html-report.js +43 -116
  17. package/dist/doctor/inventory.d.ts +10 -24
  18. package/dist/doctor/inventory.js +29 -63
  19. package/dist/doctor/overlap.d.ts +3 -6
  20. package/dist/doctor/render.js +20 -38
  21. package/dist/doctor/report.d.ts +7 -16
  22. package/dist/doctor/report.js +3 -6
  23. package/dist/doctor/rules.d.ts +6 -16
  24. package/dist/doctor/rules.js +13 -26
  25. package/dist/doctor/run.d.ts +1 -1
  26. package/dist/doctor/run.js +5 -6
  27. package/dist/doctor/sanitize.d.ts +0 -8
  28. package/dist/doctor/sanitize.js +1 -6
  29. package/dist/doctor/select.d.ts +10 -25
  30. package/dist/doctor/select.js +2 -3
  31. package/dist/download.d.ts +4 -0
  32. package/dist/download.js +12 -18
  33. package/dist/fetch.d.ts +4 -8
  34. package/dist/fetch.js +13 -19
  35. package/dist/github-install.js +1 -12
  36. package/dist/index.js +14 -22
  37. package/dist/install.js +1 -2
  38. package/dist/mcp/server.d.ts +25 -0
  39. package/dist/mcp/server.js +103 -0
  40. package/dist/mcp/tools.d.ts +73 -0
  41. package/dist/mcp/tools.js +231 -0
  42. package/dist/output.d.ts +0 -5
  43. package/dist/output.js +0 -12
  44. package/dist/prompts.d.ts +3 -10
  45. package/dist/prompts.js +5 -20
  46. package/dist/recommend.d.ts +54 -56
  47. package/dist/recommend.js +69 -127
  48. package/dist/remove.d.ts +1 -1
  49. package/dist/remove.js +5 -10
  50. package/dist/update.js +5 -8
  51. package/dist/validation.d.ts +0 -5
  52. package/dist/validation.js +3 -10
  53. package/dist/wrapper.d.ts +0 -1
  54. package/dist/wrapper.js +1 -8
  55. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { runInstall } from './install.js';
5
5
  import { runUpdate } from './update.js';
6
6
  import { runRemove, runDirectRemove } from './remove.js';
7
7
  import { runList } from './list.js';
8
- import { isOwnerRepo } from './detect.js';
8
+ import { isOwnerRepo } from './validation.js';
9
9
  import { runGithubInstall, runGithubRemove } from './github-install.js';
10
10
  import { findWrapperScopes } from './wrapper.js';
11
11
  import { findDirectInstallScopes } from './scope-detect.js';
@@ -31,6 +31,8 @@ Commands:
31
31
  recommend Recommend plugins for the current project
32
32
  doctor Diagnose the Claude Code plugin setup (read-only,
33
33
  offline; see \`doctor --help\`)
34
+ mcp Run as an MCP server for Claude Code (stdio):
35
+ claude mcp add claudepluginhub -- npx -y claudepluginhub mcp
34
36
 
35
37
  Identifiers:
36
38
  owner/repo GitHub plugin or marketplace (via Claude Code)
@@ -77,14 +79,19 @@ Options:
77
79
  }
78
80
  async function main() {
79
81
  const args = process.argv.slice(2);
80
- // doctor owns its full flag parsing (incl. `--scope all`, which the global
81
- // parseArgs rejects, and its own --help) — route it before the global help
82
- // intercept and parseArgs. It also owns its banner and exit codes (0/1/2).
82
+ // doctor owns its flags (incl. `--scope all`, which parseArgs rejects), help,
83
+ // banner and exit codes, so it must route before the global help and parseArgs.
83
84
  if (args[0] === 'doctor') {
84
85
  const { runDoctor } = await import('./doctor/run.js');
85
86
  await runDoctor(args.slice(1));
86
87
  return;
87
88
  }
89
+ // stdout belongs to the MCP protocol: no banner, nothing printed before the server starts.
90
+ if (args[0] === 'mcp') {
91
+ const { runMcpServer } = await import('./mcp/server.js');
92
+ runMcpServer();
93
+ return;
94
+ }
88
95
  if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
89
96
  printBanner();
90
97
  printUsage();
@@ -101,7 +108,6 @@ async function main() {
101
108
  process.exit(0);
102
109
  }
103
110
  printBanner();
104
- // Handle non-install commands
105
111
  if (command === 'list') {
106
112
  runList();
107
113
  process.exit(0);
@@ -116,7 +122,6 @@ async function main() {
116
122
  process.exit(1);
117
123
  }
118
124
  if (isOwnerRepo(identifier)) {
119
- // Scope-aware remove: check both direct installs and wrapper installs
120
125
  const directScopes = findDirectInstallScopes(identifier);
121
126
  const wrapperScopes = findWrapperScopes(identifier);
122
127
  const allMatches = [
@@ -126,24 +131,21 @@ async function main() {
126
131
  const filtered = scopeOverride
127
132
  ? allMatches.filter((m) => m.scope === scopeOverride)
128
133
  : allMatches;
129
- // Case 1: Nothing found anywhere → fall back for marketplace guidance
134
+ // Nothing found: runGithubRemove prints the marketplace guidance.
130
135
  if (allMatches.length === 0) {
131
136
  await runGithubRemove(identifier, scopeOverride);
132
137
  process.exit(0);
133
138
  }
134
- // Case 2: Found in other scopes but not the requested one
135
139
  if (filtered.length === 0) {
136
140
  const scopeList = [...new Set(allMatches.map((m) => m.scope))].join(', ');
137
141
  printError(`"${identifier}" not found in ${scopeOverride} scope (found in: ${scopeList})`);
138
142
  process.exit(1);
139
143
  }
140
- // Case 3: Multiple scopes without --scope
141
144
  const uniqueScopes = [...new Set(filtered.map((m) => m.scope))];
142
145
  if (uniqueScopes.length > 1) {
143
146
  printError(`"${identifier}" found in multiple scopes: ${uniqueScopes.join(', ')}. Use --scope to specify.`);
144
147
  process.exit(1);
145
148
  }
146
- // Case 4: Single scope — remove all matching kinds
147
149
  const targetScope = uniqueScopes[0];
148
150
  if (filtered.some((m) => m.kind === 'direct')) {
149
151
  await runDirectRemove(identifier, targetScope);
@@ -167,23 +169,19 @@ async function main() {
167
169
  await runRemove(identifier);
168
170
  process.exit(0);
169
171
  }
170
- // Install flow
171
172
  if (!identifier) {
172
173
  printUsage();
173
174
  process.exit(1);
174
175
  }
175
- // Direct component install: owner/repo + --skill/--command/--agent
176
176
  if (componentFlag && isOwnerRepo(identifier)) {
177
177
  const { runDirectComponentInstall } = await import('./component-install.js');
178
178
  await runDirectComponentInstall(identifier, componentFlag.type, componentFlag.repoPath, componentFlag.pluginPath, yes, scopeOverride);
179
179
  process.exit(0);
180
180
  }
181
- // owner/repo → native Claude Code install
182
181
  if (isOwnerRepo(identifier)) {
183
182
  await runGithubInstall(identifier, yes, scopeOverride, plugin);
184
183
  process.exit(0);
185
184
  }
186
- // Resolve identifier to API URL
187
185
  const url = resolveMarketplaceUrl(identifier);
188
186
  if (!url) {
189
187
  printError(`Invalid identifier: ${identifier}`);
@@ -191,23 +189,21 @@ async function main() {
191
189
  print(`Expected: owner/repo, u/<userId>/<slug>, c/<userId>/<slug>, p/<slug>, or a claudepluginhub.com URL`);
192
190
  process.exit(1);
193
191
  }
194
- // Plugin collections reference whole plugins — install via native delegation
192
+ // Collections and wrapper marketplaces reference whole plugins, so they
193
+ // install via native delegation rather than the component downloader.
195
194
  if (isCollectionUrl(url)) {
196
195
  const { runCollectionInstall } = await import('./collection-install.js');
197
196
  await runCollectionInstall(url, yes, scopeOverride);
198
197
  process.exit(0);
199
198
  }
200
- // Single-plugin wrapper marketplaces likewise install via native delegation
201
199
  if (isPluginWrapperUrl(url)) {
202
200
  const { runWrapperPluginInstall } = await import('./collection-install.js');
203
201
  await runWrapperPluginInstall(url, yes, scopeOverride);
204
202
  process.exit(0);
205
203
  }
206
- // Derive the collection identifier from the input
207
204
  const collectionId = identifier.startsWith('http')
208
205
  ? extractIdentifierFromUrl(identifier)
209
206
  : identifier;
210
- // Fetch manifest
211
207
  printStep('Fetching collection...');
212
208
  const manifest = await fetchMarketplace(url);
213
209
  if (!manifest) {
@@ -219,7 +215,6 @@ async function main() {
219
215
  printError('No components found in this collection.');
220
216
  process.exit(0);
221
217
  }
222
- // Component selection (interactive)
223
218
  let selectedComponents = allComponents;
224
219
  if (!yes && allComponents.length > 1) {
225
220
  print('');
@@ -239,7 +234,6 @@ async function main() {
239
234
  process.exit(0);
240
235
  }
241
236
  }
242
- // Scope selection
243
237
  let scope = scopeOverride ?? 'project';
244
238
  if (!yes && !scopeOverride) {
245
239
  print('');
@@ -250,7 +244,6 @@ async function main() {
250
244
  }
251
245
  scope = chosenScope;
252
246
  }
253
- // Safety warning for hooks/mcp/lsp
254
247
  const hasUnsafe = selectedComponents.some((c) => c.type === 'hook' || c.type === 'mcp' || c.type === 'lsp');
255
248
  if (hasUnsafe) {
256
249
  print('');
@@ -269,7 +262,6 @@ async function main() {
269
262
  await runInstall(collectionId, url, selectedComponents, scope);
270
263
  }
271
264
  function extractIdentifierFromUrl(url) {
272
- // Extract u/<userId>/<slug> from URL path
273
265
  const match = url.match(/\/api\/user-plugins\/([^/]+)\/([^/]+)/);
274
266
  if (match) {
275
267
  return `u/${match[1]}/${match[2]}`;
package/dist/install.js CHANGED
@@ -2,7 +2,6 @@ import { installComponent } from './download.js';
2
2
  import { readLock, writeLock, addCollection, componentKey } from './lock.js';
3
3
  import { print, printStep, printSuccess, printFail, printError, BOLD, RESET, DIM, GREEN, } from './output.js';
4
4
  export async function runInstall(identifier, apiUrl, components, scope) {
5
- // Check if already installed
6
5
  const lock = readLock(scope);
7
6
  if (lock.collections[identifier]) {
8
7
  printError(`Collection "${identifier}" is already installed.`);
@@ -32,7 +31,7 @@ export async function runInstall(identifier, apiUrl, components, scope) {
32
31
  printFail(`${component.componentName} (${component.type})`, 'download failed');
33
32
  }
34
33
  }
35
- // Write lock file (even for partial success)
34
+ // Partial success still records what was installed.
36
35
  if (succeeded > 0) {
37
36
  addCollection(lock, identifier, apiUrl, scope, installed);
38
37
  writeLock(scope, lock);
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Zero-dependency MCP server over stdio: newline-delimited JSON-RPC 2.0. stdout carries protocol
3
+ * messages only; anything else (including a stray console.log from reused CLI code) goes to stderr.
4
+ */
5
+ /** Newest first; an unsupported client version gets our newest, per the spec's negotiation. */
6
+ export declare const SUPPORTED_PROTOCOL_VERSIONS: string[];
7
+ type Id = string | number | null;
8
+ type JsonRpcResponse = {
9
+ jsonrpc: '2.0';
10
+ id: Id;
11
+ result: unknown;
12
+ } | {
13
+ jsonrpc: '2.0';
14
+ id: Id;
15
+ error: {
16
+ code: number;
17
+ message: string;
18
+ };
19
+ };
20
+ /** Handles one parsed message. Returns null for notifications, which never get a response. */
21
+ export declare function handleMessage(message: unknown): Promise<JsonRpcResponse | null>;
22
+ /** Handles one raw stdin line. Returns the serialized response, or null when there is none. */
23
+ export declare function handleLine(line: string): Promise<string | null>;
24
+ export declare function runMcpServer(): void;
25
+ export {};
@@ -0,0 +1,103 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { createRequire } from 'node:module';
3
+ import { TOOL_DEFINITIONS, callTool, hasTool } from './tools.js';
4
+ /**
5
+ * Zero-dependency MCP server over stdio: newline-delimited JSON-RPC 2.0. stdout carries protocol
6
+ * messages only; anything else (including a stray console.log from reused CLI code) goes to stderr.
7
+ */
8
+ /** Newest first; an unsupported client version gets our newest, per the spec's negotiation. */
9
+ export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
10
+ const PARSE_ERROR = -32700;
11
+ const INVALID_REQUEST = -32600;
12
+ const METHOD_NOT_FOUND = -32601;
13
+ const INVALID_PARAMS = -32602;
14
+ const INTERNAL_ERROR = -32603;
15
+ const packageVersion = createRequire(import.meta.url)('../../package.json').version;
16
+ const result = (id, value) => ({ jsonrpc: '2.0', id, result: value });
17
+ const error = (id, code, message) => ({
18
+ jsonrpc: '2.0',
19
+ id,
20
+ error: { code, message },
21
+ });
22
+ function isObject(value) {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ }
25
+ /** Handles one parsed message. Returns null for notifications, which never get a response. */
26
+ export async function handleMessage(message) {
27
+ if (!isObject(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
28
+ const id = isObject(message) && (typeof message.id === 'string' || typeof message.id === 'number') ? message.id : null;
29
+ return error(id, INVALID_REQUEST, 'Invalid Request');
30
+ }
31
+ if (!('id' in message))
32
+ return null; // notification (initialized, cancelled, ...)
33
+ const { id, method } = message;
34
+ if (typeof id !== 'string' && typeof id !== 'number')
35
+ return error(null, INVALID_REQUEST, 'Invalid Request');
36
+ const params = isObject(message.params) ? message.params : {};
37
+ switch (method) {
38
+ case 'initialize': {
39
+ const requested = params.protocolVersion;
40
+ const protocolVersion = typeof requested === 'string' && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
41
+ ? requested
42
+ : SUPPORTED_PROTOCOL_VERSIONS[0];
43
+ return result(id, {
44
+ protocolVersion,
45
+ capabilities: { tools: {} },
46
+ serverInfo: { name: 'claudepluginhub', version: packageVersion },
47
+ });
48
+ }
49
+ case 'ping':
50
+ return result(id, {});
51
+ case 'tools/list':
52
+ return result(id, { tools: TOOL_DEFINITIONS });
53
+ case 'tools/call': {
54
+ const name = params.name;
55
+ if (typeof name !== 'string' || !hasTool(name)) {
56
+ return error(id, INVALID_PARAMS, `Unknown tool: ${String(name)}`);
57
+ }
58
+ if (params.arguments !== undefined && !isObject(params.arguments)) {
59
+ return error(id, INVALID_PARAMS, 'Tool arguments must be an object');
60
+ }
61
+ return result(id, await callTool(name, params.arguments ?? {}));
62
+ }
63
+ default:
64
+ return error(id, METHOD_NOT_FOUND, `Method not found: ${method}`);
65
+ }
66
+ }
67
+ /** Handles one raw stdin line. Returns the serialized response, or null when there is none. */
68
+ export async function handleLine(line) {
69
+ if (line.trim() === '')
70
+ return null;
71
+ let message;
72
+ try {
73
+ message = JSON.parse(line);
74
+ }
75
+ catch {
76
+ return JSON.stringify(error(null, PARSE_ERROR, 'Parse error'));
77
+ }
78
+ let response;
79
+ try {
80
+ response = await handleMessage(message);
81
+ }
82
+ catch (err) {
83
+ const id = isObject(message) && (typeof message.id === 'string' || typeof message.id === 'number') ? message.id : null;
84
+ process.stderr.write(`[claudepluginhub mcp] ${err.stack ?? String(err)}\n`);
85
+ response = error(id, INTERNAL_ERROR, 'Internal error');
86
+ }
87
+ return response ? JSON.stringify(response) : null;
88
+ }
89
+ export function runMcpServer() {
90
+ // Reused CLI modules print with console.log; stdout must stay protocol-only.
91
+ console.log = console.error;
92
+ console.info = console.error;
93
+ // The client closing stdio mid-response raises EPIPE on stdout; exit instead of crashing.
94
+ process.stdout.on('error', () => process.exit(0));
95
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
96
+ rl.on('line', (line) => {
97
+ // Requests run concurrently; each response is written whole, on one line.
98
+ void handleLine(line).then((out) => {
99
+ if (out !== null)
100
+ process.stdout.write(`${out}\n`);
101
+ });
102
+ });
103
+ }
@@ -0,0 +1,73 @@
1
+ export declare const TOOL_DEFINITIONS: readonly [{
2
+ readonly name: "search_plugins";
3
+ readonly description: "Search Claude Code plugins on ClaudePluginHub";
4
+ readonly inputSchema: {
5
+ readonly type: "object";
6
+ readonly properties: {
7
+ readonly query: {
8
+ readonly type: "string";
9
+ };
10
+ readonly type: {
11
+ readonly type: "string";
12
+ readonly enum: string[];
13
+ };
14
+ readonly maxTokens: {
15
+ readonly type: "integer";
16
+ readonly description: "Max always-on tokens";
17
+ };
18
+ readonly noHooks: {
19
+ readonly type: "boolean";
20
+ };
21
+ readonly limit: {
22
+ readonly type: "integer";
23
+ readonly maximum: 10;
24
+ };
25
+ };
26
+ readonly required: readonly ["query"];
27
+ };
28
+ }, {
29
+ readonly name: "inspect_plugin";
30
+ readonly description: "Plugin details: components, always-on tokens, code it runs, install command";
31
+ readonly inputSchema: {
32
+ readonly type: "object";
33
+ readonly properties: {
34
+ readonly slug: {
35
+ readonly type: "string";
36
+ };
37
+ };
38
+ readonly required: readonly ["slug"];
39
+ };
40
+ }, {
41
+ readonly name: "recommend_for_project";
42
+ readonly description: "Recommend plugins for a project's stack";
43
+ readonly inputSchema: {
44
+ readonly type: "object";
45
+ readonly properties: {
46
+ readonly projectDir: {
47
+ type: string;
48
+ };
49
+ };
50
+ };
51
+ }, {
52
+ readonly name: "doctor_setup";
53
+ readonly description: "Offline health check of installed plugins";
54
+ readonly inputSchema: {
55
+ readonly type: "object";
56
+ readonly properties: {
57
+ readonly projectDir: {
58
+ type: string;
59
+ };
60
+ };
61
+ };
62
+ }];
63
+ export type ToolResult = {
64
+ content: Array<{
65
+ type: 'text';
66
+ text: string;
67
+ }>;
68
+ isError?: true;
69
+ };
70
+ type Args = Record<string, unknown>;
71
+ export declare function hasTool(name: string): boolean;
72
+ export declare function callTool(name: string, args: Args): Promise<ToolResult>;
73
+ export {};
@@ -0,0 +1,231 @@
1
+ import { resolve } from 'node:path';
2
+ import { BASE_URL } from '../fetch.js';
3
+ import { DEFAULT_LIMIT as RECOMMEND_LIMIT, collectProjectSignals, fetchRecommendations } from '../recommend.js';
4
+ import { probeClaude } from '../doctor/claude-source.js';
5
+ import { canonicalize } from '../doctor/paths.js';
6
+ import { createScanner } from '../doctor/inventory.js';
7
+ import { buildDoctorReport } from '../doctor/run.js';
8
+ /**
9
+ * The four MCP tools. Definitions are deliberately terse: every byte here is sent to the model
10
+ * in every session that has the server enabled (budget enforced by mcp-server.test.ts).
11
+ */
12
+ /** Canonical host for links shown to users (the apex 308s to www). */
13
+ const SITE = 'https://www.claudepluginhub.com';
14
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
15
+ const MAX_LIMIT = 10;
16
+ const DEFAULT_LIMIT = 5;
17
+ /** Component-type filter → `/api/plugins` boolean query flag. */
18
+ const TYPE_FLAGS = {
19
+ skill: 'skills',
20
+ agent: 'agents',
21
+ command: 'commands',
22
+ hook: 'hooks',
23
+ mcp: 'mcp',
24
+ outputStyle: 'outputStyles',
25
+ theme: 'themes',
26
+ monitor: 'monitors',
27
+ workflow: 'workflows',
28
+ };
29
+ /** Omitted → the server's cwd, which Claude Code sets to the project root. */
30
+ const projectDir = { type: 'string' };
31
+ export const TOOL_DEFINITIONS = [
32
+ {
33
+ name: 'search_plugins',
34
+ description: 'Search Claude Code plugins on ClaudePluginHub',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: {
38
+ query: { type: 'string' },
39
+ type: { type: 'string', enum: Object.keys(TYPE_FLAGS) },
40
+ maxTokens: { type: 'integer', description: 'Max always-on tokens' },
41
+ noHooks: { type: 'boolean' },
42
+ limit: { type: 'integer', maximum: MAX_LIMIT },
43
+ },
44
+ required: ['query'],
45
+ },
46
+ },
47
+ {
48
+ name: 'inspect_plugin',
49
+ description: 'Plugin details: components, always-on tokens, code it runs, install command',
50
+ inputSchema: { type: 'object', properties: { slug: { type: 'string' } }, required: ['slug'] },
51
+ },
52
+ {
53
+ name: 'recommend_for_project',
54
+ description: "Recommend plugins for a project's stack",
55
+ inputSchema: { type: 'object', properties: { projectDir } },
56
+ },
57
+ {
58
+ name: 'doctor_setup',
59
+ description: 'Offline health check of installed plugins',
60
+ inputSchema: { type: 'object', properties: { projectDir } },
61
+ },
62
+ ];
63
+ const ok = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value) }] });
64
+ function optionalString(args, key) {
65
+ const value = args[key];
66
+ if (value === undefined)
67
+ return undefined;
68
+ if (typeof value !== 'string' || value.trim() === '')
69
+ throw new Error(`"${key}" must be a non-empty string`);
70
+ return value.trim();
71
+ }
72
+ function optionalInt(args, key, min, max) {
73
+ const value = args[key];
74
+ if (value === undefined)
75
+ return undefined;
76
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
77
+ throw new Error(`"${key}" must be an integer ${min}-${max}`);
78
+ }
79
+ return value;
80
+ }
81
+ async function getJson(url, notFound) {
82
+ let res;
83
+ try {
84
+ res = await fetch(url, { signal: AbortSignal.timeout(15_000) });
85
+ }
86
+ catch (err) {
87
+ throw new Error(`Network error: ${err.message}`);
88
+ }
89
+ if (res.status === 404)
90
+ throw new Error(notFound);
91
+ if (res.status === 429)
92
+ throw new Error('Rate limit exceeded. Try again in a few minutes.');
93
+ if (!res.ok)
94
+ throw new Error(`ClaudePluginHub returned HTTP ${res.status}`);
95
+ return res.json();
96
+ }
97
+ async function searchPlugins(args) {
98
+ const query = optionalString(args, 'query');
99
+ if (!query)
100
+ throw new Error('"query" is required');
101
+ const type = optionalString(args, 'type');
102
+ if (type !== undefined && !TYPE_FLAGS[type]) {
103
+ throw new Error(`"type" must be one of: ${Object.keys(TYPE_FLAGS).join(', ')}`);
104
+ }
105
+ const maxTokens = optionalInt(args, 'maxTokens', 0, Number.MAX_SAFE_INTEGER);
106
+ const limit = optionalInt(args, 'limit', 1, MAX_LIMIT) ?? DEFAULT_LIMIT;
107
+ if (args.noHooks !== undefined && typeof args.noHooks !== 'boolean')
108
+ throw new Error('"noHooks" must be a boolean');
109
+ const noHooks = args.noHooks === true;
110
+ // The free directory search the /plugins page uses — not Premium Power Search.
111
+ const url = new URL(`${BASE_URL}/api/plugins`);
112
+ url.searchParams.set('q', query.slice(0, 500));
113
+ if (type)
114
+ url.searchParams.set(TYPE_FLAGS[type], 'true');
115
+ const body = (await getJson(url.toString(), 'Search endpoint not found'));
116
+ if (!Array.isArray(body.items))
117
+ throw new Error('Unexpected response from ClaudePluginHub');
118
+ const results = body.items
119
+ .filter((p) => !noHooks || p.currentVersion?.hasHooksDetail !== true)
120
+ // An unknown estimate can't satisfy a token ceiling.
121
+ .filter((p) => maxTokens === undefined || (typeof p.alwaysOnTokens === 'number' && p.alwaysOnTokens <= maxTokens))
122
+ .slice(0, limit)
123
+ .map((p) => ({
124
+ slug: p.slug,
125
+ name: p.displayName ?? p.name,
126
+ description: p.description && p.description.length > 160 ? `${p.description.slice(0, 159)}…` : p.description,
127
+ alwaysOnTokens: p.alwaysOnTokens ?? null,
128
+ hasHooks: p.currentVersion?.hasHooksDetail ?? false,
129
+ hasMcp: p.currentVersion?.hasMcpDetail ?? false,
130
+ stars: p.starCount,
131
+ install: `npx claudepluginhub p/${p.slug}`,
132
+ url: `${SITE}/plugins/${p.slug}`,
133
+ }));
134
+ return ok({
135
+ results,
136
+ // Lives in the result, not the always-on definitions: list items carry no CLI refusal.
137
+ note: results.length > 0 ? 'Run inspect_plugin before installing: it shows Claude Code refusals.' : undefined,
138
+ });
139
+ }
140
+ async function inspectPlugin(args) {
141
+ const slug = optionalString(args, 'slug');
142
+ if (!slug || !SLUG_RE.test(slug))
143
+ throw new Error('"slug" must be a plugin slug like "my-plugin"');
144
+ const body = await getJson(`${BASE_URL}/api/plugins/${slug}`, `No plugin with slug "${slug}"`);
145
+ return ok(body);
146
+ }
147
+ async function recommendForProject(args) {
148
+ const dir = resolve(optionalString(args, 'projectDir') ?? process.cwd());
149
+ const signals = collectProjectSignals(dir);
150
+ if (signals.dependencies.length === 0 && signals.files.length === 0) {
151
+ throw new Error(`No project manifests found in ${dir}`);
152
+ }
153
+ // `cli` attribution: the server allowlists cli|plugin only, and this is the same npm package.
154
+ const fetched = await fetchRecommendations(signals, RECOMMEND_LIMIT, 'cli');
155
+ if (!fetched.ok)
156
+ throw new Error(fetched.error);
157
+ const { body } = fetched;
158
+ if (!Array.isArray(body.sections))
159
+ throw new Error('Unexpected response from the recommend API');
160
+ return ok({
161
+ stacks: body.stacks,
162
+ sections: body.sections.map((s) => ({
163
+ stack: s.stack,
164
+ plugins: s.results.map((r) => ({
165
+ slug: r.slug,
166
+ name: r.name,
167
+ stars: r.starCount,
168
+ runsCode: r.runsCode === true,
169
+ install: r.install.command,
170
+ url: `${SITE}/plugins/${r.slug}`,
171
+ })),
172
+ })),
173
+ });
174
+ }
175
+ function compactFinding(f) {
176
+ return {
177
+ severity: f.severity,
178
+ title: f.title,
179
+ message: f.message,
180
+ plugins: f.pluginIds.items,
181
+ ...(f.remediation ? { fix: f.remediation } : {}),
182
+ };
183
+ }
184
+ function doctorSetup(args) {
185
+ const dir = resolve(optionalString(args, 'projectDir') ?? process.cwd());
186
+ const probe = probeClaude();
187
+ if (!probe.ok)
188
+ throw new Error(probe.reason);
189
+ const report = buildDoctorReport({
190
+ records: probe.records,
191
+ droppedRecords: probe.droppedRecords,
192
+ claudeVersion: probe.claudeVersion,
193
+ cwdCanonical: canonicalize(dir),
194
+ flags: { json: true, strict: false, verbose: false, open: false, scope: 'all', allProjects: false },
195
+ scanner: createScanner(),
196
+ });
197
+ const { errors, warnings } = report.summary;
198
+ return ok({
199
+ verdict: errors > 0 ? 'error' : warnings > 0 ? 'warning' : 'ok',
200
+ claudeVersion: report.claude.version,
201
+ summary: report.summary,
202
+ findings: report.findings.items.map(compactFinding),
203
+ contexts: report.contexts.map((c) => ({
204
+ label: c.label,
205
+ isCurrent: c.isCurrent,
206
+ alwaysOnTokens: c.summary.estimatedAlwaysOnTokens,
207
+ estimateComplete: c.summary.estimateComplete,
208
+ activePlugins: c.summary.activePlugins,
209
+ topContributors: c.contributors?.top ?? [],
210
+ findings: c.findings.items.map(compactFinding),
211
+ })),
212
+ });
213
+ }
214
+ const HANDLERS = {
215
+ search_plugins: searchPlugins,
216
+ inspect_plugin: inspectPlugin,
217
+ recommend_for_project: recommendForProject,
218
+ doctor_setup: doctorSetup,
219
+ };
220
+ export function hasTool(name) {
221
+ return Object.hasOwn(HANDLERS, name);
222
+ }
223
+ export async function callTool(name, args) {
224
+ // Every failure (bad input, upstream, doctor) is a tool result the model can read and act on.
225
+ try {
226
+ return await HANDLERS[name](args);
227
+ }
228
+ catch (err) {
229
+ return { content: [{ type: 'text', text: err.message }], isError: true };
230
+ }
231
+ }
package/dist/output.d.ts CHANGED
@@ -18,8 +18,3 @@ export declare function printStep(label: string): void;
18
18
  export declare function printSuccess(label: string): void;
19
19
  export declare function printProgress(label: string): void;
20
20
  export declare function printFail(label: string, error?: string): void;
21
- export declare function printSummary(results: {
22
- name: string;
23
- ok: boolean;
24
- error?: string;
25
- }[]): void;
package/dist/output.js CHANGED
@@ -34,15 +34,3 @@ export function printProgress(label) {
34
34
  export function printFail(label, error) {
35
35
  print(` ${RED}fail${RESET} ${label}${error ? ` ${DIM}(${error})${RESET}` : ''}`);
36
36
  }
37
- export function printSummary(results) {
38
- const succeeded = results.filter((r) => r.ok).length;
39
- const failed = results.filter((r) => !r.ok).length;
40
- print('');
41
- if (failed === 0) {
42
- print(`${GREEN}${BOLD}Done!${RESET} ${succeeded} plugin(s) installed successfully.`);
43
- }
44
- else {
45
- print(`${YELLOW}${BOLD}Done.${RESET} ${succeeded} succeeded, ${failed} failed.`);
46
- }
47
- print('');
48
- }
package/dist/prompts.d.ts CHANGED
@@ -6,16 +6,9 @@ export interface SelectableItem {
6
6
  }
7
7
  export declare function checkboxPrompt(title: string, items: SelectableItem[]): Promise<number[] | null>;
8
8
  /**
9
- * Recommendation-specific multi-select. Differs from `checkboxPrompt` (which
10
- * existing collection/component selectors keep unchanged) in three deliberate
11
- * ways:
12
- * - NO select-all: the 'a' key is ignored — recommendations are opt-in per
13
- * item, never bulk-installed.
14
- * - Hard selection cap: toggling ON past `maxSelected` is rejected with
15
- * immediate hint feedback; toggling OFF always works.
16
- * - Non-TTY fallback returns [] (select nothing) — recommend must never
17
- * auto-install in a non-interactive run, unlike checkboxPrompt's
18
- * all-selected fallback.
9
+ * Unlike `checkboxPrompt`, deliberately: no select-all, a hard cap of
10
+ * `maxSelected` (toggling off always works), and non-TTY returns [] so
11
+ * recommend never auto-installs.
19
12
  */
20
13
  export declare function recommendPrompt(title: string, items: SelectableItem[], maxSelected: number): Promise<number[] | null>;
21
14
  export declare function confirmPrompt(message: string): Promise<boolean>;