@sage-protocol/pi-adapter
v0.2.2
Published
Sage Protocol MCP integration for pi coding agent
Readme
@sage-protocol/pi-adapter
Sage integration for the pi coding agent runtime.
Additional docs:
- Setup:
docs/setup.md - Developer guide:
docs/developer.md
It gives you:
- Sage MCP tools in pi (
sage_search,sage_execute,sage_status) - Dynamic identity context — wallet, active libraries, and skill counts injected into every turn's system prompt
- Session hook integration (
sage skill context,sage suggest hook skill) - RLM capture hooks (
sage capture hook prompt/response) - Optional pre/post tool security scanning (
sage security scan-hook)
Sage internal domains are available immediately through those tools. External MCP server lifecycle still goes through pi's hub-compat flow when needed.
Agent Profile (Dynamic Identity Context)
Every pi session automatically gets Sage Protocol identity context injected into the system prompt. The agent knows who it's working for without any configuration.
What gets injected (example):
## Sage Protocol Context
Sage Protocol is a decentralized network for collaborative prompt, skill, and knowledge
curation on Base (L2). Skills and prompts live in libraries governed by DAOs. Creators
and curators earn when their work is used. SXXX is the governance token: hold it to
vote, create DAOs, and shape the protocol. Burns from activity create deflationary
pressure — early participants gain governance influence and economic upside as the
network grows. The more skills published, the more valuable discovery becomes for every
user and agent.
### Active Identity
- Wallet: 0x9794...507ca (privy, Base Sepolia)
- Active libraries (6): sage-entrypoints, impeccable-ui-review, sage-review-foundations, ...
- Libraries: 10 installed (48 skills, 12 prompts)This makes every pi session "sage-aware" — the agent knows the active wallet, network, installed libraries, and available skill count. The context is fetched from the sage CLI (wallet current, library active, library list) and cached for 60 seconds to avoid redundant calls.
Extension mode: Identity context is appended to the system prompt on every turn via the before_agent_start hook.
SDK mode: Identity context is injected as a hook message at session start via setupHooks.
The feature is always-on when the sage CLI is available. If the CLI is missing or any query fails, the identity block is silently omitted — it never blocks the agent turn.
For model-driven patching, see packages/sage-pi-adapter/SKILL.md.
Requirements
- Node project using
@mariozechner/pi-coding-agent - Sage CLI installed and on
PATH(sage)
Choose the Right Integration Mode
There are two different scenarios:
- You own harness source code (SDK embedding with
createAgentSession) -> use this package directly. - You only run installed
piCLI (npm i -g @mariozechner/pi-coding-agent) -> install this package withpi install.
This package now ships a pi extension entrypoint, so CLI users do not need to patch harness internals.
Install
npm install @sage-protocol/pi-adapterFor pi CLI extension mode:
pi install npm:@sage-protocol/pi-adapterFor local development from this monorepo:
npm link /path/to/sage-protocol/packages/sage-pi-adapterVerify extension mode:
pi list
# should include npm:@sage-protocol/pi-adapterCI validates the packed tarball against the latest published pi CLI by running
npx @mariozechner/pi-coding-agent@latest install in an isolated HOME and local
project workspace.
pi CLI Mode (No Harness Source Changes)
After pi install npm:@sage-protocol/pi-adapter, restart pi and use it normally.
What loads automatically in extension mode:
- custom tools:
sage_search,sage_execute,sage_status - prompt hooks:
sage suggest hook skill - capture hooks:
sage capture hook prompt/response - security hooks:
sage security scan-hookon tool pre/post
Optional environment overrides:
export SAGE_BIN=sage
export SAGE_PROFILE=testnet
export SAGE_SUGGEST_LIMIT=3
export SAGE_SUGGEST_DEBOUNCE_MS=800
export SAGE_SECURITY_HOOKS=1
export SAGE_RLM_FEEDBACK=1
export SAGE_SHOW_HOOK_MESSAGES=1
export SAGE_ALLOW_BASH_CLI=0 # optional: force MCP-only routing; direct `sage ...` calls are allowed by default, and `env SAGE_ALLOW_BASH_CLI=1 sage ...` re-enables per commandManual hook command check (hook reads prompt from env/stdin, not positional args):
PROMPT="cpp libraries" SAGE_SOURCE=pi-extension sage suggest hook skill --limit 3sage suggest hook skill "cpp libraries" is expected to fail because hook mode does not accept positional query text.
Use plain query mode when testing manually without hook env:
sage suggest skill "cpp libraries"Recommended Project Config For Entrypoint Development
For a project-local pi setup where Sage owns routing and entrypoint behavior, keep pi thin and explicitly point it at the Sage Pi export surface, not the raw Sage authoring root.
Recommended .pi/settings.json shape for local monorepo development:
{
"packages": [
"../packages/sage-pi-adapter",
{
"source": "../packages/sage-pi-export",
"skills": ["skills/*/SKILL.md"],
"extensions": [],
"prompts": [],
"themes": []
},
{
"source": "npm:oh-pi",
"extensions": ["!**"]
}
],
"skills": [
"-../.agents/skills/frontend-design/SKILL.md",
"-~/.pi/agent/skills/prompt-builder/SKILL.md",
"-~/.pi/agent/skills/sage/SKILL.md",
"-~/.pi/agent/skills/sage-codebase/SKILL.md"
],
"enableSkillCommands": true
}Notes:
- Paths are relative to
.pi/settings.json, so the../packages/...layout matches this monorepo shape. - Prefer the curated
packages/sage-pi-exportsurface over broad runtime roots such as~/.local/share/sage/skills,~/.claude/skills, or~/.codex/skills. Those runtime roots often contain backups, version snapshots, and third-party skills that create noisy Pi validation errors and collisions. - Keep pi/OpenClaw as the transport and tool layer. Put routing policy and recurring entrypoint behavior in Sage skills and libraries instead of hard-coding them into the harness.
- Treat repo-authored Sage skills and entrypoint definitions as the authoring source, on-chain libraries as the shared distribution surface, and local sync as development convenience.
- A good pattern is one thin entrypoint library concept such as
sage-entrypointsthat dispatches into stable Sage-owned dependency libraries by key instead of duplicating their bodies. - For example, an entrypoint layer can route into
code-review,ceo-plan-review, orvc-office-hoursfrom a stable dependency surface such assage-review-foundationswithout embedding those skill bodies in the adapter or local config. packages/sage/pi-export.manifest.jsonis the source of truth for what Pi sees by default.node scripts/util/sync-sage-pi-export.mjsmaterializes that manifest intopackages/sage-pi-export/skills/as symlinks to the real Sage-authored skills.- If another plugin or harness layer also injects context automatically, avoid double-injection. Pick one place to do prompt/context steering.
Harness Integration (Recommended)
import { createAgentSession, createCodingTools } from '@mariozechner/pi-coding-agent';
import { createSageSessionConfig } from '@sage-protocol/pi-adapter';
export async function createSessionWithSage(model: any, cwd = process.cwd()) {
const sage = await createSageSessionConfig({
sageBin: 'sage',
source: 'pi-agent-core',
suggestLimit: 3,
enableRlmFeedback: true,
enableSecurityHooks: true,
});
const { session } = await createAgentSession({
model,
tools: sage.wrapToolsWithSecurity(createCodingTools(cwd)),
customTools: sage.customTools,
});
const disposeSageHooks = sage.setupHooks(session);
return {
session,
dispose: async () => {
disposeSageHooks();
await sage.mcpBridge.stop();
},
};
}Integrate Into an Existing Harness (Model-Directed)
If this package is on npm, you can ask a coding model to patch your harness directly.
Important: make sure the model is operating in the harness repository (for example pi-mono), not in sage-protocol/packages/sage-pi-adapter.
Preflight checks to include in your instruction:
npm view @sage-protocol/pi-adapter version
npm config get registryUse this instruction block as-is:
Install @sage-protocol/pi-adapter and patch the session bootstrap to:
1) create const sage = await createSageSessionConfig(...)
2) set customTools: sage.customTools
3) wrap base tools with tools: sage.wrapToolsWithSecurity(existingTools)
4) call const disposeSageHooks = sage.setupHooks(session) after createAgentSession
5) call disposeSageHooks() during teardown
6) keep existing model/provider/settings behavior unchanged
7) if current workspace is not the harness repo, switch to it first and patch thereHelpful search targets for the model:
rg "createAgentSession|createCodingTools|customTools|tools:" src
rg "dispose|shutdown|teardown|cleanup" src
rg "createAgentSession|createCodingTools|customTools|tools:" packages/coding-agent
rg "dispose|shutdown|teardown|cleanup" packages/coding-agentTypical patch shape:
import { createSageSessionConfig } from '@sage-protocol/pi-adapter';
const sage = await createSageSessionConfig({
source: 'pi-agent-core',
enableSecurityHooks: true,
enableRlmFeedback: true,
});
const { session } = await createAgentSession({
...existingConfig,
tools: sage.wrapToolsWithSecurity(existingTools),
customTools: sage.customTools,
});
const disposeSageHooks = sage.setupHooks(session);
// on shutdown: disposeSageHooks()Plugin Pattern
If your harness has a plugin/bootstrap layer, wire Sage there:
- Construct config with
createSageSessionConfig(...) - Add
customTools: sage.customTools - Wrap existing tools with
sage.wrapToolsWithSecurity(...) - Call
const dispose = sage.setupHooks(session)after session creation - Call
dispose()during teardown (and optionallysage.mcpBridge.stop())
If your harness uses a plugin registry, expose Sage as one plugin:
export async function setupSagePlugin(runtime: {
makeSession: (config: any) => Promise<{ session: any }>;
tools: any[];
model: any;
}) {
const sage = await createSageSessionConfig({ source: 'pi-agent-core' });
const { session } = await runtime.makeSession({
model: runtime.model,
tools: sage.wrapToolsWithSecurity(runtime.tools),
customTools: sage.customTools,
});
const disposeSageHooks = sage.setupHooks(session);
return {
session,
dispose: async () => {
disposeSageHooks();
await sage.mcpBridge.stop();
},
};
}API Summary
createSageSessionConfig(config) returns:
{
customTools: ToolDefinition[];
mcpBridge: SageMcpBridge;
setupHooks: (session: AgentSession) => () => void;
wrapToolsWithSecurity: (tools: ToolDefinition[]) => ToolDefinition[];
}Config shape:
interface SageP2Config {
sageBin?: string;
sageProfile?: string;
suggestLimit?: number;
suggestDebounceMs?: number;
timeoutMs?: number;
enableProvision?: boolean;
enableRlmFeedback?: boolean;
enableSecurityHooks?: boolean;
source?: string;
env?: Record<string, string>;
}Validate
npm run build
npm testLicense
MIT
