How to Integrate PrimeAgent with Other Tools: CLI, SDK, MCP, and Sub-Agent Patterns

PrimeAgent integrates with external tools through four modular layers: CLI modes (JSON/RPC), the Node.js SDK, MCP skill packages, and sub-agent orchestration via the rlm runtime.

PrimeAgent is built as an extensible, multi-layered platform that exposes clean integration surfaces for scripts, services, and third-party applications. Whether you need to embed agent capabilities in a CI pipeline, drive sessions programmatically from Node.js, or extend functionality through custom Python skills, the codebase provides explicit hooks in packages/coding-agent/src/cli/cli.ts, packages/coding-agent/src/core/sdk.ts, and related modules. This guide covers each integration pattern with runnable code examples drawn directly from the PrimeIntellect-ai/prime-agent source.

CLI Integration Modes: JSON and RPC

The prime-agent command supports three runtime modes controlled by the --mode flag. Two of these—json and rpc—are designed specifically for tool integration without interactive terminal UI.

JSON Mode for Scripted Automation

JSON mode streams structured events to stdout, making it ideal for shell scripts and automated pipelines. The implementation lives in packages/coding-agent/src/modes/headless-completion.ts, where the agent formats all output as newline-delimited JSON objects.

#!/usr/bin/env bash

# Run a one-off prompt and extract the generated code

prime-agent --mode json <<'EOF' | jq -r '.output'
Write a Python function that validates email addresses using regex.
EOF

Key flags for JSON mode:

  • --mode json — enables structured output
  • Events include type, output, tokenUsage, and error fields
  • Parse with jq, Python's json module, or any JSON consumer

RPC Mode for Language-Agnostic Subprocess Integration

RPC mode establishes a bidirectional JSON-RPC channel over stdin/stdout. This lets you embed PrimeAgent as a subprocess from Go, Rust, Python, or any language that can spawn processes and handle pipes.

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("prime-agent", "--mode", "rpc")
	stdin, _ := cmd.StdinPipe()
	stdout, _ := cmd.StdoutPipe()
	cmd.Start()

	// Send prompt request
	request := map[string]string{
		"type":    "prompt",
		"prompt":  "Explain the CAP theorem in one paragraph",
	}
	reqJSON, _ := json.Marshal(request)
	fmt.Fprintln(stdin, string(reqJSON))

	// Read response
	decoder := json.NewDecoder(stdout)
	var resp map[string]interface{}
	decoder.Decode(&resp)
	fmt.Println("Answer:", resp["output"])
}

The RPC protocol uses newline-delimited JSON messages. Request types include prompt, exec (for tool calls), and shutdown.

Node.js SDK: Programmatic Agent Sessions

For TypeScript and Node.js services, PrimeAgent exposes a high-level SDK through the AgentSession class in packages/coding-agent/src/core/sdk.ts. This handles session lifecycle, model selection, and daemon communication automatically.

import { AgentSession } from "prime-agent-coding-agent";

async function generateUnitTests(sourceFile: string) {
  const session = await AgentSession.create({
    model: "gpt-4o-mini",     // see `prime-agent list-models` for options
    mode: "json",             // structured events for programmatic handling
  });

  const { output, tokenUsage } = await session.runPrompt(`
    Generate Jest unit tests for the functions in ${sourceFile}.
    Include edge cases for null inputs and async errors.
  `);

  console.log(`Used ${tokenUsage.total} tokens`);
  console.log("Generated tests:\n", output);

  await session.shutdown();   // terminates daemon cleanly
}

generateUnitTests("./src/utils.ts");

SDK capabilities include:

  • session.runPrompt(prompt, options) — single-turn generation with optional system prompts
  • session.exec(command) — execute shell commands through the agent's tool runtime
  • session.listTools() — enumerate available tools for the current session
  • Automatic daemon management via packages/coding-agent/src/cli/daemon-command.ts

MCP Skill Packages: Custom External Integrations

PrimeAgent's Model Context Protocol (MCP) framework enables deep integration with external services. Built-in integrations (Linear, Notion, etc.) are implemented as Python skill packages that subclass McpIntegration. You can author custom skills for proprietary APIs or internal tools.

Structure of an MCP Skill Package

Custom skills reside under the skills/ directory and implement the interface defined in packages/coding-agent/docs/mcp-integrations.md:


# skills/jira_integration/__init__.py

from prime_agent.mcp import McpIntegration, tool, context

class JiraIntegration(McpIntegration):
    def __init__(self):
        self.base_url = self.config.get("JIRA_URL")
        self.token = self.config.get("JIRA_TOKEN")

    @tool
    async def get_issue(self, issue_key: str) -> dict:
        """Fetch a Jira issue by its key (e.g., PROJ-123)."""
        # HTTP implementation omitted for brevity

        return {"key": issue_key, "summary": "Fix login bug", "status": "In Progress"}

    @tool
    async def create_issue(self, project: str, summary: str, description: str) -> dict:
        """Create a new issue in the specified project."""
        # ...

        return {"key": f"{project}-42", "url": f"{self.base_url}/browse/{project}-42"}

    @context
    async def recent_activity(self) -> str:
        """Provide context about recent issues the user interacted with."""
        # Called automatically by the agent to enrich prompts

        return "Recently viewed: PROJ-119, PROJ-120"

