> ## Documentation Index
> Fetch the complete documentation index at: https://help.loopiq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a Custom Agent with LoopIQ MCP

## What This Does

This guide helps you create a custom agent that uses LoopIQ MCP safely.

A custom agent can use MCP to read LoopIQ records, retrieve release governance evidence, run AI/ML agents, and request approved actions such as remediation work-package creation.

## Recommended Architecture

Use this pattern for production agents:

1. The user authenticates with your application.
2. Your backend obtains or receives a LoopIQ-approved access token.
3. Your backend connects to the LoopIQ MCP server.
4. The agent discovers available tools.
5. The agent uses read tools first to ground its answer.
6. The agent previews any write action.
7. The user approves or rejects the payload.
8. The backend executes approved writes with an idempotency key.
9. Your app stores the audit trail.

Do not put long-lived bearer tokens in browser code, mobile apps, prompts, screenshots, or shared configuration files.

## Good First Custom Agents

Start with agents that read context before they write:

* Release readiness copilot
* Evidence gap reviewer
* Security blocker summarizer
* Sprint planning assistant
* Incident triage assistant
* Compliance evidence packager
* Analytics dashboard assistant
* Remediation work-package creator

## Required Safety Behavior

Every production custom agent should:

* preserve tenant and user context
* pass request ID and trace ID
* use read-only tools before write tools
* prefer semantic tools over raw route invocation
* use `dryRun: true` before important mutations
* show the exact payload before approval
* use an idempotency key for approved writes
* store the approval ID and tool result
* reject actions with missing parent records, missing titles, or unclear ownership

## Example Agent Flow

For a release remediation agent:

1. Ask the user for a release or certification.
2. Call `loopiq_get_release_certification`.
3. Call `loopiq_get_release_certification_evidence_graph`.
4. Identify failed controls, evidence gaps, and provider blockers.
5. Draft one parent remediation story and child tasks.
6. Call `loopiq_create_remediation_work_package` with `dryRun: true`.
7. Show the user the payload.
8. If approved, call the same tool with `dryRun: false`, `approvalId`, and `idempotencyKey`.
9. Show created story and task IDs.

## Openai Custom Agent Example

The exact SDK syntax may vary by OpenAI SDK version, but the production pattern is stable:

```ts theme={null}
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const loopiqMcpServer = {
  type: "mcp",
  server_label: "loopiq",
  server_url: process.env.LOOPIQ_MCP_URL,
  headers: {
    Authorization: `Bearer ${process.env.LOOPIQ_ACCESS_TOKEN}`,
  },
};

const response = await openai.responses.create({
  model: "gpt-4.1",
  tools: [loopiqMcpServer],
  input: [
    {
      role: "system",
      content:
        "You are a LoopIQ release governance assistant. Read evidence before making recommendations. Never create or update records without explicit user approval.",
    },
    {
      role: "user",
      content:
        "Review release backend-v1.0-GCN and draft a remediation work package for blockers. Do not execute writes yet.",
    },
  ],
});

console.log(response.output_text);
```

For write actions, build an approval step in your application. The agent should return a proposed payload, not execute the write immediately.

## Approval Loop Example

```ts theme={null}
const proposedPayload = {
  tenantId: "fusiononeplatform",
  story: {
    title: "Remediate release blockers for backend-v1.0-GCN",
    description: "Parent story for release certification blockers.",
    release_id: "REL_ID",
    certification_id: "CERT_ID",
  },
  tasks: [
    {
      title: "Triage critical Checkmarx findings",
      description: "Review exploitable critical findings attached to the release evidence graph.",
    },
  ],
  dryRun: true,
};

// First run a dry-run through your MCP client.
// Then display proposedPayload to the user.

const approvedPayload = {
  ...proposedPayload,
  dryRun: false,
  approvalId: "approval_123",
  idempotencyKey: "release-backend-v1-remediation-2026-06-04",
};

// Execute only after approval.
```

## Prompt Template for a Custom LoopIQ Agent

Use a system prompt like this:

```text theme={null}
You are a governed LoopIQ agent.

Rules:
- Always preserve tenant and user context.
- Prefer semantic LoopIQ MCP tools over raw route invocation.
- Read relevant records before recommending action.
- For release readiness, read the release certification and evidence graph first.
- For remediation, create a parent story and child tasks only through an approved work-package tool.
- Never invent backlog items, evidence, provider findings, owners, releases, or certifications.
- For write actions, produce a preview payload and wait for explicit approval.
- Include request ID, trace ID, approval ID, and idempotency key in action metadata.
- If evidence is missing or stale, say so and request a refresh instead of giving a confident answer.
```

## Tool Selection Guide

Use these rules:

* Use `loopiq_get_mcp_reliability_contract` at startup to understand server guarantees.
* Use `loopiq_list_ai_ml_agents` before running AI/ML agents.
* Use `loopiq_list_resources` before generic record operations.
* Use `loopiq_list_routes` before fallback route invocation.
* Use release certification tools for release compliance workflows.
* Use evidence graph tools for provider-normalized evidence.
* Use analytics tools for metrics, charts, and dashboard workflows.
* Use `loopiq_create_remediation_work_package` for approved parent-story-plus-child-task creation.

## Tenant and Auth Setup

Your custom agent should not ask the user to paste a token into a prompt.

Use one of these patterns:

* backend session exchanges user auth for a LoopIQ token
* short-lived user token stored server-side
* organization-approved service account token with strict tenant allow-list
* Helix backend-mediated flow where LoopIQ handles MCP auth propagation

For multi-tenant users, always show the selected tenant before executing actions.

## Dry-run and Approval Strategy

For read-only tools, execute normally.

For write tools:

1. Call with `dryRun: true` when supported.
2. Show the exact payload.
3. Ask for approval.
4. Add `approvalId`.
5. Add `idempotencyKey`.
6. Execute once.
7. Store the result.

If the network drops after approval, check the audit trail before retrying.

## Testing Checklist

Before production, test:

* tool discovery works
* tenant context is correct
* read-only calls return expected records
* unauthorized tenants are rejected
* stale or expired tokens fail safely
* dry-run write calls do not create records
* approved writes create exactly the expected records
* duplicate idempotency keys do not create duplicates
* action results include created IDs
* audit metadata is stored

## Troubleshooting

### The Agent Sees Too Many Tools

Constrain the agent with instructions to prefer semantic tools and specific tool families. Use `loopiq_list_resources` or `loopiq_list_ai_ml_agents` instead of listing every route.

### The Agent Chooses `loopiq_invoke_route` Too Often

Add a system instruction: "Use raw route invocation only when no named semantic tool exists."

### The Agent Proposes Ungrounded Tasks

Reject the action. Ask the agent to list the records it read: release, certification, evidence graph records, failed controls, provider blockers, evidence gaps, and linked work items.

### The Action Fails with Missing Fields

Regenerate the payload with explicit required fields. For work items, require clear titles, parent story details, release ID, certification ID, team, and evidence references.

### The Custom Agent Gives a Confident Answer with Missing Evidence

Change the prompt so missing provider evidence forces a caveated answer and a refresh recommendation.

## Related Articles

* [MCP Tool and Action Catalog](/ai-and-agents/mcp-tool-and-action-catalog)
* [Use LoopIQ MCP Tools](/ai-and-agents/use-loopiq-mcp-tools)
* [Connect LoopIQ MCP Clients](/ai-and-agents/connect-loopiq-mcp-clients)
* [Governed MCP Actions, Approvals, and Audit](/ai-and-agents/governed-mcp-actions-approvals-and-audit)
