How to Integrate PrimeAgent with Other Systems: 6 Integration Methods Explained

PrimeAgent integrates with external systems through six composable interfaces: JSON mode for shell pipelines, RPC mode for service architecture, MCP integrations for external APIs, sub-agents for hierarchical tasks, a TypeScript SDK for programmatic embedding, and CLI commands for automation workflows.

PrimeAgent is architected around modular abstractions that enable seamless integration with diverse tools, services, and automation pipelines. Whether you need a headless CI component, a long-running service backend, or a recursive agent swarm, the PrimeIntellect-ai/prime-agent repository provides purpose-built integration points grounded in its daemon-worker-kernel architecture.

JSON Mode: Line-Oriented Protocol for Shell Integration

JSON mode emits a deterministic stream of newline-delimited JSON messages through standard I/O channels. This design makes PrimeAgent immediately compatible with Unix pipes, CI systems, and any runtime capable of parsing stdin/stdout.

Message Types

Each line is a JSON object with a type field:

  • event — lifecycle notifications (start, stop, error)
  • assistant — generated responses from the language model
  • tool_use — tool invocation requests with arguments
  • tool_result — execution output from completed tools

Shell Pipeline Example

#!/usr/bin/env bash

# Extract only assistant responses from a PrimeAgent session

prime-agent --json "Analyze this codebase for security issues" \
  | jq -r 'select(.type == "assistant") | .content'

The --json flag forces deterministic output with no TUI rendering, as documented in [packages/coding-agent/docs/json.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/json.md). This mode requires no daemon—each invocation spawns an ephemeral agent that terminates after completion.

RPC Mode: Socket-Based Service Integration

RPC mode starts a persistent JSON-RPC server (default localhost:4444) that supports bidirectional communication. Unlike JSON mode's one-shot execution, RPC maintains session state across multiple client connections.

Core RPC Methods

Method Purpose
/run Execute a prompt and stream events
/refine Continue an existing conversation thread
/heartbeat Verify daemon connectivity
/attach Reconnect to a persisted session

Node.js RPC Client Example

import { createAgent } from '@primeintellect/prime-agent';

const agent = await createAgent({ rpcUrl: 'http://localhost:4444' });

const { events } = await agent.run({
  prompt: "Refactor this function to use async/await",
  sessionId: 'my-persistent-session'
});

for await (const event of events) {
  if (event.type === 'tool_use') {
    console.log(`Tool: ${event.name}(${JSON.stringify(event.arguments)})`);
  }
}

The SDK in [packages/coding-agent/src/core/sdk.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/sdk.ts) abstracts transport details, handling reconnection, backpressure, and event buffering automatically. For raw protocol details, see [packages/coding-agent/docs/rpc.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/rpc.md).

MCP Integrations: External API as Agent Skills

Modular Capability Provider (MCP) integrations wrap external services (GitHub, Jira, cloud providers) as discoverable agent tools. Each integration is a Python package that subclasses McpIntegration from [prime-agent-runtime/src/rlm/mcp_base.py](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/prime-agent-runtime/src/rlm/mcp_base.py).

Integration Structure

from rlm.mcp_base import McpIntegration

class GitHubIntegration(McpIntegration):
    PROVIDER = "github"
    CONFIG = {
        "type": "http",
        "base_url": "https://api.github.com",
        "auth_type": "oauth"
    }

    async def create_issue(self, repo: str, title: str, body: str) -> dict:
        """Create a GitHub issue—exposed to agent as /github create_issue"""
        return await self.request(
            "POST", 
            f"/repos/{repo}/issues",
            json={"title": title, "body": body}
        )

Once registered, the agent invokes these skills through standard tool-use semantics:


[tool_use] name="github/create_issue" arguments={"repo": "PrimeIntellect-ai/prime-agent", ...}

The host gatekeeps availability through OAuth scopes defined in the integration's CONFIG. See [packages/coding-agent/docs/mcp-integrations.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/mcp-integrations.md) for packaging and distribution guidelines.

Sub-Agents: Recursive Agent Orchestration

Recursive Language Model (RLM) agents enable hierarchical task decomposition. The rlm() function spawns isolated sandboxed agents that execute in separate Python REPLs, with full parent-child communication.

Sub-Agent Invocation Patterns


# Inside a PrimeAgent session

# Pattern 1: Fire-and-collect result

research = rlm("""
  You are a focused research agent. Find 3 recent papers on LLM efficiency.
  Return only URLs and key metrics in JSON.
""")

# Pattern 2: Parallel sub-agents for map-reduce

tasks = ["Summarize section A", "Summarize section B", "Synthesize findings"]
results = [rlm(t) for t in tasks]  # Concurrent execution

# Pattern 3: Stateful sub-agent with message passing

child = rlm("Initialize long-running document processor", persistent=True)
child.send("Process file: report.pdf")
status = child.receive(timeout=30)

