Skip to content

Integrating an AI Agent Builder with Backstage IDP

Interactive Diagram

새 탭 ↗

The AI Agent Builder built in n8n-poc is a standalone application. But to operate it in a real organization, the following questions arise:

Backstage UI highlighting core components such as the sidebar and header versus the Service Catalog plugin area Source: Backstage docs, Architecture overview, The Backstage Authors, Apache-2.0

  • Who created the Agent, and which team owns it?
  • What are its dependencies on other services (APIs, infrastructure)?
  • Is there a standard procedure for creating an Agent?

These questions ultimately fall into the domain of the Internal Developer Portal (IDP). Backstage is an open-source IDP platform created by Spotify that provides the following:

FeatureDescription
Software CatalogManage all services, APIs, and resources in one place
Plugin SystemExtend functionality on a per-plugin basis
Software TemplatesStandardized project creation workflows
TechDocsTechnical documentation per service

The key judgment: an AI Agent is also a “software asset” of the organization. It should be registerable in the Catalog, have its ownership tracked, and be creatable through a standard procedure.


  1. Do not modify the n8n-poc API. Backstage acts only as a proxy and UI layer.
  2. Follow Backstage plugin standards. Use the New Backend System and the Plugin API.
  3. Keep changes minimal. Reuse existing code and use a proxy pattern.
PlantUML Diagram

The reason for choosing an HTTP proxy instead of having the Backstage backend plugin directly access the n8n-poc API’s DB:

ItemProxy (chosen)Direct DB access
Modifying n8n-poc codeNot neededNeeded
Independent deploymentEach deployableIncreased coupling
Type safetyChecked at runtimeChecked at compile time
LatencyOne extra hopDirect connection
ComplexitySimpleDuplicate ORM setup

At the PoC stage, simplicity and independence were more important.


Plugin registration using Backstage’s New Backend System. Required dependencies are injected via DI from coreServices:

plugins/ai-agent-backend/src/plugin.ts
export const aiAgentPlugin = createBackendPlugin({
pluginId: 'ai-agent',
register(env) {
env.registerInit({
deps: {
httpAuth: coreServices.httpAuth,
httpRouter: coreServices.httpRouter,
logger: coreServices.logger,
config: coreServices.rootConfig,
},
async init({ httpAuth, httpRouter, logger, config }) {
httpRouter.use(
await createRouter({ httpAuth, logger, config }),
);
// allow access to the Health endpoint without authentication
httpRouter.addAuthPolicy({
path: '/health',
allow: 'unauthenticated',
});
},
});
},
});

A proxy pattern that forwards all requests to the n8n-poc API. The n8n-poc API URL is configured in app-config.yaml:

plugins/ai-agent-backend/src/router.ts
export async function createRouter({ httpAuth, logger, config }): Promise<express.Router> {
const router = Router();
router.use(express.json());
const n8nPocBaseUrl = config.getOptionalString('aiAgent.n8nPocApiUrl')
?? 'http://localhost:3001';
// proxy helper
async function proxyFetch(path: string, options?: RequestInit) {
const url = `${n8nPocBaseUrl}/api/v1${path}`;
logger.debug(`Proxying to: ${url}`);
return fetch(url, {
...options,
headers: { 'Content-Type': 'application/json', ...options?.headers },
});
}
// Agent list — upstream returns { data: Agent[], total }
// Frontend expects an array, so extract only data (unwrap)
router.get('/agents', async (_req, res) => {
const upstream = await proxyFetch('/agents');
const json = await upstream.json();
res.status(upstream.status).json(json.data ?? json);
});
// Agent detail
router.get('/agents/:id', async (req, res) => {
const upstream = await proxyFetch(`/agents/${req.params.id}`);
res.status(upstream.status).json(await upstream.json());
});
// Agent creation
router.post('/agents', async (req, res) => {
const upstream = await proxyFetch('/agents', {
method: 'POST',
body: JSON.stringify(req.body),
});
res.status(upstream.status).json(await upstream.json());
});
// Agent execution — core proxy
router.post('/agents/:id/execute', async (req, res) => {
const upstream = await proxyFetch(`/agents/${req.params.id}/executions`, {
method: 'POST',
body: JSON.stringify(req.body),
});
res.status(upstream.status).json(await upstream.json());
});
// Health check — verify n8n-poc API connection
router.get('/health', async (_req, res) => {
try {
const upstream = await proxyFetch('/n8n/health');
res.json({ status: 'ok', upstream: await upstream.json() });
} catch (err) {
res.status(503).json({ status: 'error', error: String(err) });
}
});
return router;
}
app-config.yaml
aiAgent:
n8nPocApiUrl: 'http://localhost:3001'

