@jcorpac/skill-vault 1.8.0 → 2.0.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,473 @@
1
+ #!/usr/bin/env python3
2
+ """Skill Vault Read-Only MCP Stdio Server.
3
+
4
+ Provides two read-only fallback tools (`search_skills`, `load_skill`) over JSON-RPC 2.0
5
+ (supporting both newline-delimited JSON and Content-Length framing) so coding agents can
6
+ look up cold-storage skills mid-turn without shell approvals or L1 mutations.
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import sys
14
+
15
+ SCRIPT_DIR = Path(__file__).resolve().parent
16
+ if str(SCRIPT_DIR) not in sys.path:
17
+ sys.path.insert(0, str(SCRIPT_DIR))
18
+
19
+ import skill_router # noqa: E402
20
+
21
+ SERVER_NAME = "skill-vault"
22
+ SERVER_VERSION = "2.0.0"
23
+ MAX_READ_BYTES = 102400 # 100 KB safety cap per tool call
24
+
25
+ TOOLS_SPEC = [
26
+ {
27
+ "name": "search_skills",
28
+ "description": (
29
+ "Search vaulted cold-storage skills by keyword, intent, or category. "
30
+ "Pass an empty query to list all available skill categories and counts."
31
+ ),
32
+ "inputSchema": {
33
+ "type": "object",
34
+ "properties": {
35
+ "query": {
36
+ "type": "string",
37
+ "description": "Search keywords or task intent (or empty string to list categories).",
38
+ },
39
+ "category": {
40
+ "type": "string",
41
+ "description": "Optional category name filter.",
42
+ },
43
+ "limit": {
44
+ "type": "integer",
45
+ "description": "Maximum results to return (default 8, max 25).",
46
+ "default": 8,
47
+ },
48
+ },
49
+ "required": ["query"],
50
+ },
51
+ "annotations": {
52
+ "readOnlyHint": True,
53
+ "destructiveHint": False,
54
+ "idempotentHint": True,
55
+ "openWorldHint": False,
56
+ },
57
+ },
58
+ {
59
+ "name": "load_skill",
60
+ "description": (
61
+ "Load the full SKILL.md instructions for a vaulted skill, or read a specific "
62
+ "companion file (e.g. 'references/guide.md') inside that skill's directory."
63
+ ),
64
+ "inputSchema": {
65
+ "type": "object",
66
+ "properties": {
67
+ "name": {
68
+ "type": "string",
69
+ "description": "Exact skill name from search_skills or pointer context.",
70
+ },
71
+ "file": {
72
+ "type": "string",
73
+ "description": "Optional relative path to a companion file inside the skill folder.",
74
+ },
75
+ },
76
+ "required": ["name"],
77
+ },
78
+ "annotations": {
79
+ "readOnlyHint": True,
80
+ "destructiveHint": False,
81
+ "idempotentHint": True,
82
+ "openWorldHint": False,
83
+ },
84
+ },
85
+ ]
86
+
87
+
88
+ def _debug(msg):
89
+ if os.environ.get("SKILL_VAULT_MCP_DEBUG") == "1":
90
+ sys.stderr.write(f"[skill-vault-mcp] {msg}\n")
91
+ sys.stderr.flush()
92
+
93
+
94
+ def _resolve_base_and_archive(cli_base=None):
95
+ if cli_base:
96
+ p = Path(cli_base).resolve()
97
+ return p, p / "skill_archive"
98
+
99
+ for env_key in ("SKILL_VAULT_BASE", "SKILL_BASE_DIR", "AGENTS_HOME"):
100
+ val = os.environ.get(env_key)
101
+ if val:
102
+ p = Path(val).resolve()
103
+ return p, p / "skill_archive"
104
+
105
+ candidates = []
106
+
107
+ plugin_data = os.environ.get("PLUGIN_DATA")
108
+ if plugin_data:
109
+ candidates.append(Path(plugin_data).resolve())
110
+
111
+ vault_link = SCRIPT_DIR.parent / "vault_link.json"
112
+ if vault_link.exists():
113
+ try:
114
+ link_data = json.loads(vault_link.read_text(encoding="utf-8"))
115
+ if isinstance(link_data, dict) and link_data.get("baseDir"):
116
+ candidates.append(Path(link_data["baseDir"]).resolve())
117
+ except Exception:
118
+ pass
119
+
120
+ for parent in Path(__file__).resolve().parents:
121
+ if parent.name != "skill_archive" and (parent / "skill_archive").exists():
122
+ candidates.append(parent)
123
+
124
+ home = Path.home()
125
+ candidates.extend([
126
+ home / ".gemini" / "config",
127
+ home / ".gemini" / "config" / "skills" / "skill-vault",
128
+ home / ".agents",
129
+ home / ".claude",
130
+ home / ".gemini",
131
+ home / ".cursor",
132
+ ])
133
+
134
+ for cand in candidates:
135
+ arch = cand / "skill_archive"
136
+ if arch.exists() and (
137
+ (arch / "backup_manifest.json").exists()
138
+ or (arch / "search_index.json").exists()
139
+ or (arch / "skills").exists()
140
+ ):
141
+ return cand, arch
142
+
143
+ for cand in candidates:
144
+ if cand.exists():
145
+ return cand, cand / "skill_archive"
146
+
147
+ fallback = home / ".gemini" / "config"
148
+ return fallback, fallback / "skill_archive"
149
+
150
+
151
+ def _load_index(base_dir, archive_dir):
152
+ if not archive_dir.exists():
153
+ return {"doc_count": 0, "skills": [], "df": {}, "avg_len": {}}
154
+ return skill_router.load_or_build_index(archive_dir=archive_dir, base_dir=base_dir)
155
+
156
+
157
+ def _tool_result(text, is_error=False):
158
+ return {
159
+ "content": [{"type": "text", "text": text}],
160
+ "isError": is_error,
161
+ }
162
+
163
+
164
+ def _handle_search_skills(args, base_dir, archive_dir):
165
+ query = str(args.get("query") or "")
166
+ category = args.get("category")
167
+ if category is not None:
168
+ category = str(category).strip() or None
169
+ try:
170
+ limit = int(args.get("limit", 8))
171
+ except (TypeError, ValueError):
172
+ limit = 8
173
+ limit = max(1, min(limit, 25))
174
+
175
+ index_data = _load_index(base_dir, archive_dir)
176
+ skills = index_data.get("skills", [])
177
+
178
+ if not query.strip() and not category:
179
+ cats = {}
180
+ for s in skills:
181
+ c = s.get("category", "General & Utility Skills")
182
+ cats[c] = cats.get(c, 0) + 1
183
+ summary = {
184
+ "total_skills": len(skills),
185
+ "categories": [
186
+ {"category": k, "count": v}
187
+ for k, v in sorted(cats.items(), key=lambda kv: (-kv[1], kv[0].lower()))
188
+ ],
189
+ }
190
+ return _tool_result(json.dumps(summary, indent=2, ensure_ascii=False))
191
+
192
+ matches = skill_router.search_index(
193
+ index_data=index_data,
194
+ query=query,
195
+ category=category,
196
+ limit=limit,
197
+ )
198
+
199
+ # Substring fallback for partial fragments (e.g., "proto") if tokenizer returned nothing
200
+ if not matches and query.strip():
201
+ q_lower = query.strip().lower()
202
+ fallback = []
203
+ for entry in skills:
204
+ if category and entry.get("category", "").lower() != category.lower():
205
+ continue
206
+ if (
207
+ q_lower in entry.get("name", "").lower()
208
+ or q_lower in entry.get("description", "").lower()
209
+ or q_lower in entry.get("category", "").lower()
210
+ ):
211
+ fallback.append({
212
+ "name": entry["name"],
213
+ "category": entry.get("category", "General & Utility Skills"),
214
+ "score": 1.0,
215
+ "description": entry.get("description", ""),
216
+ "companion_files": entry.get("companion_files", []),
217
+ })
218
+ matches = fallback[:limit]
219
+
220
+ payload = {
221
+ "query": query,
222
+ "count": len(matches),
223
+ "results": [
224
+ {
225
+ "name": m["name"],
226
+ "category": m["category"],
227
+ "score": m["score"],
228
+ "description": m["description"],
229
+ "companion_files": m.get("companion_files", []),
230
+ }
231
+ for m in matches
232
+ ],
233
+ }
234
+ return _tool_result(json.dumps(payload, indent=2, ensure_ascii=False))
235
+
236
+
237
+ def _find_skill_entry(index_data, skill_name):
238
+ target_canon = skill_router.canonicalize_skill_name(skill_name)
239
+ raw_lower = str(skill_name or "").strip().lower()
240
+ for entry in index_data.get("skills", []):
241
+ if entry.get("name", "").lower() == raw_lower:
242
+ return entry
243
+ if entry.get("canonical_key") == target_canon:
244
+ return entry
245
+ for alias in entry.get("aliases", []):
246
+ if alias.lower() == raw_lower:
247
+ return entry
248
+ return None
249
+
250
+
251
+ def _handle_load_skill(args, base_dir, archive_dir):
252
+ skill_name = str(args.get("name") or "").strip()
253
+ if not skill_name:
254
+ return _tool_result("Error: 'name' parameter is required.", is_error=True)
255
+
256
+ rel_file = args.get("file")
257
+ if rel_file is not None:
258
+ rel_file = str(rel_file).strip() or None
259
+
260
+ index_data = _load_index(base_dir, archive_dir)
261
+ entry = _find_skill_entry(index_data, skill_name)
262
+ if not entry:
263
+ return _tool_result(
264
+ f"Skill '{skill_name}' was not found in the Skill Vault archive. "
265
+ "Call search_skills to discover exact skill names.",
266
+ is_error=True,
267
+ )
268
+
269
+ skill_dir = None
270
+ if entry.get("resolved_path") and Path(entry["resolved_path"]).exists():
271
+ skill_dir = Path(entry["resolved_path"]).resolve()
272
+ elif entry.get("archived_path"):
273
+ cand = skill_router._resolve_archived_skill_dir(base_dir, archive_dir, entry["archived_path"])
274
+ if cand.exists():
275
+ skill_dir = cand.resolve()
276
+
277
+ if not skill_dir or not skill_dir.exists():
278
+ return _tool_result(
279
+ f"Error: Archived directory for skill '{skill_name}' does not exist on disk.",
280
+ is_error=True,
281
+ )
282
+
283
+ if rel_file:
284
+ # Strict path traversal check: target must reside inside skill_dir
285
+ try:
286
+ req_path = Path(rel_file)
287
+ if req_path.is_absolute():
288
+ return _tool_result(
289
+ "Error: Absolute paths are not allowed; provide a relative path inside the skill directory.",
290
+ is_error=True,
291
+ )
292
+ target = (skill_dir / req_path).resolve()
293
+ if skill_dir not in target.parents:
294
+ return _tool_result(
295
+ "Error: Path traversal denied; companion file must reside inside the skill directory.",
296
+ is_error=True,
297
+ )
298
+ except Exception as exc:
299
+ return _tool_result(f"Error resolving path: {exc}", is_error=True)
300
+
301
+ if not target.exists() or not target.is_file():
302
+ return _tool_result(
303
+ f"Error: Companion file '{rel_file}' not found inside '{entry['name']}'.",
304
+ is_error=True,
305
+ )
306
+
307
+ raw = target.read_bytes()
308
+ truncated = len(raw) > MAX_READ_BYTES
309
+ text = raw[:MAX_READ_BYTES].decode("utf-8", errors="replace")
310
+ if truncated:
311
+ text += f"\n\n[... truncated at {MAX_READ_BYTES} bytes ...]"
312
+ header = f"# {entry['name']} :: {rel_file}\n\n"
313
+ return _tool_result(header + text)
314
+
315
+ skill_md = skill_dir / "SKILL.md"
316
+ if not skill_md.exists():
317
+ return _tool_result(
318
+ f"Error: SKILL.md missing for skill '{entry['name']}'.",
319
+ is_error=True,
320
+ )
321
+
322
+ raw = skill_md.read_bytes()
323
+ truncated = len(raw) > MAX_READ_BYTES
324
+ content = raw[:MAX_READ_BYTES].decode("utf-8", errors="replace")
325
+ if truncated:
326
+ content += f"\n\n[... truncated at {MAX_READ_BYTES} bytes ...]"
327
+
328
+ companions = entry.get("companion_files", [])
329
+ comp_line = ", ".join(companions) if companions else "(none)"
330
+ header = (
331
+ f"Skill: {entry['name']}\n"
332
+ f"Category: {entry.get('category', 'General & Utility Skills')}\n"
333
+ f"Directory: {skill_dir}\n"
334
+ f"Companion Files: {comp_line}\n"
335
+ f"---\n"
336
+ )
337
+ return _tool_result(header + content)
338
+
339
+
340
+ def _read_rpc_message(stdin_buf):
341
+ """Read one JSON-RPC message supporting both newline-delimited JSON and Content-Length framing."""
342
+ while True:
343
+ line = stdin_buf.readline()
344
+ if not line:
345
+ return None, None
346
+ stripped = line.strip()
347
+ if not stripped:
348
+ continue
349
+
350
+ lower = stripped.lower()
351
+ if lower.startswith(b"content-length:"):
352
+ try:
353
+ content_length = int(stripped.split(b":", 1)[1].strip())
354
+ except ValueError:
355
+ return None, "content_length"
356
+ # Consume remaining headers up to blank line
357
+ while True:
358
+ hdr = stdin_buf.readline()
359
+ if not hdr or hdr.strip() == b"":
360
+ break
361
+ body = stdin_buf.read(content_length)
362
+ if not body:
363
+ return None, "content_length"
364
+ return json.loads(body.decode("utf-8", errors="replace")), "content_length"
365
+
366
+ return json.loads(stripped.decode("utf-8", errors="replace")), "newline"
367
+
368
+
369
+ def _write_rpc_message(stdout_buf, payload, framing):
370
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
371
+ if framing == "content_length":
372
+ header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
373
+ stdout_buf.write(header + body)
374
+ else:
375
+ stdout_buf.write(body + b"\n")
376
+ stdout_buf.flush()
377
+
378
+
379
+ def _dispatch_request(msg, base_dir, archive_dir):
380
+ method = msg.get("method")
381
+ msg_id = msg.get("id")
382
+ params = msg.get("params") or {}
383
+
384
+ # Notifications have no id (or id is None) and expect no response
385
+ if msg_id is None:
386
+ return None
387
+
388
+ if method == "initialize":
389
+ proto_ver = params.get("protocolVersion") or "2024-11-05"
390
+ result = {
391
+ "protocolVersion": proto_ver,
392
+ "capabilities": {"tools": {}},
393
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
394
+ }
395
+ return {"jsonrpc": "2.0", "id": msg_id, "result": result}
396
+
397
+ if method == "ping":
398
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
399
+
400
+ if method == "tools/list":
401
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
402
+
403
+ if method == "tools/call":
404
+ tool_name = params.get("name")
405
+ args = params.get("arguments") or {}
406
+ if tool_name == "search_skills":
407
+ res = _handle_search_skills(args, base_dir, archive_dir)
408
+ elif tool_name == "load_skill":
409
+ res = _handle_load_skill(args, base_dir, archive_dir)
410
+ else:
411
+ return {
412
+ "jsonrpc": "2.0",
413
+ "id": msg_id,
414
+ "error": {"code": -32601, "message": f"Unknown tool: {tool_name}"},
415
+ }
416
+ return {"jsonrpc": "2.0", "id": msg_id, "result": res}
417
+
418
+ return {
419
+ "jsonrpc": "2.0",
420
+ "id": msg_id,
421
+ "error": {"code": -32601, "message": f"Method not found: {method}"},
422
+ }
423
+
424
+
425
+ def main():
426
+ parser = argparse.ArgumentParser(description="Skill Vault Read-Only MCP Stdio Server")
427
+ parser.add_argument("--base-dir", help="Explicit Skill Vault base directory")
428
+ args, _ = parser.parse_known_args()
429
+
430
+ base_dir, archive_dir = _resolve_base_and_archive(args.base_dir)
431
+ _debug(f"Started MCP server with base_dir={base_dir}, archive_dir={archive_dir}")
432
+
433
+ stdin_buf = sys.stdin.buffer
434
+ stdout_buf = sys.stdout.buffer
435
+ detected_framing = "newline"
436
+
437
+ while True:
438
+ try:
439
+ msg, framing = _read_rpc_message(stdin_buf)
440
+ except Exception as exc:
441
+ _debug(f"Parse error: {exc}")
442
+ err_resp = {
443
+ "jsonrpc": "2.0",
444
+ "id": None,
445
+ "error": {"code": -32700, "message": f"Parse error: {exc}"},
446
+ }
447
+ _write_rpc_message(stdout_buf, err_resp, detected_framing)
448
+ continue
449
+
450
+ if msg is None:
451
+ break
452
+ if framing:
453
+ detected_framing = framing
454
+
455
+ try:
456
+ resp = _dispatch_request(msg, base_dir, archive_dir)
457
+ except Exception as exc:
458
+ _debug(f"Internal error: {exc}")
459
+ msg_id = msg.get("id") if isinstance(msg, dict) else None
460
+ if msg_id is None:
461
+ continue
462
+ resp = {
463
+ "jsonrpc": "2.0",
464
+ "id": msg_id,
465
+ "error": {"code": -32603, "message": f"Internal error: {exc}"},
466
+ }
467
+
468
+ if resp is not None:
469
+ _write_rpc_message(stdout_buf, resp, detected_framing)
470
+
471
+
472
+ if __name__ == "__main__":
473
+ main()