How to Integrate Prime-Agent with Other Tools: 3 Methods Explained
Prime-Agent from PrimeIntellect-ai/prime-agent integrates with external tools through JSON event-stream mode, RPC mode, or the Node.js/TypeScript library, giving you lightweight automation, full-duplex programmatic control, or native in-process API access.
Prime-Agent is an extensible AI coding agent that offers multiple integration paths for embedding its capabilities into your own applications, pipelines, and services. Whether you need quick shell scripting, real-time interactive control, or tight TypeScript integration, the same core engine powers all three approaches according to the PrimeIntellect-ai/prime-agent source code. This guide walks through each integration method with complete code examples and references to the actual implementation files.
JSON Event-Stream Mode: Lightweight Line-Delimited Integration
The JSON event-stream mode is the simplest way to integrate Prime-Agent. Run the CLI with --mode json and every session event becomes a line-delimited JSON record on stdout. Commands are read from stdin using the same format.
This approach requires no libraries—just any tool that can pipe JSON lines. It excels in CI pipelines, shell scripts, and language-agnostic automation.
Basic JSON Mode Usage
# Stream results and extract final assistant message
prime-agent --mode json "List all TypeScript files" \
| jq -c 'select(.type=="message_end") | .message.content[]?.text'
The command passes the prompt directly on the command line. The jq filter selects only message_end events and extracts the text content.
Sending Commands via Stdin
You can also feed JSON commands to trigger specific tools:
echo '{
"type":"bash",
"command":"git status"
}' | prime-agent --mode json --no-session
All event types—agent_start, message_update, tool_execution_end, and more—are documented in packages/coding-agent/docs/json.md according to the PrimeIntellect-ai/prime-agent source code.
RPC Mode: Full-Duplex Programmatic Control
For long-running services and interactive applications, RPC mode provides a full-duplex JSON Lines protocol over stdin/stdout. It supports commands with request/response correlation, real-time streaming of assistant messages, and a rich extension-UI sub-protocol for dialogs and confirmations.
Starting RPC Mode
prime-agent --mode rpc --no-session
The client sends command objects (e.g., prompt, bash, set_model) with optional id fields for correlation. While processing, the agent streams events on stdout with the same shape as JSON mode, as defined in packages/coding-agent/docs/rpc.md.
Python RPC Client Example
import subprocess, json, sys
proc = subprocess.Popen(
["prime-agent", "--mode", "rpc", "--no-session"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True
)
def send(cmd):
proc.stdin.write(json.dumps(cmd) + "\n")
proc.stdin.flush()
def read_events():
for line in proc.stdout:
yield json.loads(line)
# Send a prompt
send({"type": "prompt", "message": "Explain the Fibonacci sequence"})
# Print streamed text deltas
for ev in read_events():
if ev.get("type") == "message_update":
delta = ev.get("assistantMessageEvent", {})
if delta.get("type") == "text_delta":
sys.stdout.write(delta["delta"])
sys.stdout.flush()
if ev.get("type") == "agent_end":
print()
break
This minimal client demonstrates prompt sending, streaming text extraction, and graceful termination detection.
Node.js RPC Client with Stream-Safe Reader
const { spawn } = require("child_process");
const { StringDecoder } = require("string_decoder");
const agent = spawn("prime-agent", ["--mode", "rpc", "--no-session"]);
function attachJsonlReader(stream, onLine) {
const decoder = new StringDecoder("utf8");
let buf = "";
stream.on("data", chunk => {
buf += typeof chunk === "string" ? chunk : decoder.write(chunk);
while (true) {
const i = buf.indexOf("\n");
if (i === -1) break;
let line = buf.slice(0, i);
buf = buf.slice(i + 1);
if (line.endsWith("\r")) line = line.slice(0, -1);
onLine(line);
}
});
stream.on("end", () => {
buf += decoder.end();
if (buf) onLine(buf.endsWith("\r") ? buf.slice(0, -1) : buf);
});
}
// Print streamed text deltas
attachJsonlReader(agent.stdout, line => {
const ev = JSON.parse(line);
if (ev.type === "message_update" &&
ev.assistantMessageEvent?.type === "text_delta") {
process.stdout.write(ev.assistantMessageEvent.delta);
}
});
// Send a prompt
agent.stdin.write(JSON.stringify({ type: "prompt", message: "List files" }) + "\n");
// Graceful abort on Ctrl-C
process.on("SIGINT", () => agent.stdin.write(JSON.stringify({ type: "abort" }) + "\n"));
The reference implementation in packages/coding-agent/src/modes/rpc/rpc-client.ts provides a fully typed RPC client for production use.
Extension UI Protocol
RPC mode supports extension UI requests such as select, confirm, and custom dialogs. This allows your client to render native UI elements when the agent needs user input, as shown in examples/rpc-extension-ui.ts.
Node.js/TypeScript Library: Native In-Process Integration
For maximum performance and type safety, import the @earendil-works/pi-coding-agent package directly. This bypasses subprocess overhead and exposes the full AgentSession API.
Installation and Basic Usage
npm install @earendil-works/pi-coding-agent
import { AgentSession } from "@earendil-works/pi-coding-agent";
async function run() {
const session = new AgentSession({
provider: "openai",
modelId: "gpt-4o",
// optional: custom session directory, tool configurations, etc.
});
const resp = await session.prompt("Write a one-line summary of this repo");
console.log(resp.message.content.map(c => c.text).join(""));
}
run();
Advanced Library Features
The AgentSession class in packages/coding-agent/src/core/agent-session.ts exposes methods unavailable through CLI modes:
session.setThinkingLevel(level)— adjust reasoning depthsession.compact()— trigger context compactionsession.addSchedule(task)— register autonomous tasks
This direct access makes the library ideal for building native Node applications, VS Code extensions, or serverless functions where latency and type safety matter.
Extending Prime-Agent with Custom Commands
Prime-Agent's extension system lets you register custom slash commands that work across all integration modes. Extensions are TypeScript files placed in ~/.prime/agent/extensions/ or project-local ./.prime/agent/extensions/.
Creating a Custom Extension
import { pi } from "pi";
pi.registerCommand({
name: "uppercase",
description: "Upper-case the given text",
async handler(ctx, args) {
const text = args[0] ?? "";
ctx.sendMessage(text.toUpperCase());
},
});
Save as my-extension.ts, restart the agent, then invoke via any client:
{ "type": "prompt", "message": "/uppercase hello world" }
Extensions automatically become available in JSON mode, RPC mode, and the interactive TUI, as documented in packages/coding-agent/docs/rpc.md.
Skills and Packages for Tool Expansion
Beyond extensions, Prime-Agent supports skills (importable Python packages that add tool implementations) and packages (bundled npm modules). Install packages via:
prime-agent package install <source>
These can provide additional commands, tools, or UI components. The full package management workflow is documented in packages/coding-agent/docs/usage.md.
Architecture Overview
All three integration methods feed into the same pipeline, as illustrated in packages/coding-agent/docs/architecture.md:
CLI/JSON/RPC/Library → AgentConnection → Supervisor → Worker → AgentSessionRuntime (IPython kernel) → Model provider
This unified architecture ensures that model selection, tool execution, sub-agent spawning, compaction, and autonomous mode behave identically regardless of how you integrate.
Summary
- JSON event-stream mode (
--mode json) offers the fastest path to integration—pipe JSON lines for lightweight automation in any language - RPC mode (
--mode rpc) provides full-duplex control with streaming, request/response correlation, and extension UI support for interactive applications - Node.js/TypeScript library (
@earendil-works/pi-coding-agent) delivers native, type-safe API access with the lowest overhead - Extensions registered via
pi.registerCommand()work across all modes, enabling reusable custom functionality - The architecture diagram in
packages/coding-agent/docs/architecture.mdconfirms all methods share the same core engine, ensuring consistent behavior
Frequently Asked Questions
Can I integrate Prime-Agent with Python applications?
Yes. While there's no native Python library, you can spawn the CLI in JSON or RPC mode and communicate via subprocess pipes. The Python RPC client example above demonstrates streaming text deltas with under 30 lines of code. For synchronous use cases, JSON mode with subprocess.run() and jq-style filtering suffices.
How do I handle user prompts and confirmations in RPC mode?
Implement the extension UI sub-protocol. When the agent needs user input, it sends UI request events (e.g., {"type":"select","options":[...]}). Your client renders the appropriate interface, then sends the response back as a UI response command. See examples/rpc-extension-ui.ts for a complete implementation handling select, confirm, and custom input types.
What's the performance difference between RPC mode and the Node.js library?
The Node.js library eliminates subprocess overhead. In RPC mode, every message serializes through stdin/stdout pipes, adding latency proportional to JSON encoding and OS buffer handling. The AgentSession class operates in-process with direct method calls, reducing latency by roughly 1-10ms per interaction depending on payload size. For high-frequency or latency-sensitive applications, prefer the library.
Can I use Prime-Agent in CI/CD pipelines without interactive input?
Absolutely. JSON mode with --no-session is designed for this. Each invocation starts fresh, processes the provided prompt or command, streams results as JSON lines, and exits. Combine with tools like jq for filtering or xargs for batch processing. The deterministic, non-interactive behavior makes it ideal for automated testing, documentation generation, and code review workflows.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →