Coverage for src/romfarmer/mcp/farmhand_skills.py: 0%
111 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""MCP tools for Farm-Hand skill system.
3Exposes skill search, display, capture, and artifact management
4as MCP tools for AI agent-driven workflows.
5"""
7from __future__ import annotations
9import logging
10from pathlib import Path
11from typing import Any
13logger = logging.getLogger(__name__)
15# Module-level recorder — persists across tool calls in a session
16_active_recorder: Any | None = None
19def _get_workspace_root() -> Path:
20 from romfarmer.core.paths import get_paths
22 return get_paths().workspace_root
25def _get_store() -> Any:
26 from romfarmer.farmhand.skills import SkillStore
28 return SkillStore(workspace_root=_get_workspace_root())
31# ---------------------------------------------------------------------------
32# Tool: farmhand_skill_search
33# ---------------------------------------------------------------------------
36async def tool_farmhand_skill_search(
37 query: str = "",
38 category: str = "",
39 tag: str = "",
40 platform: str = "",
41 target: str = "",
42) -> dict[str, Any]:
43 """Search the skill library. Returns matching skills with summaries.
45 Combine query text with filters. All filters are AND-combined.
46 """
47 from romfarmer.farmhand.skills import SkillCategory
49 store = _get_store()
50 results = store.search(
51 query=query or None,
52 category=SkillCategory(category) if category else None,
53 tags=[tag] if tag else None,
54 platform=platform or None,
55 target=target or None,
56 )
58 return {
59 "count": len(results),
60 "skills": [
61 {
62 "name": s.meta.name,
63 "description": s.meta.description,
64 "category": s.meta.category.value,
65 "version": s.meta.version,
66 "tags": s.meta.tags,
67 "platforms": s.meta.platforms,
68 "targets": s.meta.targets,
69 "has_procedure": s.has_procedure,
70 "artifact_count": len(s.meta.artifacts),
71 "is_builtin": s.is_builtin,
72 }
73 for s in results
74 ],
75 }
78# ---------------------------------------------------------------------------
79# Tool: farmhand_skill_show
80# ---------------------------------------------------------------------------
83async def tool_farmhand_skill_show(name: str) -> dict[str, Any]:
84 """Get full details of a skill including procedure steps and body.
86 Returns everything needed to understand and execute the skill.
87 """
88 store = _get_store()
89 skill = store.get(name)
91 if not skill:
92 return {"error": f"Skill '{name}' not found"}
94 meta = skill.meta
95 result: dict[str, Any] = {
96 "name": meta.name,
97 "description": meta.description,
98 "version": meta.version,
99 "category": meta.category.value,
100 "author": meta.author,
101 "created": str(meta.created.date()),
102 "updated": str(meta.updated.date()),
103 "tags": meta.tags,
104 "platforms": meta.platforms,
105 "targets": meta.targets,
106 "tools_used": meta.tools_used,
107 "preconditions": meta.preconditions,
108 "is_builtin": skill.is_builtin,
109 "body": skill.body,
110 }
112 if meta.params:
113 result["params"] = [
114 {
115 "name": p.name,
116 "type": p.type,
117 "description": p.description,
118 "required": p.required,
119 "default": p.default,
120 "enum": p.enum,
121 }
122 for p in meta.params
123 ]
125 if meta.artifacts:
126 result["artifacts"] = [
127 {
128 "filename": a.filename,
129 "description": a.description,
130 "artifact_type": a.artifact_type,
131 "executable": a.executable,
132 }
133 for a in meta.artifacts
134 ]
136 if skill.steps:
137 result["procedure_steps"] = [
138 {
139 "id": step.id,
140 "description": step.description,
141 "action": step.action.value,
142 "tool": step.tool,
143 "command": step.command,
144 "args": step.args,
145 "condition": step.condition,
146 "on_failure": step.on_failure,
147 }
148 for step in skill.steps
149 ]
151 return result
154# ---------------------------------------------------------------------------
155# Tool: farmhand_skill_artifact
156# ---------------------------------------------------------------------------
159async def tool_farmhand_skill_artifact(skill_name: str, filename: str) -> dict[str, Any]:
160 """Retrieve the contents of an artifact file from a skill.
162 Use this to read scripts, game lists, configs, etc. bundled in skills.
163 """
164 store = _get_store()
165 skill = store.get(skill_name)
167 if not skill:
168 return {"error": f"Skill '{skill_name}' not found"}
170 content = store.get_artifact_content(skill_name, filename)
171 if content is None:
172 available = [a.filename for a in skill.meta.artifacts]
173 return {
174 "error": f"Artifact '{filename}' not found in skill '{skill_name}'",
175 "available_artifacts": available,
176 }
178 return {
179 "skill": skill_name,
180 "filename": filename,
181 "content": content,
182 }
185# ---------------------------------------------------------------------------
186# Tool: farmhand_skill_save
187# ---------------------------------------------------------------------------
190async def tool_farmhand_skill_save(
191 name: str,
192 description: str,
193 category: str,
194 body: str = "",
195 tags: str = "",
196 platforms: str = "",
197 targets: str = "",
198 tools_used: str = "",
199 preconditions: str = "",
200) -> dict[str, Any]:
201 """Create or update a user skill from explicit parameters.
203 Use this when the agent wants to persist a skill directly rather
204 than through the capture workflow.
206 Comma-separated strings for tags, platforms, targets, tools_used, preconditions.
207 """
208 from romfarmer.farmhand.skills import Skill, SkillCategory, SkillMeta
210 try:
211 meta = SkillMeta(
212 name=name,
213 description=description,
214 category=SkillCategory(category),
215 tags=[t.strip() for t in tags.split(",") if t.strip()] if tags else [],
216 platforms=[p.strip() for p in platforms.split(",") if p.strip()] if platforms else [],
217 targets=[t.strip() for t in targets.split(",") if t.strip()] if targets else [],
218 tools_used=[t.strip() for t in tools_used.split(",") if t.strip()]
219 if tools_used
220 else [],
221 preconditions=[p.strip() for p in preconditions.split(",") if p.strip()]
222 if preconditions
223 else [],
224 )
226 skill = Skill(meta=meta, body=body, steps=[], is_builtin=False)
228 store = _get_store()
229 store.save(skill)
231 return {
232 "saved": True,
233 "name": name,
234 "category": category,
235 "message": f"Skill '{name}' saved successfully.",
236 }
237 except Exception as exc:
238 return {"error": str(exc)}
241# ---------------------------------------------------------------------------
242# Tool: farmhand_skill_save_artifact
243# ---------------------------------------------------------------------------
246async def tool_farmhand_skill_save_artifact(
247 skill_name: str,
248 filename: str,
249 content: str,
250 description: str = "",
251 artifact_type: str = "script",
252 executable: bool = False,
253) -> dict[str, Any]:
254 """Save an artifact file to a user skill.
256 Creates the skill directory if needed. The artifact is stored as a plain
257 file alongside the SKILL.md. Also updates the skill metadata.
258 """
259 store = _get_store()
260 skill = store.get(skill_name)
262 if skill and skill.is_builtin:
263 return {"error": f"Cannot add artifacts to builtin skill '{skill_name}'"}
265 try:
266 store.save_artifact(skill_name, filename, content, executable=executable)
268 # If the skill exists, update its artifact list in metadata
269 if skill:
270 from romfarmer.farmhand.skills import SkillArtifact
272 existing_filenames = {a.filename for a in skill.meta.artifacts}
273 if filename not in existing_filenames:
274 skill.meta.artifacts.append(
275 SkillArtifact(
276 filename=filename,
277 description=description,
278 artifact_type=artifact_type,
279 executable=executable,
280 )
281 )
282 store.save(skill)
284 return {
285 "saved": True,
286 "skill": skill_name,
287 "filename": filename,
288 "message": f"Artifact '{filename}' saved to skill '{skill_name}'.",
289 }
290 except Exception as exc:
291 return {"error": str(exc)}
294# ---------------------------------------------------------------------------
295# Tool: farmhand_skill_capture_start
296# ---------------------------------------------------------------------------
299async def tool_farmhand_skill_capture_start(
300 task_description: str,
301) -> dict[str, Any]:
302 """Begin recording agent actions for skill auto-capture.
304 Call this when starting a workflow you want to save as a reusable skill.
305 Then call farmhand_skill_capture_step for each significant action.
306 Finally call farmhand_skill_capture_finish to save the skill.
308 Only one recording can be active at a time.
309 """
310 global _active_recorder
312 from romfarmer.farmhand.skills.capture import SkillRecorder
314 if _active_recorder is not None and _active_recorder.is_active:
315 return {
316 "error": "A recording is already active. Finish or cancel it first.",
317 "step_count": _active_recorder.step_count,
318 }
320 _active_recorder = SkillRecorder()
321 _active_recorder.start(task_description)
323 return {
324 "recording": True,
325 "task": task_description,
326 "message": "Recording started. Use farmhand_skill_capture_step for each action.",
327 }
330# ---------------------------------------------------------------------------
331# Tool: farmhand_skill_capture_step
332# ---------------------------------------------------------------------------
335async def tool_farmhand_skill_capture_step(
336 action: str,
337 description: str = "",
338 tool: str = "",
339 command: str = "",
340 args: str = "",
341 result: str = "",
342 success: bool = True,
343) -> dict[str, Any]:
344 """Record a step in the active skill capture session.
346 Parameters
347 ----------
348 action
349 Step type: mcp_call, shell, ssh, python, decision
350 description
351 What this step does
352 tool
353 Tool/function name (for mcp_call)
354 command
355 Shell command (for shell/ssh)
356 args
357 JSON-encoded arguments dict
358 result
359 Brief result/output summary
360 success
361 Whether the step succeeded
362 """
363 global _active_recorder
365 if _active_recorder is None or not _active_recorder.is_active:
366 return {"error": "No active recording. Call farmhand_skill_capture_start first."}
368 import json as json_mod
370 parsed_args = {}
371 if args:
372 try:
373 parsed_args = json_mod.loads(args)
374 except json_mod.JSONDecodeError:
375 parsed_args = {"raw": args}
377 _active_recorder.record_step(
378 action=action,
379 description=description,
380 tool=tool,
381 command=command,
382 args=parsed_args,
383 result=result,
384 success=success,
385 )
387 return {
388 "recorded": True,
389 "step_count": _active_recorder.step_count,
390 "action": action,
391 }
394# ---------------------------------------------------------------------------
395# Tool: farmhand_skill_capture_finish
396# ---------------------------------------------------------------------------
399async def tool_farmhand_skill_capture_finish(
400 name: str,
401 description: str = "",
402 category: str = "workflow",
403 tags: str = "",
404 platforms: str = "",
405 targets: str = "",
406 save: bool = True,
407) -> dict[str, Any]:
408 """Finish recording and optionally save the captured skill.
410 Converts the recorded steps into a Skill with SKILL.md and procedure.yaml,
411 then saves it to the user skill directory.
413 Parameters
414 ----------
415 name
416 Skill name (slug format: lowercase, hyphens)
417 description
418 Override description (default: auto-generated from task)
419 category
420 Skill category
421 tags
422 Comma-separated tags
423 platforms, targets
424 Comma-separated platform/target filters
425 save
426 Whether to save immediately (default: True)
427 """
428 global _active_recorder
430 if _active_recorder is None or not _active_recorder.is_active:
431 return {"error": "No active recording to finish."}
433 from romfarmer.farmhand.skills import SkillCategory
435 try:
436 skill = _active_recorder.capture(
437 name=name,
438 description=description or None,
439 category=SkillCategory(category),
440 tags=[t.strip() for t in tags.split(",") if t.strip()] if tags else None,
441 platforms=[p.strip() for p in platforms.split(",") if p.strip()] if platforms else None,
442 targets=[t.strip() for t in targets.split(",") if t.strip()] if targets else None,
443 )
445 result: dict[str, Any] = {
446 "captured": True,
447 "name": skill.meta.name,
448 "description": skill.meta.description,
449 "category": skill.meta.category.value,
450 "step_count": len(skill.steps),
451 "param_count": len(skill.meta.params),
452 }
454 if save:
455 store = _get_store()
456 store.save(skill)
457 result["saved"] = True
458 result["message"] = f"Skill '{name}' captured and saved ({len(skill.steps)} steps)."
459 else:
460 result["saved"] = False
461 result["message"] = f"Skill '{name}' captured but not saved."
463 _active_recorder = None
464 return result
465 except Exception as exc:
466 return {"error": str(exc)}
469# ---------------------------------------------------------------------------
470# Tool: farmhand_skill_capture_cancel
471# ---------------------------------------------------------------------------
474async def tool_farmhand_skill_capture_cancel() -> dict[str, Any]:
475 """Cancel the active skill capture session without saving."""
476 global _active_recorder
478 if _active_recorder is None or not _active_recorder.is_active:
479 return {"error": "No active recording to cancel."}
481 steps = _active_recorder.step_count
482 _active_recorder.cancel()
483 _active_recorder = None
485 return {
486 "cancelled": True,
487 "steps_discarded": steps,
488 "message": "Recording cancelled.",
489 }