Each sub-agent maintains independent tool access and can itself spawn further descendants. The parent awaits completion or polls via message passing, as detailed in [packages/coding-agent/docs/rlm.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/rlm.md). This pattern implements the "agent-as-service" architecture for complex workflows.

TypeScript SDK: Programmatic Embedding

The official TypeScript SDK wraps all protocol variants (JSON, RPC, hybrid) with type-safe abstractions for Node.js applications.

SDK Installation and Usage

npm install @primeintellect/prime-agent
import { createAgent, AgentConfig } from '@primeintellect/prime-agent';

const config: AgentConfig = {
  mode: 'rpc',           // or 'json' for stateless
  rpcUrl: process.env.PRIME_AGENT_RPC_URL,
  provider: 'anthropic', // LLM backend selection
  tools: ['shell', 'file', 'github'] // Filter available tools
};

const agent = await createAgent(config);

// Event-driven interaction
agent.on('tool_use', ({ name, arguments }) => {
  auditLog.record({ tool: name, args: arguments });
});

const result = await agent.run({
  prompt: "Deploy the staging environment",
  maxIterations: 50  // Safety limit
});

The SDK source in [packages/coding-agent/src/core/sdk.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/sdk.ts) exposes attach(), refine(), and streaming variants for all operations. Type definitions are generated from the daemon's OpenRPC schema.

CLI Commands: Automation Interface

The PrimeAgent CLI provides a uniform surface for scripting and orchestration. Commands are parsed in [packages/coding-agent/src/cli/args.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/cli/args.ts).

Essential Commands for Integration


# Daemon lifecycle

prime-agent daemon --rpc-port 4444 &

# Session management

prime-agent start my-analysis-project
prime-agent attach my-analysis-project --json "Complete partial task"

# Agent inspection

prime-agent status          # Daemon health

prime-agent agents          # List active sessions

prime-agent logs <session>  # Stream historical events

# Custom slash commands (available in attached sessions)

prime-agent attach my-project

# Then interactively: /refine, /goal, /heartbeat, /tools

Slash commands like /refine and /goal are implemented as RPC calls with structured parsing. The --json flag on any command forces machine-parseable output.

Architecture: How Integration Points Connect

Understanding the runtime layers clarifies when to use each integration method.

Layer Responsibility Integration Relevance
Daemon Persistent Node.js process, socket management RPC server lifetime, session persistence
Worker Message routing, protocol translation JSON/RPC → internal event bus
Kernel Python REPL, tool execution, sub-agent spawning Actual code execution, MCP skill dispatch

State persists in the Continual Harness (documented in [packages/coding-agent/docs/architecture.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/architecture.md)), enabling re-attachment across client disconnections. When a tool executes—whether triggered by RPC, JSON, or SDK—the kernel captures output identically and streams tool_result events.

Choosing the Right Integration Pattern

Scenario Recommended Method Key File
CI/CD pipeline step JSON mode [docs/json.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/json.md)
Web service backend RPC mode + SDK [src/core/sdk.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/sdk.ts)
External API access MCP integration [mcp_base.py](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/prime-agent-runtime/src/rlm/mcp_base.py)
Parallel sub-tasks RLM sub-agents [docs/rlm.md](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/rlm.md)
Scheduled automation CLI + cron/systemd [src/cli/args.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/cli/args.ts)
Embedded application TypeScript SDK [src/core/sdk.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/sdk.ts)

Summary

  • JSON mode provides stateless, pipe-friendly integration for shell scripts and CI systems through deterministic stdout streaming.

  • RPC mode enables long-running service architecture with bidirectional communication over local sockets.

  • MCP integrations externalize third-party APIs as native agent skills through Python subclassing of McpIntegration.

  • RLM sub-agents implement hierarchical task decomposition with isolated execution environments and parent-child messaging.

  • TypeScript SDK offers type-safe programmatic access from Node.js applications with unified abstraction over all protocol variants.

  • CLI commands expose complete functionality for automation scripting, with machine-parseable output via --json.

Frequently Asked Questions

How do I maintain session state across PrimeAgent restarts?

Sessions persist automatically in the Continual Harness. Start with prime-agent start <name>, then re-attach later with prime-agent attach <name>. The daemon stores message history, file system state, and sub-agent relationships in its working directory.

Can I restrict which tools an integration can access?

Yes. MCP integrations declare required capabilities in their CONFIG dict. The host enforces these at registration time. Additionally, SDK users can pass tools: ['subset'] to createAgent() to whitelist specific tools for that session.

What is the performance overhead of RLM sub-agents?

Each sub-agent spawns a fresh Python kernel (~50-100MB RAM baseline). Sub-agents execute concurrently via asyncio, but kernel startup latency is ~500ms. For high-frequency operations, prefer persistent sub-agents with persistent=True over repeated rlm() calls.

How do I add support for a new LLM provider?

Extend the provider interface in packages/ai/src/providers/ following the pattern in [openai-completions.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/ai/src/providers/openai-completions.ts), then register it in register-builtins.ts. Restart the daemon to pick up the new provider.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →