@jcorpac/skill-vault 1.8.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -98
- package/SKILL.md +40 -219
- package/bin/hook.js +37 -0
- package/bin/mcp.js +37 -0
- package/hooks.json +20 -0
- package/mcp_config.json +9 -0
- package/package.json +8 -3
- package/plugin.json +10 -0
- package/scripts/hook_runner.py +488 -0
- package/scripts/mcp_server.py +636 -0
- package/scripts/skill_router.py +1187 -0
- package/scripts/skill_vault.py +1289 -96
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Skill Vault Read-Only MCP Stdio Server.
|
|
3
|
+
|
|
4
|
+
Provides three read-only fallback tools (`search_skills`, `list_skills`, `load_skill`) over
|
|
5
|
+
JSON-RPC 2.0 (supporting both newline-delimited JSON and Content-Length framing) so coding
|
|
6
|
+
agents can discover and inspect 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 re
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
17
|
+
if str(SCRIPT_DIR) not in sys.path:
|
|
18
|
+
sys.path.insert(0, str(SCRIPT_DIR))
|
|
19
|
+
|
|
20
|
+
import skill_router # noqa: E402
|
|
21
|
+
|
|
22
|
+
SERVER_NAME = "skill-vault"
|
|
23
|
+
SERVER_VERSION = "2.0.1"
|
|
24
|
+
MAX_READ_BYTES = 102400 # 100 KB safety cap per tool call
|
|
25
|
+
|
|
26
|
+
TOOLS_SPEC = [
|
|
27
|
+
{
|
|
28
|
+
"name": "search_skills",
|
|
29
|
+
"description": (
|
|
30
|
+
"Search vaulted cold-storage skills by keyword, intent, or category. "
|
|
31
|
+
"Pass an empty query to list categories and counts, or use list_skills to list all skill names in one call."
|
|
32
|
+
),
|
|
33
|
+
"inputSchema": {
|
|
34
|
+
"type": "object",
|
|
35
|
+
"properties": {
|
|
36
|
+
"query": {
|
|
37
|
+
"type": "string",
|
|
38
|
+
"description": "Search keywords or task intent (or empty string to list categories).",
|
|
39
|
+
},
|
|
40
|
+
"category": {
|
|
41
|
+
"type": "string",
|
|
42
|
+
"description": "Optional category name filter.",
|
|
43
|
+
},
|
|
44
|
+
"limit": {
|
|
45
|
+
"type": "integer",
|
|
46
|
+
"description": "Maximum results to return (default 8, max 25).",
|
|
47
|
+
"default": 8,
|
|
48
|
+
},
|
|
49
|
+
"offset": {
|
|
50
|
+
"type": "integer",
|
|
51
|
+
"description": "Pagination offset into sorted results (default 0).",
|
|
52
|
+
"default": 0,
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
"required": ["query"],
|
|
56
|
+
},
|
|
57
|
+
"annotations": {
|
|
58
|
+
"readOnlyHint": True,
|
|
59
|
+
"destructiveHint": False,
|
|
60
|
+
"idempotentHint": True,
|
|
61
|
+
"openWorldHint": False,
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"name": "list_skills",
|
|
66
|
+
"description": (
|
|
67
|
+
"List all vaulted cold-storage skill names grouped by category in a single compact call "
|
|
68
|
+
"(no 25-item limit). Optionally filter by category or include short 1-line descriptions."
|
|
69
|
+
),
|
|
70
|
+
"inputSchema": {
|
|
71
|
+
"type": "object",
|
|
72
|
+
"properties": {
|
|
73
|
+
"category": {
|
|
74
|
+
"type": "string",
|
|
75
|
+
"description": "Optional category name filter (case-insensitive).",
|
|
76
|
+
},
|
|
77
|
+
"include_descriptions": {
|
|
78
|
+
"type": "boolean",
|
|
79
|
+
"description": (
|
|
80
|
+
"Include truncated 1-line descriptions per skill "
|
|
81
|
+
"(default false for compact names-only output)."
|
|
82
|
+
),
|
|
83
|
+
"default": False,
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
"annotations": {
|
|
88
|
+
"readOnlyHint": True,
|
|
89
|
+
"destructiveHint": False,
|
|
90
|
+
"idempotentHint": True,
|
|
91
|
+
"openWorldHint": False,
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
"name": "load_skill",
|
|
96
|
+
"description": (
|
|
97
|
+
"Load the full SKILL.md instructions for a vaulted skill, or read a specific "
|
|
98
|
+
"companion file (e.g. 'references/guide.md') inside that skill's directory."
|
|
99
|
+
),
|
|
100
|
+
"inputSchema": {
|
|
101
|
+
"type": "object",
|
|
102
|
+
"properties": {
|
|
103
|
+
"name": {
|
|
104
|
+
"type": "string",
|
|
105
|
+
"description": "Exact skill name from search_skills or pointer context.",
|
|
106
|
+
},
|
|
107
|
+
"file": {
|
|
108
|
+
"type": "string",
|
|
109
|
+
"description": "Optional relative path to a companion file inside the skill folder.",
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
"required": ["name"],
|
|
113
|
+
},
|
|
114
|
+
"annotations": {
|
|
115
|
+
"readOnlyHint": True,
|
|
116
|
+
"destructiveHint": False,
|
|
117
|
+
"idempotentHint": True,
|
|
118
|
+
"openWorldHint": False,
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _debug(msg):
|
|
125
|
+
if os.environ.get("SKILL_VAULT_MCP_DEBUG") == "1":
|
|
126
|
+
sys.stderr.write(f"[skill-vault-mcp] {msg}\n")
|
|
127
|
+
sys.stderr.flush()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _resolve_base_and_archive(cli_base=None):
|
|
131
|
+
if cli_base:
|
|
132
|
+
p = Path(cli_base).resolve()
|
|
133
|
+
return p, p / "skill_archive"
|
|
134
|
+
|
|
135
|
+
for env_key in ("SKILL_VAULT_BASE", "SKILL_BASE_DIR", "AGENTS_HOME"):
|
|
136
|
+
val = os.environ.get(env_key)
|
|
137
|
+
if val:
|
|
138
|
+
p = Path(val).resolve()
|
|
139
|
+
return p, p / "skill_archive"
|
|
140
|
+
|
|
141
|
+
candidates = []
|
|
142
|
+
|
|
143
|
+
plugin_data = os.environ.get("PLUGIN_DATA")
|
|
144
|
+
if plugin_data:
|
|
145
|
+
candidates.append(Path(plugin_data).resolve())
|
|
146
|
+
|
|
147
|
+
vault_link = SCRIPT_DIR.parent / "vault_link.json"
|
|
148
|
+
if vault_link.exists():
|
|
149
|
+
try:
|
|
150
|
+
link_data = json.loads(vault_link.read_text(encoding="utf-8"))
|
|
151
|
+
if isinstance(link_data, dict) and link_data.get("baseDir"):
|
|
152
|
+
candidates.append(Path(link_data["baseDir"]).resolve())
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
for parent in Path(__file__).resolve().parents:
|
|
157
|
+
if parent.name != "skill_archive" and (parent / "skill_archive").exists():
|
|
158
|
+
candidates.append(parent)
|
|
159
|
+
|
|
160
|
+
home = Path.home()
|
|
161
|
+
candidates.extend([
|
|
162
|
+
home / ".gemini" / "config",
|
|
163
|
+
home / ".gemini" / "config" / "skills" / "skill-vault",
|
|
164
|
+
home / ".agents",
|
|
165
|
+
home / ".claude",
|
|
166
|
+
home / ".gemini",
|
|
167
|
+
home / ".cursor",
|
|
168
|
+
])
|
|
169
|
+
|
|
170
|
+
for cand in candidates:
|
|
171
|
+
arch = cand / "skill_archive"
|
|
172
|
+
if arch.exists() and (
|
|
173
|
+
(arch / "backup_manifest.json").exists()
|
|
174
|
+
or (arch / "search_index.json").exists()
|
|
175
|
+
or (arch / "skills").exists()
|
|
176
|
+
):
|
|
177
|
+
return cand, arch
|
|
178
|
+
|
|
179
|
+
for cand in candidates:
|
|
180
|
+
if cand.exists():
|
|
181
|
+
return cand, cand / "skill_archive"
|
|
182
|
+
|
|
183
|
+
fallback = home / ".gemini" / "config"
|
|
184
|
+
return fallback, fallback / "skill_archive"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
_INDEX_CACHE = {}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _file_sig(path):
|
|
191
|
+
try:
|
|
192
|
+
st = Path(path).stat()
|
|
193
|
+
return (st.st_mtime_ns, st.st_size)
|
|
194
|
+
except OSError:
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def clear_index_cache():
|
|
199
|
+
"""Clear the in-memory search index cache."""
|
|
200
|
+
_INDEX_CACHE.clear()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _load_index(base_dir, archive_dir):
|
|
204
|
+
archive_path = Path(archive_dir).resolve()
|
|
205
|
+
cache_key = str(archive_path)
|
|
206
|
+
if not archive_path.exists():
|
|
207
|
+
_INDEX_CACHE.pop(cache_key, None)
|
|
208
|
+
return {"doc_count": 0, "skills": [], "df": {}, "avg_len": {}}
|
|
209
|
+
|
|
210
|
+
index_sig = _file_sig(archive_path / "search_index.json")
|
|
211
|
+
manifest_sig = _file_sig(archive_path / "backup_manifest.json")
|
|
212
|
+
cached = _INDEX_CACHE.get(cache_key)
|
|
213
|
+
if cached is not None and cached[0] == index_sig and cached[1] == manifest_sig:
|
|
214
|
+
return cached[2]
|
|
215
|
+
|
|
216
|
+
data = skill_router.load_or_build_index(archive_dir=archive_path, base_dir=base_dir)
|
|
217
|
+
new_index_sig = _file_sig(archive_path / "search_index.json")
|
|
218
|
+
new_manifest_sig = _file_sig(archive_path / "backup_manifest.json")
|
|
219
|
+
_INDEX_CACHE[cache_key] = (new_index_sig, new_manifest_sig, data)
|
|
220
|
+
return data
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _tool_result(text, is_error=False):
|
|
224
|
+
return {
|
|
225
|
+
"content": [{"type": "text", "text": text}],
|
|
226
|
+
"isError": is_error,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _short_desc(text, max_len=160):
|
|
231
|
+
collapsed = " ".join(str(text or "").split())
|
|
232
|
+
if len(collapsed) <= max_len:
|
|
233
|
+
return collapsed
|
|
234
|
+
return collapsed[: max_len - 3].rstrip() + "..."
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _handle_list_skills(args, base_dir, archive_dir):
|
|
238
|
+
category = args.get("category")
|
|
239
|
+
if category is not None:
|
|
240
|
+
category = str(category).strip() or None
|
|
241
|
+
|
|
242
|
+
raw_inc = args.get("include_descriptions", False)
|
|
243
|
+
if isinstance(raw_inc, bool):
|
|
244
|
+
include_descriptions = raw_inc
|
|
245
|
+
elif isinstance(raw_inc, str):
|
|
246
|
+
include_descriptions = raw_inc.strip().lower() in ("true", "1", "yes")
|
|
247
|
+
else:
|
|
248
|
+
include_descriptions = bool(raw_inc)
|
|
249
|
+
|
|
250
|
+
index_data = _load_index(base_dir, archive_dir)
|
|
251
|
+
skills = index_data.get("skills", [])
|
|
252
|
+
|
|
253
|
+
grouped = {}
|
|
254
|
+
for entry in skills:
|
|
255
|
+
cat = entry.get("category") or "General & Utility Skills"
|
|
256
|
+
grouped.setdefault(cat, []).append(entry)
|
|
257
|
+
|
|
258
|
+
all_categories = sorted(grouped.keys(), key=str.lower)
|
|
259
|
+
|
|
260
|
+
if category:
|
|
261
|
+
cat_lower = category.lower()
|
|
262
|
+
filtered_items = [
|
|
263
|
+
(cat, items) for cat, items in grouped.items() if cat.lower() == cat_lower
|
|
264
|
+
]
|
|
265
|
+
else:
|
|
266
|
+
filtered_items = list(grouped.items())
|
|
267
|
+
|
|
268
|
+
filtered_items.sort(key=lambda kv: (-len(kv[1]), kv[0].lower()))
|
|
269
|
+
|
|
270
|
+
cat_blocks = []
|
|
271
|
+
total_matching = 0
|
|
272
|
+
for cat, items in filtered_items:
|
|
273
|
+
sorted_entries = sorted(items, key=lambda s: s.get("name", "").lower())
|
|
274
|
+
total_matching += len(sorted_entries)
|
|
275
|
+
if include_descriptions:
|
|
276
|
+
skill_list = [
|
|
277
|
+
{
|
|
278
|
+
"name": s["name"],
|
|
279
|
+
"description": _short_desc(s.get("description", "")),
|
|
280
|
+
}
|
|
281
|
+
for s in sorted_entries
|
|
282
|
+
]
|
|
283
|
+
else:
|
|
284
|
+
skill_list = [s["name"] for s in sorted_entries]
|
|
285
|
+
cat_blocks.append({
|
|
286
|
+
"category": cat,
|
|
287
|
+
"count": len(sorted_entries),
|
|
288
|
+
"skills": skill_list,
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
payload = {
|
|
292
|
+
"total_skills": total_matching,
|
|
293
|
+
"category_count": len(cat_blocks),
|
|
294
|
+
"categories": cat_blocks,
|
|
295
|
+
}
|
|
296
|
+
if category and total_matching == 0:
|
|
297
|
+
payload["available_categories"] = all_categories
|
|
298
|
+
|
|
299
|
+
return _tool_result(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _handle_search_skills(args, base_dir, archive_dir):
|
|
303
|
+
query = str(args.get("query") or "")
|
|
304
|
+
category = args.get("category")
|
|
305
|
+
if category is not None:
|
|
306
|
+
category = str(category).strip() or None
|
|
307
|
+
try:
|
|
308
|
+
limit = int(args.get("limit", 8))
|
|
309
|
+
except (TypeError, ValueError):
|
|
310
|
+
limit = 8
|
|
311
|
+
limit = max(1, min(limit, 25))
|
|
312
|
+
try:
|
|
313
|
+
offset = max(0, int(args.get("offset", 0)))
|
|
314
|
+
except (TypeError, ValueError):
|
|
315
|
+
offset = 0
|
|
316
|
+
|
|
317
|
+
index_data = _load_index(base_dir, archive_dir)
|
|
318
|
+
skills = index_data.get("skills", [])
|
|
319
|
+
|
|
320
|
+
if not query.strip() and not category:
|
|
321
|
+
cats = {}
|
|
322
|
+
for s in skills:
|
|
323
|
+
c = s.get("category", "General & Utility Skills")
|
|
324
|
+
cats[c] = cats.get(c, 0) + 1
|
|
325
|
+
summary = {
|
|
326
|
+
"total_skills": len(skills),
|
|
327
|
+
"categories": [
|
|
328
|
+
{"category": k, "count": v}
|
|
329
|
+
for k, v in sorted(cats.items(), key=lambda kv: (-kv[1], kv[0].lower()))
|
|
330
|
+
],
|
|
331
|
+
}
|
|
332
|
+
return _tool_result(json.dumps(summary, indent=2, ensure_ascii=False))
|
|
333
|
+
|
|
334
|
+
all_matches = skill_router.search_index(
|
|
335
|
+
index_data=index_data,
|
|
336
|
+
query=query,
|
|
337
|
+
category=category,
|
|
338
|
+
limit=None,
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
# Substring fallback for partial fragments (e.g., "proto") if BM25 returned nothing
|
|
342
|
+
if not all_matches and query.strip():
|
|
343
|
+
q_lower = query.strip().lower()
|
|
344
|
+
word_pat = re.compile(rf"(?<![a-z0-9]){re.escape(q_lower)}(?![a-z0-9])")
|
|
345
|
+
fallback = []
|
|
346
|
+
for entry in skills:
|
|
347
|
+
entry_cat = entry.get("category", "General & Utility Skills")
|
|
348
|
+
if category and entry_cat.lower() != category.lower():
|
|
349
|
+
continue
|
|
350
|
+
name_l = entry.get("name", "").lower()
|
|
351
|
+
aliases_l = [a.lower() for a in entry.get("aliases", [entry.get("name", "")])]
|
|
352
|
+
desc_l = entry.get("description", "").lower()
|
|
353
|
+
cat_l = entry_cat.lower()
|
|
354
|
+
|
|
355
|
+
if q_lower == name_l or q_lower in aliases_l:
|
|
356
|
+
score = 10.0
|
|
357
|
+
elif q_lower in name_l or any(q_lower in a for a in aliases_l):
|
|
358
|
+
score = 5.0
|
|
359
|
+
elif word_pat.search(desc_l):
|
|
360
|
+
score = 2.0
|
|
361
|
+
elif q_lower in desc_l or q_lower in cat_l:
|
|
362
|
+
score = 1.0
|
|
363
|
+
else:
|
|
364
|
+
continue
|
|
365
|
+
|
|
366
|
+
fallback.append({
|
|
367
|
+
"name": entry["name"],
|
|
368
|
+
"category": entry_cat,
|
|
369
|
+
"score": score,
|
|
370
|
+
"description": entry.get("description", ""),
|
|
371
|
+
"companion_files": entry.get("companion_files", []),
|
|
372
|
+
})
|
|
373
|
+
fallback.sort(key=lambda m: (-m["score"], m["name"].lower()))
|
|
374
|
+
all_matches = fallback
|
|
375
|
+
|
|
376
|
+
total_matches = len(all_matches)
|
|
377
|
+
matches = all_matches[offset : offset + limit]
|
|
378
|
+
|
|
379
|
+
payload = {
|
|
380
|
+
"query": query,
|
|
381
|
+
"total_matches": total_matches,
|
|
382
|
+
"offset": offset,
|
|
383
|
+
"count": len(matches),
|
|
384
|
+
"results": [
|
|
385
|
+
{
|
|
386
|
+
"name": m["name"],
|
|
387
|
+
"category": m["category"],
|
|
388
|
+
"score": m["score"],
|
|
389
|
+
"description": m["description"],
|
|
390
|
+
"companion_files": m.get("companion_files", []),
|
|
391
|
+
}
|
|
392
|
+
for m in matches
|
|
393
|
+
],
|
|
394
|
+
}
|
|
395
|
+
return _tool_result(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _find_skill_entry(index_data, skill_name):
|
|
399
|
+
target_canon = skill_router.canonicalize_skill_name(skill_name)
|
|
400
|
+
raw_lower = str(skill_name or "").strip().lower()
|
|
401
|
+
for entry in index_data.get("skills", []):
|
|
402
|
+
if entry.get("name", "").lower() == raw_lower:
|
|
403
|
+
return entry
|
|
404
|
+
if entry.get("canonical_key") == target_canon:
|
|
405
|
+
return entry
|
|
406
|
+
for alias in entry.get("aliases", []):
|
|
407
|
+
if alias.lower() == raw_lower:
|
|
408
|
+
return entry
|
|
409
|
+
return None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _handle_load_skill(args, base_dir, archive_dir):
|
|
413
|
+
skill_name = str(args.get("name") or "").strip()
|
|
414
|
+
if not skill_name:
|
|
415
|
+
return _tool_result("Error: 'name' parameter is required.", is_error=True)
|
|
416
|
+
|
|
417
|
+
rel_file = args.get("file")
|
|
418
|
+
if rel_file is not None:
|
|
419
|
+
rel_file = str(rel_file).strip() or None
|
|
420
|
+
|
|
421
|
+
index_data = _load_index(base_dir, archive_dir)
|
|
422
|
+
entry = _find_skill_entry(index_data, skill_name)
|
|
423
|
+
if not entry:
|
|
424
|
+
return _tool_result(
|
|
425
|
+
f"Skill '{skill_name}' was not found in the Skill Vault archive. "
|
|
426
|
+
"Call search_skills to discover exact skill names.",
|
|
427
|
+
is_error=True,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
skill_dir = None
|
|
431
|
+
if entry.get("resolved_path") and Path(entry["resolved_path"]).exists():
|
|
432
|
+
skill_dir = Path(entry["resolved_path"]).resolve()
|
|
433
|
+
elif entry.get("archived_path"):
|
|
434
|
+
cand = skill_router._resolve_archived_skill_dir(base_dir, archive_dir, entry["archived_path"])
|
|
435
|
+
if cand.exists():
|
|
436
|
+
skill_dir = cand.resolve()
|
|
437
|
+
|
|
438
|
+
if not skill_dir or not skill_dir.exists():
|
|
439
|
+
return _tool_result(
|
|
440
|
+
f"Error: Archived directory for skill '{skill_name}' does not exist on disk.",
|
|
441
|
+
is_error=True,
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
if rel_file:
|
|
445
|
+
# Strict path traversal check: target must reside inside skill_dir
|
|
446
|
+
try:
|
|
447
|
+
req_path = Path(rel_file)
|
|
448
|
+
if req_path.is_absolute():
|
|
449
|
+
return _tool_result(
|
|
450
|
+
"Error: Absolute paths are not allowed; provide a relative path inside the skill directory.",
|
|
451
|
+
is_error=True,
|
|
452
|
+
)
|
|
453
|
+
target = (skill_dir / req_path).resolve()
|
|
454
|
+
if skill_dir not in target.parents:
|
|
455
|
+
return _tool_result(
|
|
456
|
+
"Error: Path traversal denied; companion file must reside inside the skill directory.",
|
|
457
|
+
is_error=True,
|
|
458
|
+
)
|
|
459
|
+
except Exception as exc:
|
|
460
|
+
return _tool_result(f"Error resolving path: {exc}", is_error=True)
|
|
461
|
+
|
|
462
|
+
if not target.exists() or not target.is_file():
|
|
463
|
+
return _tool_result(
|
|
464
|
+
f"Error: Companion file '{rel_file}' not found inside '{entry['name']}'.",
|
|
465
|
+
is_error=True,
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
raw = target.read_bytes()
|
|
469
|
+
truncated = len(raw) > MAX_READ_BYTES
|
|
470
|
+
text = raw[:MAX_READ_BYTES].decode("utf-8", errors="replace")
|
|
471
|
+
if truncated:
|
|
472
|
+
text += f"\n\n[... truncated at {MAX_READ_BYTES} bytes ...]"
|
|
473
|
+
header = f"# {entry['name']} :: {rel_file}\n\n"
|
|
474
|
+
return _tool_result(header + text)
|
|
475
|
+
|
|
476
|
+
skill_md = skill_dir / "SKILL.md"
|
|
477
|
+
if not skill_md.exists():
|
|
478
|
+
return _tool_result(
|
|
479
|
+
f"Error: SKILL.md missing for skill '{entry['name']}'.",
|
|
480
|
+
is_error=True,
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
raw = skill_md.read_bytes()
|
|
484
|
+
truncated = len(raw) > MAX_READ_BYTES
|
|
485
|
+
content = raw[:MAX_READ_BYTES].decode("utf-8", errors="replace")
|
|
486
|
+
if truncated:
|
|
487
|
+
content += f"\n\n[... truncated at {MAX_READ_BYTES} bytes ...]"
|
|
488
|
+
|
|
489
|
+
companions = entry.get("companion_files", [])
|
|
490
|
+
comp_line = ", ".join(companions) if companions else "(none)"
|
|
491
|
+
header = (
|
|
492
|
+
f"Skill: {entry['name']}\n"
|
|
493
|
+
f"Category: {entry.get('category', 'General & Utility Skills')}\n"
|
|
494
|
+
f"Directory: {skill_dir}\n"
|
|
495
|
+
f"Companion Files: {comp_line}\n"
|
|
496
|
+
f"---\n"
|
|
497
|
+
)
|
|
498
|
+
return _tool_result(header + content)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _read_rpc_message(stdin_buf):
|
|
502
|
+
"""Read one JSON-RPC message supporting both newline-delimited JSON and Content-Length framing."""
|
|
503
|
+
while True:
|
|
504
|
+
line = stdin_buf.readline()
|
|
505
|
+
if not line:
|
|
506
|
+
return None, None
|
|
507
|
+
stripped = line.strip()
|
|
508
|
+
if not stripped:
|
|
509
|
+
continue
|
|
510
|
+
|
|
511
|
+
lower = stripped.lower()
|
|
512
|
+
if lower.startswith(b"content-length:"):
|
|
513
|
+
try:
|
|
514
|
+
content_length = int(stripped.split(b":", 1)[1].strip())
|
|
515
|
+
except ValueError:
|
|
516
|
+
return None, "content_length"
|
|
517
|
+
# Consume remaining headers up to blank line
|
|
518
|
+
while True:
|
|
519
|
+
hdr = stdin_buf.readline()
|
|
520
|
+
if not hdr or hdr.strip() == b"":
|
|
521
|
+
break
|
|
522
|
+
body = stdin_buf.read(content_length)
|
|
523
|
+
if not body:
|
|
524
|
+
return None, "content_length"
|
|
525
|
+
return json.loads(body.decode("utf-8", errors="replace")), "content_length"
|
|
526
|
+
|
|
527
|
+
return json.loads(stripped.decode("utf-8", errors="replace")), "newline"
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _write_rpc_message(stdout_buf, payload, framing):
|
|
531
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
532
|
+
if framing == "content_length":
|
|
533
|
+
header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
|
|
534
|
+
stdout_buf.write(header + body)
|
|
535
|
+
else:
|
|
536
|
+
stdout_buf.write(body + b"\n")
|
|
537
|
+
stdout_buf.flush()
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _dispatch_request(msg, base_dir, archive_dir):
|
|
541
|
+
method = msg.get("method")
|
|
542
|
+
msg_id = msg.get("id")
|
|
543
|
+
params = msg.get("params") or {}
|
|
544
|
+
|
|
545
|
+
# Notifications have no id (or id is None) and expect no response
|
|
546
|
+
if msg_id is None:
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
if method == "initialize":
|
|
550
|
+
proto_ver = params.get("protocolVersion") or "2024-11-05"
|
|
551
|
+
result = {
|
|
552
|
+
"protocolVersion": proto_ver,
|
|
553
|
+
"capabilities": {"tools": {}},
|
|
554
|
+
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
|
555
|
+
}
|
|
556
|
+
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
|
|
557
|
+
|
|
558
|
+
if method == "ping":
|
|
559
|
+
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
|
|
560
|
+
|
|
561
|
+
if method == "tools/list":
|
|
562
|
+
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
|
|
563
|
+
|
|
564
|
+
if method == "tools/call":
|
|
565
|
+
tool_name = params.get("name")
|
|
566
|
+
args = params.get("arguments") or {}
|
|
567
|
+
if tool_name == "search_skills":
|
|
568
|
+
res = _handle_search_skills(args, base_dir, archive_dir)
|
|
569
|
+
elif tool_name == "list_skills":
|
|
570
|
+
res = _handle_list_skills(args, base_dir, archive_dir)
|
|
571
|
+
elif tool_name == "load_skill":
|
|
572
|
+
res = _handle_load_skill(args, base_dir, archive_dir)
|
|
573
|
+
else:
|
|
574
|
+
return {
|
|
575
|
+
"jsonrpc": "2.0",
|
|
576
|
+
"id": msg_id,
|
|
577
|
+
"error": {"code": -32601, "message": f"Unknown tool: {tool_name}"},
|
|
578
|
+
}
|
|
579
|
+
return {"jsonrpc": "2.0", "id": msg_id, "result": res}
|
|
580
|
+
|
|
581
|
+
return {
|
|
582
|
+
"jsonrpc": "2.0",
|
|
583
|
+
"id": msg_id,
|
|
584
|
+
"error": {"code": -32601, "message": f"Method not found: {method}"},
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def main():
|
|
589
|
+
parser = argparse.ArgumentParser(description="Skill Vault Read-Only MCP Stdio Server")
|
|
590
|
+
parser.add_argument("--base-dir", help="Explicit Skill Vault base directory")
|
|
591
|
+
args, _ = parser.parse_known_args()
|
|
592
|
+
|
|
593
|
+
base_dir, archive_dir = _resolve_base_and_archive(args.base_dir)
|
|
594
|
+
_debug(f"Started MCP server with base_dir={base_dir}, archive_dir={archive_dir}")
|
|
595
|
+
|
|
596
|
+
stdin_buf = sys.stdin.buffer
|
|
597
|
+
stdout_buf = sys.stdout.buffer
|
|
598
|
+
detected_framing = "newline"
|
|
599
|
+
|
|
600
|
+
while True:
|
|
601
|
+
try:
|
|
602
|
+
msg, framing = _read_rpc_message(stdin_buf)
|
|
603
|
+
except Exception as exc:
|
|
604
|
+
_debug(f"Parse error: {exc}")
|
|
605
|
+
err_resp = {
|
|
606
|
+
"jsonrpc": "2.0",
|
|
607
|
+
"id": None,
|
|
608
|
+
"error": {"code": -32700, "message": f"Parse error: {exc}"},
|
|
609
|
+
}
|
|
610
|
+
_write_rpc_message(stdout_buf, err_resp, detected_framing)
|
|
611
|
+
continue
|
|
612
|
+
|
|
613
|
+
if msg is None:
|
|
614
|
+
break
|
|
615
|
+
if framing:
|
|
616
|
+
detected_framing = framing
|
|
617
|
+
|
|
618
|
+
try:
|
|
619
|
+
resp = _dispatch_request(msg, base_dir, archive_dir)
|
|
620
|
+
except Exception as exc:
|
|
621
|
+
_debug(f"Internal error: {exc}")
|
|
622
|
+
msg_id = msg.get("id") if isinstance(msg, dict) else None
|
|
623
|
+
if msg_id is None:
|
|
624
|
+
continue
|
|
625
|
+
resp = {
|
|
626
|
+
"jsonrpc": "2.0",
|
|
627
|
+
"id": msg_id,
|
|
628
|
+
"error": {"code": -32603, "message": f"Internal error: {exc}"},
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
if resp is not None:
|
|
632
|
+
_write_rpc_message(stdout_buf, resp, detected_framing)
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
if __name__ == "__main__":
|
|
636
|
+
main()
|