Open Weight Thoughts
All articles

· 8 min read

Use the Cline SDK to Build Custom AI Coding Agents

By V. Wijaya

  • guides

To use the Cline SDK to build custom AI coding agents, install @cline/sdk, create an Agent with an LLM provider, give it narrowly defined tools, subscribe to its events, and run it with a task-specific system prompt. The practical path is to start with one bounded workflow—such as reviewing a diff or generating a migration—then make its inputs, tools, approvals, and final output explicit rather than trying to build a general-purpose autonomous developer on day one. [1][2]

How do you get started with the Cline SDK?

The Cline SDK is a set of TypeScript packages for embedding Cline’s agent runtime in an application. It requires Node.js 22 or later. The top-level package is the right starting point for most server-side coding-agent projects because it exposes the public SDK surface, including the agent runtime, model gateway, tools, and the fuller Cline harness. [1]

mkdir custom-review-agent
cd custom-review-agent
npm init -y
npm install @cline/sdk zod
npm install -D typescript tsx @types/node

Set the credentials for the provider you choose in the environment rather than committing them to source control. Cline’s provider layer can work with several hosted providers and OpenAI-compatible endpoints; the important design decision is to put the provider and model identifiers in configuration, so switching models does not require rewriting your agent logic. [2]

For a first agent, prefer the stateless Agent API. It is a good fit for a CLI command, queue worker, CI job, or a single request in an internal tool: construct an agent, stream events, call run(), and persist the result you care about. If you need durable sessions, built-in tools, approvals, scheduling, or a host application coordinating many sessions, graduate to ClineCore. [1][3]

Which Cline SDK package should you use?

Choose the smallest layer that owns the behavior you need. @cline/sdk is the umbrella package and the easiest import for an application. Underneath it, @cline/core is the Node-oriented full harness; @cline/agents is the lightweight, browser-compatible stateless execution loop; @cline/llms provides provider clients and model catalogs; and @cline/shared holds shared types, schemas, hooks, and helpers. [1][3]

  • Use Agent when your application already owns state and you want a focused run loop with your own tools.
  • Use ClineCore when you need sessions, persistence, built-in coding tools, approval flows, plugins, or scheduling.
  • Use the provider gateway separately only when you are building your own agent loop but want standardized model-provider integration.
  • Avoid importing lower-level packages prematurely: fewer moving parts makes failures and security boundaries easier to understand.

How do you build a custom AI coding agent?

A useful coding agent has a narrow job definition and a deterministic way to declare that job complete. The example below builds a small review agent. It does not grant arbitrary shell access or filesystem writes; instead, your host application supplies the diff in the prompt, and the model records structured findings by calling a custom tool. A second completion tool ends the loop and returns a machine-readable verdict. This is the same general pattern Cline documents for its code-review example. [4]

import { Agent, createTool } from "@cline/sdk"
import { z } from "zod"

const findings: Array<{
  file: string
  line: number
  severity: "critical" | "warning" | "suggestion"
  comment: string
}> = []

const addFinding = createTool({
  name: "add_review_finding",
  description:
    "Record one actionable code-review finding. Use only for bugs, security issues, performance risks, or specific readability problems in the supplied diff.",
  inputSchema: z.object({
    file: z.string().describe("Repository-relative file path"),
    line: z.number().int().positive().describe("Relevant line number"),
    severity: z.enum(["critical", "warning", "suggestion"])
      .describe("Impact level of the finding"),
    comment: z.string().describe("Concise explanation and suggested fix"),
  }),
  async execute(input) {
    findings.push(input)
    return { recorded: true, total: findings.length }
  },
})

const submitReview = createTool({
  name: "submit_review",
  description: "Submit the final review decision after all findings are recorded.",
  inputSchema: z.object({
    summary: z.string().describe("Brief overall assessment"),
    approve: z.boolean().describe("Whether the change is safe to merge"),
  }),
  lifecycle: { completesRun: true },
  async execute(input) {
    return { ...input, findings }
  },
})

const agent = new Agent({
  providerId: process.env.PROVIDER_ID!,
  modelId: process.env.MODEL_ID!,
  apiKey: process.env.LLM_API_KEY!,
  tools: [addFinding, submitReview],
  maxIterations: 12,
  systemPrompt: `You are a careful code reviewer. Review only the diff supplied.
Record each concrete issue with add_review_finding. Do not invent context.
When finished, call submit_review exactly once.`,
})

agent.subscribe((event) => {
  if (event.type === "assistant-text-delta") process.stdout.write(event.text ?? "")
})

const diff = process.env.DIFF ?? ""
const result = await agent.run(`Review this git diff:\n\n\`\`\`diff\n${diff}\n\`\`\``)
console.log("\nFinal result:", result)

The important part is not the prompt wording; it is the contract. The system prompt names the permitted workflow, the review tool collects a typed record, and lifecycle: { completesRun: true } gives the model a defined exit rather than leaving it to consume iterations until a ceiling is reached. Keep the iteration cap anyway: it is a cost and runaway-loop control, not a substitute for a completion contract. [4][5]

How do custom tools make an AI coding agent useful?

Tools bridge the gap between text generation and work your software can rely on. In the Cline SDK, a tool has a unique name, a description the model uses to decide whether to call it, an input schema, and an execute handler. createTool accepts Zod schemas and converts them to JSON Schema automatically, giving the handler typed input. [5]

Tool descriptions are interface documentation for a probabilistic caller. Describe what the tool does, what it returns, when it should be used, when it must not be used, and its limits. Prefer get_pull_request to github, search_database to data, and an enum such as "critical" | "warning" | "suggestion" over a free-form severity string. Cline’s guidance specifically recommends descriptions on every input and constrained enums where the domain is finite. [5]

Return structured data whenever possible. A tool that returns { issue: "not_found", retryable: false } lets the model choose a different path. Throwing an exception discards that useful domain signal and is treated differently by the runtime. For long-running work, inspect the tool context’s cancellation signal so a cancelled web request or CI job does not continue consuming resources. [5]

How do you keep an AI coding agent safe?

Treat every tool as a capability grant, not a convenience API. A code-review agent normally needs read access and an output sink; it does not need rm, production credentials, package publication, or unrestricted network access. Give it the smallest capability set that can complete the workflow, validate input in the tool handler as well as the Zod schema, and execute dangerous jobs in isolated environments with short-lived credentials.

Cline supports per-tool policies: tools can be auto-approved, require approval, or be disabled so the model cannot see them. Crucially, omitted policies default to enabled and auto-approved, so define policies explicitly for tools that matter. A practical default is auto-approving read-only inspection while requiring an approval step for file edits, command execution, writes to external services, and network-affecting operations. [6]

toolPolicies: {
  read_files: { autoApprove: true },
  search_codebase: { autoApprove: true },
  editor: { autoApprove: false },
  run_commands: { autoApprove: false },
}

Approval is not a sandbox. It is a product control for a human-in-the-loop workflow. For headless CI, use an isolated runner and an allowlist tailored to that job—for example, permit a formatter or test command only inside a disposable checkout. Do not translate “fully automated” into “all tools are safe to auto-approve.” Cline’s own permission guide warns that blanket auto-approval permits shell commands, file modifications, and network requests without review. [6]

How do you observe and ship a coding agent?

Subscribe to events from the first prototype. With Agent, agent.subscribe() exposes runtime events such as streamed assistant text. With the fuller core runtime, host-facing events cover content, iteration boundaries, usage, notices, completion, and errors. That event stream should feed the CLI or UI, but also your logs and metrics: capture run IDs, model IDs, tool names, approval decisions, latency, token usage, failures, and final status. [2][7]

Before production, create an evaluation set from real tasks: clean diffs, intentionally vulnerable changes, ambiguous requirements, missing files, tool errors, and rejected approvals. Assert both the final structured output and the trace behavior—whether it called a prohibited tool, stopped correctly, or made unsupported claims. Test custom tools in isolation before involving a model; then test the complete agent in a sandbox. This separates ordinary software defects from model judgment failures and makes regressions diagnosable.

Where does Cline fit after you build the agent?

If you want the underlying runtime for an internal developer tool, CI reviewer, scheduled maintenance worker, or customer-facing coding feature, Cline is the open-source agent platform behind the SDK. Its site describes one runtime available through editor integrations, a terminal CLI, desktop apps, and an embeddable SDK; it also highlights custom tools, lifecycle hooks, MCP support, and streaming events—the exact building blocks that make a custom coding agent more than a chat wrapper. [2][8]

For this use case, the SDK itself is open source and free to use. The broader Cline product offers bring-your-own provider credentials or local models, usage-billed model access, and ClinePass, listed at $9.99 per month; those are model-access options rather than a requirement to use the SDK. That flexibility matters when your custom agent needs to run against an organization’s chosen provider, endpoint, or infrastructure. [1][8]

Sources & citations

  1. [1]Cline SDK overview
  2. [2]Cline SDK product page
  3. [3]Cline SDK packages documentation
  4. [4]Cline guide: Building an Agent
  5. [5]Cline guide: Creating Custom Tools
  6. [6]Cline guide: Permission Handling
  7. [7]Cline SDK events documentation
  8. [8]Cline overview and model access
Use the Cline SDK to Build Custom AI Coding Agents | Open Weight Thoughts