module-development
Guide for creating new Amplifier modules including protocol implementation, entry points, mount functions, and testing patterns. Use when creating new modules or understanding module architecture.
- License 许可
- MIT
- 最近更新
- 2026-11-12
- Stars
- ★ 12
- Forks
- 11
01 前言 Front Matter
- name
- module-development
- license
- MIT
- version
- 1.0.0
- metadata
- { "category": "development", "complexity": "medium" }
- description
- Guide for creating new Amplifier modules including protocol implementation, entry points, mount functions, and testing patterns. Use when creating new modules or understanding module architecture.
02 资源文件 1
- 参考文档checklists/wcag-checklist.md16.0 KB
03 SKILL.md 正文
Module Development Guide
Creating a New Module
Step 1: Choose Protocol
Determine which protocol your module implements:
- Tool: Agent capability (filesystem, bash, web, database)
- Provider: LLM backend (Anthropic, OpenAI, Ollama)
- Context: Conversation state management (simple, persistent)
- Orchestrator: Execution loop strategy (basic, streaming, events)
- Hook: Lifecycle observer (logging, approval, redaction)
Step 2: Implement Protocol
from typing import Any
from amplifier_core import ModuleCoordinator, ToolResult
class MyTool:
"""Tool for doing something useful."""
name = "my-tool"
description = "Does something useful"
def __init__(self: "MyTool", config: dict[str, Any]) -> None:
"""Initialize tool with configuration."""
self.config = config
self.timeout = config.get("timeout", 30)
@property
def input_schema(self: "MyTool") -> dict:
"""Return JSON schema for tool parameters."""
return {
"type": "object",
"properties": {
"param": {"type": "string", "description": "Parameter description"}
},
"required": ["param"]
}
async def execute(self: "MyTool", input: dict[str, Any]) -> ToolResult:
"""Execute tool operation."""
param = input.get("param")
if not param:
return ToolResult(
success=False,
error={"message": "param is required"}
)
# Implementation here
result = f"Processed: {param}"
return ToolResult(
success=True,
output={"result": result}
)
Step 3: Create Mount Function
async def mount(coordinator: ModuleCoordinator, config: dict[str, Any] | None = None) -> None:
"""
Mount the tool module.
Args:
coordinator: Module coordinator providing infrastructure
config: Module configuration from profile
Returns:
Optional cleanup function
"""
config = config or {}
tool = MyTool(config)
await coordinator.mount("tools", tool, name=tool.name)
logger.info("Mounted MyTool")
return
Step 4: Register Entry Point
# pyproject.toml
[project]
name = "amplifier-module-tool-mytool"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"amplifier-core",
]
[project.entry-points."amplifier.modules"]
tool-mytool = "amplifier_module_tool_mytool:mount"
[tool.uv.sources]
amplifier-core = { path = "../amplifier-core", editable = true }
Module Structure
Required files:
amplifier-module-tool-mytool/
├── amplifier_module_tool_mytool/
│ ├── __init__.py # mount() + tool class
│ └── (optional modules)
├── tests/
│ └── test_mytool.py
├── pyproject.toml
├── Makefile
└── README.md
Using Coordinator Infrastructure
The coordinator provides infrastructure context:
async def mount(coordinator: ModuleCoordinator, config: dict[str, Any] | None = None) -> None:
# Access infrastructure
session_id = coordinator.session_id # Current session
parent_id = coordinator.parent_id # Parent session (if child)
session_config = coordinator.config # Full session configuration
loader = coordinator.loader # Dynamic module loading
# Emit events
await coordinator.hooks.emit("module:mounted", {
"module_type": "tool",
"module_name": "my-tool"
})
# Register capabilities (optional)
coordinator.register_capability("my-tool.version", "1.0.0")
# Register cleanup (optional)
async def cleanup():
logger.info("Cleaning up MyTool")
coordinator.register_cleanup(cleanup)
Testing Modules
Use TestCoordinator:
import pytest
from amplifier_core.testing import TestCoordinator
from amplifier_module_tool_mytool import mount
@pytest.mark.asyncio
async def test_tool_execution():
coordinator = TestCoordinator()
# Mount module
await mount(coordinator, {"timeout": 10})
# Get tool
tool = coordinator.get("tools", "my-tool")
assert tool is not None
# Execute
result = await tool.execute({"param": "test"})
assert result.success
assert "Processed: test" in result.output["result"]
Common Patterns
Configuration Handling
class MyTool:
def __init__(self: "MyTool", config: dict[str, Any]) -> None:
# Required config
self.required = config.get("required_param")
if not self.required:
raise ValueError("required_param must be provided")
# Optional config with defaults
self.timeout = config.get("timeout", 30)
self.retries = config.get("retries", 3)
Event Emission
async def execute(self: "MyTool", input: dict[str, Any]) -> ToolResult:
# Events emitted by orchestrator via hooks, not by tools directly
# Tools just return results
result = await self._process(input)
return ToolResult(success=True, output=result)
Error Patterns
# Return error, don't raise
return ToolResult(
success=False,
error={"message": "Clear error message", "code": "ERROR_CODE"}
)
# Log for debugging
logger.error(f"Failed to process {input}: {e}")
return ToolResult(success=False, error={"message": str(e)})
Remember
- One responsibility per module - Don't create mega-modules
- Config via mount() - No hard-coded defaults in modules
- Async everywhere - All I/O must be async
- Protocols not inheritance - Implement interface, don't inherit
- Test at protocol level - Test behavior, not internals
04 同仓库更多 Skills
verification-discipline
Use when verifying that completed work actually works. Auto-surface during /verify mode, post-implementation review, or before claiming a task is done. Teaches testing outcomes vs implementation, the unit/integration/smoke gradient, and what "done" actually means.
user-advocate
User-need reviewer that speaks for the person who isn't in the room — the one who will actually live with what gets built. Hunts the gap between "we can build this" and "they actually want this," in the patient, impatient voice of the absent user. Use at any checkpoint — brainstorm, design, plan, implement, debug, review — when a feature is being built because it's buildable rather than wanted, the recovery path is missing, or nobody can name the person this serves: "do they actually want this, and can they live with it?"
tester-breaker
Adversarial breaker that reviews code by trying to make it fail, not by confirming it works. Hunts the unhappy paths — malformed input, the empty string, the reversed range, the race condition — as a gleeful adversary who assumes everything is broken until a concrete attempt to break it comes up empty. Use at any checkpoint — brainstorm, design, plan, implement, debug, review — when the happy path is celebrated while the edges sit unexamined, "looks fine" stands in for "I tried to break it and couldn't," or nobody has named the input that makes this fall over: "how does this fail, and where are the edges?"
skills-assist
Authoritative consultant for all skills-related questions. Use when creating or modifying skills, understanding the Agent Skills spec, troubleshooting skill loading or invocation issues, leveraging enhanced format features (context fork, model_role, user-invocable), writing cross-harness portable skills, ensuring Claude Code Skills 2.0 compatibility, or deciding between skills vs agents.
skillify
Capture a repeatable process from the current session into a reusable Amplifier SKILL.md skill file. Use when the user wants to create a skill, save a workflow as a skill, turn a process into a reusable skill, or mentions "skillify", "create skill", "make a skill", "save as skill", "capture workflow", "turn this into a skill", "new skill", or wants to automate a repeatable process they just performed.
session-debug
Diagnose issues in the current Amplifier session — misconfigured tools, failing operations, unexpected behavior. Use when something isn't working right.