Registering and Enabling Custom Skills

After placing your package under skills/, register it in packages/coding-agent/src/core/skills.ts:

// In packages/coding-agent/src/core/skills.ts
import { JiraIntegration } from "../../skills/jira_integration";

export const BUILTIN_SKILLS = [
  // ... existing skills
  {
    name: "jira",
    class: JiraIntegration,
    description: "Jira issue tracking integration",
  },
];

Users enable the skill interactively via /login → MCP Connections, after which the model can invoke jira.get_issue("PROJ-123") directly.

Sub-Agent Orchestration with the RLM Runtime

The rlm built-in tool spawns child agents that run in parallel isolate from the parent session. This pattern—implemented in packages/coding-agent/src/core/rlm-runtime.ts—enables complex multi-agent pipelines where PrimeAgent instances delegate work to specialized sub-agents.

Basic Sub-Agent Invocation

From within a running session, invoke rlm() to spawn a child:

// Executed within an AgentSession context
const results = await rlm([
  {
    prompt: "Analyze the security of this SSH config",
    files: ["/etc/ssh/sshd_config"],
  },
  {
    prompt: "Suggest hardening improvements",
    files: ["/etc/ssh/sshd_config"],
  },
  {
    prompt: "Generate an Ansible playbook applying these changes",
  }
], {
  parallel: true,           // Run all three agents concurrently
  timeoutMs: 120000,        // 2 minute timeout per sub-agent
  model: "gpt-4o",          // Override model for children
});

// results is an array of {output, tokenUsage, durationMs} matching the input order
console.log("Security analysis:", results[0].output);
console.log("Hardening suggestions:", results[1].output);
console.log("Ansible playbook:", results[2].output);

Cross-Process Sub-Agent Orchestration

External processes can also drive sub-agents by spawning PrimeAgent with --mode json or --mode rpc and invoking rlm() through the session:


# Parent script orchestrates multiple PrimeAgent workers

for dir in ./services/*/; do
  prime-agent --mode json <<EOF &
{"prompt": "Generate API documentation for $(basename $dir)", "cwd": "$dir"}
EOF
done
wait

This pattern supports:

  • Parallelized workloads — shard large tasks across CPU cores or machines
  • Specialized agent teams — delegate to agents configured with different models or tool sets
  • Background monitoring — spawn persistent sub-agents that report status to a parent

Choosing the Right Integration Pattern

Pattern Entry Point Best For Key Source File
Shell/CI automation prime-agent --mode json Pipelines, cron jobs, test harnesses packages/coding-agent/src/modes/headless-completion.ts
Node.js backend service AgentSession.create() API servers, chatbots, internal tools packages/coding-agent/src/core/sdk.ts
Custom service integration Python McpIntegration subclass Proprietary APIs, domain-specific tools packages/coding-agent/docs/mcp-integrations.md
Language-agnostic embedding prime-agent --mode rpc Go, Rust, Python, or containerized callers packages/coding-agent/src/modes/headless-completion.ts
Multi-agent workflows rlm() tool Parallel execution, specialized sub-tasks packages/coding-agent/src/core/rlm-runtime.ts

Summary

Frequently Asked Questions

Can I integrate PrimeAgent with Python applications?

Yes. Use RPC mode to spawn prime-agent --mode rpc as a subprocess and communicate via stdin/stdout JSON. Alternatively, implement an MCP skill package in Python that exposes your application's functionality to PrimeAgent, rather than driving PrimeAgent from Python.

What is the difference between JSON mode and RPC mode?

JSON mode is unidirectional: the agent streams events to stdout until completion. RPC mode is bidirectional: your process sends requests over stdin and receives responses over stdout, enabling multiple turns, tool callbacks, and explicit session control. Choose JSON mode for fire-and-forget automation; RPC mode for interactive or multi-step workflows.

How do I add a custom tool for my internal API?

Create a Python package under skills/ with a class extending McpIntegration, decorate methods with @tool, then register in packages/coding-agent/src/core/skills.ts. The tool becomes available after users enable it via /login → MCP Connections. See packages/coding-agent/docs/mcp-integrations.md for the full specification.

Is the RLM runtime suitable for production workload distribution?

The rlm tool spawns child agents within the same daemon process or container. For true distributed workloads across machines, combine RPC mode with your own orchestration layer that spawns PrimeAgent instances on separate hosts, or use rlm() locally for parallel CPU-bound tasks and fan-out results to external queues.

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 →