Define the plugin with the Backstage Plugin API, and DI-register the AiAgentClient through an API Factory:

plugins/ai-agent/src/plugin.ts
export const aiAgentPlugin = createPlugin({
id: 'ai-agent',
apis: [
createApiFactory({
api: aiAgentApiRef,
deps: { discoveryApi: discoveryApiRef, fetchApi: fetchApiRef },
factory: ({ discoveryApi, fetchApi }) =>
new AiAgentClient({ discoveryApi, fetchApi }),
}),
],
routes: { root: rootRouteRef },
});

Dynamically resolve the backend URL with discoveryApi, and send requests that automatically include the auth token with fetchApi:

plugins/ai-agent/src/api.ts
export interface Agent {
id: string;
name: string;
description: string;
status: string;
modelConfig: {
provider?: 'gemini' | 'anthropic' | 'openai';
model: string;
maxTokens?: number;
temperature?: number;
};
systemPrompt: string;
createdAt: string;
}
export class AiAgentClient implements AiAgentApi {
constructor(private options: { discoveryApi: DiscoveryApi; fetchApi: FetchApi }) {}
private async baseUrl() {
return this.options.discoveryApi.getBaseUrl('ai-agent');
}
async listAgents(): Promise<Agent[]> {
const url = `${await this.baseUrl()}/agents`;
const res = await this.options.fetchApi.fetch(url);
if (!res.ok) throw new Error(`Failed to fetch agents: ${res.statusText}`);
return res.json();
}
async executeAgent(id: string, message: string): Promise<ExecutionResult> {
const url = `${await this.baseUrl()}/agents/${id}/execute`;
const res = await this.options.fetchApi.fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
if (!res.ok) throw new Error(`Failed to execute agent: ${res.statusText}`);
return res.json();
}
}

Leverages Backstage’s common components such as Table, StatusOK, StatusError:

plugins/ai-agent/src/components/AgentListPage/AgentList.tsx
const StatusIndicator = ({ status }: { status: string }) => {
switch (status) {
case 'active': return <StatusOK>Active</StatusOK>;
case 'inactive': return <StatusError>Inactive</StatusError>;
default: return <StatusPending>{status}</StatusPending>;
}
};
const columns: TableColumn<Agent>[] = [
{ title: 'Name', field: 'name' },
{ title: 'Description', field: 'description' },
{
title: 'Status',
render: (row) => <StatusIndicator status={row.status} />,
},
{
title: 'Provider',
render: (row) => <Chip label={row.modelConfig?.provider || 'N/A'} size="small" />,
},
{
title: 'Model',
render: (row) => <Chip label={row.modelConfig?.model || 'N/A'} size="small" />,
},
{
title: 'Created',
render: (row) => new Date(row.createdAt).toLocaleDateString(),
},
];
export const AgentList = () => {
const api = useApi(aiAgentApiRef);
const navigate = useNavigate();
const { value: agents, loading, error } = useAsync(() => api.listAgents());
return (
<Page themeId="tool">
<Header title="AI Agents">
<HeaderLabel label="Owner" value="platform-team" />
</Header>
<Content>
<ContentHeader title="Agent List">
<Button startIcon={<AddIcon />} onClick={() => navigate('new')}>
Create Agent
</Button>
</ContentHeader>
<Table
columns={columns}
data={agents || []}
isLoading={loading}
onRowClick={(_e, row) => row && navigate(row.id)}
/>
</Content>
</Page>
);
};

Converse with the Agent through a chat-style UI. The API Client is injected and used via the useApi Hook:

plugins/ai-agent/src/components/ExecutionPanel/index.tsx
export const ExecutionPanel = ({ agentId, agentName }: Props) => {
const api = useApi(aiAgentApiRef);
const [input, setInput] = useState('');
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [loading, setLoading] = useState(false);
const handleExecute = async () => {
if (!input.trim()) return;
// add user message
setMessages(prev => [...prev, { role: 'user', content: input, timestamp: new Date() }]);
setInput('');
setLoading(true);
try {
const result = await api.executeAgent(agentId, input);
const content = typeof result.output === 'string'
? result.output
: result.output?.output ?? JSON.stringify(result.output);
setMessages(prev => [...prev, {
role: 'agent',
content,
timestamp: new Date(),
executionTime: result.executionTime,
}]);
} catch (err: any) {
setMessages(prev => [...prev, {
role: 'agent',
content: `❌ Error: ${err.message}`,
timestamp: new Date(),
}]);
} finally {
setLoading(false);
}
};
return (
<InfoCard title={`Chat with ${agentName}`}>
{/* message list */}
<Box style={{ maxHeight: 400, overflow: 'auto' }}>
{messages.map((msg, i) => (
<Paper key={i} style={{ padding: 8, margin: 4, ... }}>
<Typography variant="body2">{msg.content}</Typography>
</Paper>
))}
{loading && <CircularProgress size={24} />}
</Box>
{/* input field */}
<Box style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<TextField fullWidth value={input} onChange={e => setInput(e.target.value)}
onKeyPress={e => e.key === 'Enter' && handleExecute()} />
<Button variant="contained" onClick={handleExecute} disabled={loading}>
Send
</Button>
</Box>
</InfoCard>
);
};

Add an AI Agents menu to the sidebar:

packages/app/src/components/Root/Root.tsx
import SmartToyIcon from '@material-ui/icons/Memory';
<SidebarItem icon={SmartToyIcon} to="ai-agent" text="AI Agents" />

Verification of the entire pipeline through Backstage:

PlantUML Diagram
Verification itemResultNotes
Health Check✅Confirmed connection between Backend Plugin and n8n-poc API
Agent list query✅data unwrap works correctly
Agent detail query✅Prompt, Config displayed correctly
Agent execution✅Gemini response received (about 4.5 seconds)

LayerTechnology
Backstagev1.48.0 (New Backend System)
Frontend PluginReact, Material UI v4, @backstage/core-plugin-api
Backend PluginExpress, @backstage/backend-plugin-api
n8n-poc APINestJS, TypeORM, PostgreSQL
Workflow Enginen8n 1.94.1
LLMGemini 2.5 Flash
  • Directorybackstage-n8n-poc/
    • Directorypackages/
      • Directoryapp/ Backstage frontend
        • …
      • Directorybackend/ Backstage backend
        • …
    • Directoryplugins/
      • Directoryai-agent/ Frontend Plugin
        • Directorysrc/
          • api.ts API client (AiAgentClient)
          • plugin.ts plugin definition + API Factory
          • routes.ts route definition
          • Directorycomponents/
            • DirectoryAgentListPage/ list (Table + Status)
              • …
            • DirectoryAgentDetailPage/ detail (Prompt, Config)
              • …
            • DirectoryExecutionPanel/ chat UI
              • …
      • Directoryai-agent-backend/ Backend Plugin
        • Directorysrc/
          • plugin.ts plugin registration
          • router.ts proxy router
    • app-config.yaml aiAgent.n8nPocApiUrl configuration

  • The effect of the proxy pattern: integrated into Backstage without modifying a single line of n8n-poc code
  • Backstage Plugin System: the frontend/backend plugin structure is well designed, making extension easy
  • New Backend System: clean plugin initialization based on DI
  • Backstage learning curve: there are many concepts to understand, such as the Plugin API, Discovery API, and Auth system
  • MUI v4 constraints: unable to use the latest MUI patterns, which limits CSS styling
  • Memory pressure: running Backstage + n8n-poc API + n8n + PostgreSQL simultaneously is tight at 7.8GB RAM
ItemReason
PostgreSQL migration (Backstage DB)SQLite in-memory is sufficient for the PoC
Software TemplateStandardizing Agent creation is the next step
CatalogProcessorAutomatic sync between Agent ↔ Catalog Entity
RBACOut of scope for the PoC
  1. Authentication integration: integrate OAuth/OIDC instead of Guest mode
  2. DB separation: a separate PostgreSQL instance is recommended for Backstage
  3. CatalogProcessor: automatically registering Agents as Catalog Entities enables ownership and dependency tracking
  4. Software Template: provide a standardized creation workflow with an “AI Agent creation” template
  5. Monitoring: add dashboards for execution cost and token usage

  1. Design and Implementation of an n8n-based AI Agent Builder (previous part)
  2. Integrating an AI Agent Builder with Backstage IDP (current part)

Source Code: backstage-n8n-poc (private repository). The excerpts and explanations in this article are written to stand on their own.