Integrating an AI Agent Builder with Backstage IDP
Why Backstage
Section titled “Why Backstage”The AI Agent Builder built in n8n-poc is a standalone application. But to operate it in a real organization, the following questions arise:

- 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:
| Feature | Description |
|---|---|
| Software Catalog | Manage all services, APIs, and resources in one place |
| Plugin System | Extend functionality on a per-plugin basis |
| Software Templates | Standardized project creation workflows |
| TechDocs | Technical 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.
Integration Strategy
Section titled “Integration Strategy”Design Principles
Section titled “Design Principles”- Do not modify the n8n-poc API. Backstage acts only as a proxy and UI layer.
- Follow Backstage plugin standards. Use the New Backend System and the Plugin API.
- Keep changes minimal. Reuse existing code and use a proxy pattern.
Architecture
Section titled “Architecture”Why the Proxy Pattern?
Section titled “Why the Proxy Pattern?”The reason for choosing an HTTP proxy instead of having the Backstage backend plugin directly access the n8n-poc API’s DB:
| Item | Proxy (chosen) | Direct DB access |
|---|---|---|
| Modifying n8n-poc code | Not needed | Needed |
| Independent deployment | Each deployable | Increased coupling |
| Type safety | Checked at runtime | Checked at compile time |
| Latency | One extra hop | Direct connection |
| Complexity | Simple | Duplicate ORM setup |
At the PoC stage, simplicity and independence were more important.
Backend Plugin Implementation
Section titled “Backend Plugin Implementation”Plugin Definition
Section titled “Plugin Definition”Plugin registration using Backstage’s New Backend System. Required dependencies are injected via DI from coreServices:
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', }); }, }); },});Proxy Router
Section titled “Proxy Router”A proxy pattern that forwards all requests to the n8n-poc API. The n8n-poc API URL is configured in app-config.yaml:
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;}Configuration
Section titled “Configuration”aiAgent: n8nPocApiUrl: 'http://localhost:3001'Frontend Plugin Implementation
Section titled “Frontend Plugin Implementation”Plugin Registration
Section titled “Plugin Registration”Define the plugin with the Backstage Plugin API, and DI-register the AiAgentClient through an API Factory:
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 },});API Client
Section titled “API Client”Dynamically resolve the backend URL with discoveryApi, and send requests that automatically include the auth token with fetchApi:
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(); }}Agent List (AgentListPage)
Section titled “Agent List (AgentListPage)”Leverages Backstage’s common components such as Table, StatusOK, StatusError:
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> );};Execution Panel (ExecutionPanel)
Section titled “Execution Panel (ExecutionPanel)”Converse with the Agent through a chat-style UI. The API Client is injected and used via the useApi Hook:
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> );};Navigation Menu
Section titled “Navigation Menu”Add an AI Agents menu to the sidebar:
import SmartToyIcon from '@material-ui/icons/Memory';
<SidebarItem icon={SmartToyIcon} to="ai-agent" text="AI Agents" />E2E Verification
Section titled “E2E Verification”Verification of the entire pipeline through Backstage:
| Verification item | Result | Notes |
|---|---|---|
| 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) |
Tech Stack
Section titled “Tech Stack”| Layer | Technology |
|---|---|
| Backstage | v1.48.0 (New Backend System) |
| Frontend Plugin | React, Material UI v4, @backstage/core-plugin-api |
| Backend Plugin | Express, @backstage/backend-plugin-api |
| n8n-poc API | NestJS, TypeORM, PostgreSQL |
| Workflow Engine | n8n 1.94.1 |
| LLM | Gemini 2.5 Flash |
Directory Structure
Section titled “Directory Structure”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
Retrospective
Section titled “Retrospective”What Went Well
Section titled “What Went Well”- 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
What Was Difficult
Section titled “What Was Difficult”- 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
What Was Intentionally Excluded
Section titled “What Was Intentionally Excluded”| Item | Reason |
|---|---|
| PostgreSQL migration (Backstage DB) | SQLite in-memory is sufficient for the PoC |
| Software Template | Standardizing Agent creation is the next step |
| CatalogProcessor | Automatic sync between Agent ↔ Catalog Entity |
| RBAC | Out of scope for the PoC |
Considerations for Production Adoption
Section titled “Considerations for Production Adoption”- Authentication integration: integrate OAuth/OIDC instead of Guest mode
- DB separation: a separate PostgreSQL instance is recommended for Backstage
- CatalogProcessor: automatically registering Agents as Catalog Entities enables ownership and dependency tracking
- Software Template: provide a standardized creation workflow with an “AI Agent creation” template
- Monitoring: add dashboards for execution cost and token usage
Full Series
Section titled “Full Series”- Design and Implementation of an n8n-based AI Agent Builder (previous part)
- 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.