AgentBack
ninemindai/agentback
Um schema, todos os limites: API + MCP + docs unificados com Zod
Ver no GitHubFramework AI-nativo para APIs e servidores MCP que unifica contratos REST, MCP tools e documentação através de um único schema Zod. Baseado em injeção de dependência com Context e Binding, oferece validação em tempo de execução, geração automática de OpenAPI 3.1, segurança integrada (confirmação, idempotência) e suporte a precificação por chamada.
Instalação
npx convez-ai ninemindai/agentback1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Construir APIs consumidas simultaneamente por aplicações e agentes IA
- Gerar ferramentas MCP tipadas automaticamente a partir de schemas
- Implementar rotas REST e tools MCP com decoradores compartilhados
- Adicionar segurança (confirmação de payload, idempotência) em APIs de agentes
- Metrificar e cobrar por uso de ferramentas MCP com custo por chamada
Veredito

Solução sofisticada e bem-arquitetada para times que precisam de APIs multi-consumidor (aplicações + agentes). Alpha estável com testes end-to-end, mas exige familiaridade com DI e Zod; compensador para stacks que unificam REST/MCP.
README
A tradução para o português deste README ainda está na fila.
AgentBack
AgentBack is an AI-native API/MCP framework for the agent era, built with agents, for agents. It lets REST endpoints, MCP tools, generated docs, typed clients, tests, and runtime validation all share one Zod contract.
The foundation is a modern ESM port of LoopBack 4's proven dependency-injection
core: a hierarchical Context of Bindings with @inject, providers,
interceptors, extension points, lifecycle observers, and tag-based discovery.
REST controllers and MCP tool classes are just bindings the respective servers
find by tag. The same schemas attached to those bindings become the runtime
validator, z.infer type, OpenAPI 3.1 contract, MCP input/output schema, and
Swagger/Inspector-rendered docs.
- ESM-only, Node 22.13+, TypeScript 6.0
Context+BindingDI with@inject, providers, interceptors, extensions, lifecycle observers- Zod-first schemas; decorators accept
ZodTypedirectly - OpenAPI 3.1.1 emission via Zod v4's native
z.toJSONSchema - MCP (Model Context Protocol) server with the same decorator style as REST
- Swagger UI at
/explorerand MCP Inspector at/mcp-inspector - AX artifacts:
/llms.txt+/llms-full.txtserved from the same route registry - Machine-actionable errors: stable codes, per-field issues, the violated schema, retryability, and remediation hints — same envelope on REST and MCP
- Safety primitives:
confirm:(payload-bound confirmation tokens) andidempotency:(idempotency-key replay) on routes and tools - Tool cost report: token-price the MCP tool surface before agents pay for it
- Per-call pricing:
@price('$0.001')meters a route or tool and (withinstallPriceGate) refuses unpaid calls with an x402/MPP challenge - Typed HTTP client without codegen when TypeScript consumers share schemas
- Policy, auth, metering, payments, messaging, and observability as DI components
- Built on the official
@modelcontextprotocol/sdk
Status: alpha. End-to-end examples and tests pass; the API surface is stabilizing but may still change between alpha releases.
Positioning
The core product claim is one schema, every boundary. Compared with common Node/TypeScript service stacks, AgentBack optimizes for teams whose APIs are consumed by both applications and AI agents.
| Stack | Runtime contract | Service contract | Agent/tool contract |
|---|---|---|---|
| Express + raw Zod | Hand-wired Zod | Hand-written OpenAPI | Hand-written tool manifest |
| tRPC | Zod | TypeScript-only | Custom adapter |
| NestJS | class-validator | Swagger decorators | Custom adapter |
| FastAPI | Pydantic | OpenAPI from the same models | Custom adapter |
| AgentBack | Zod | OpenAPI from same Zod | MCP from same Zod |
Use it when you need HTTP APIs, MCP tools, docs, typed clients, policy checks, and usage rails to stay coherent as the system grows.
Documentation
Full docs live in docs/ — a guided path from the core
ideas to building real apps:
- Blog — Design notes · Boundary architecture map
- Concepts — Dependency injection · Schema-first decorators · Components, servers & lifecycle
- Guides — Build a REST API · Build an MCP server · Hybrid app (REST + MCP) · Composition & extensibility · Testing · Secure MCP over HTTP · Deploy to production
- Architecture — Overview + diagrams · Boundary-coherence design thesis
The rest of this README is the one-page tour and code feel.
Packages
The DI framework is the foundation; everything else is built on it.
DI foundation
| Package | Role |
|---|---|
@agentback/common | Shared logging, env, ID, redaction, and async helper utilities |
@agentback/metadata | Decorator metadata utilities (port of @loopback/metadata) |
@agentback/context | DI container: Context, Binding, @inject, providers, interceptors (port of @loopback/context) |
@agentback/core | Application (a Context), Component, Server, life-cycle (port of @loopback/core) |
REST, MCP, and clients
| Package | Role |
|---|---|
@agentback/http-server | HTTP server with graceful stop (port of @loopback/http-server) |
@agentback/express | Express integration + middleware (port of @loopback/express) |
@agentback/openapi | Zod-first decorators + OpenAPI 3.1.1 emission |
@agentback/rest | Minimal REST server with Zod request/body validation |
@agentback/rest-explorer | Mounts Swagger UI 5.x at /explorer |
@agentback/context-explorer | Mounts a context/binding explorer UI |
@agentback/schema-explorer | Mounts a schema/entity provenance explorer UI (REST + MCP + Drizzle) |
@agentback/mcp | Decorator-driven MCP server (@mcpServer, @tool w/ Zod input/output) |
@agentback/mcp-inspector | Mounts an MCP inspector UI at /mcp-inspector |
@agentback/mcp-http | Exposes the MCP server over Streamable HTTP at /mcp (+ OAuth, scopes) |
@agentback/mcp-client | Connect to remote MCP servers over HTTP (OAuth-aware) |
@agentback/mcp-host | Aggregate upstream MCP servers into one gateway |
@agentback/mcp-connect | Persistent outbound MCP connections for browser/admin UIs |
@agentback/client | Schema-shared typed HTTP client with no codegen |
Platform components
| Package | Role |
|---|---|
@agentback/config | Zod-validated config loader with env overlays and DI bindings |
@agentback/security | User, subject, and principal primitives |
@agentback/authentication | Authentication decorator and strategy pipeline |
@agentback/authentication-jwt | JWT bearer strategy |
@agentback/authentication-oauth2 | OAuth2 introspection and JWKS bearer-token strategies |
@agentback/authorization | @authorize decorator and voter pipeline |
@agentback/extension-health | Health/readiness probes |
@agentback/extension-metrics | Prometheus /metrics endpoint and HTTP timing |
@agentback/extension-otel | OpenTelemetry spans across REST, MCP, and jobs |
@agentback/extension-rate-limit | In-memory or Redis-backed rate limiting |
@agentback/metering | Per-principal REST/MCP usage events, audit sinks, and quota |
@agentback/payments | x402/MPP/Stripe payment authorization and billing seams |
@agentback/messaging | Zod-typed JobQueue/EventBus/Scheduler ports with in-memory adapter |
@agentback/messaging-bullmq | BullMQ + Redis Streams durable adapter for messaging ports |
@agentback/drizzle | Drizzle ORM binding and drizzle-zod recipe |
@agentback/files | FileStore port for uploads/downloads + in-memory & filesystem adapters |
@agentback/files-s3 | S3 FileStore adapter (streaming via AWS SDK v3) |
@agentback/plugin | Plugin discovery, gating, and component mounting |
@agentback/testing | Test harness with typed REST client, supertest, and in-memory MCP |
@agentback/testlab | Lower-level test helpers used by the package test suites |
create-agentback | npm create scaffold for REST, MCP, and hybrid services |
@agentback/console | Combined context, schema, REST/OpenAPI, and MCP admin console |
@agentback/console-theme | Shared styling for console and explorer UIs |
Quick start
pnpm install
pnpm build
pnpm -F hello-rest start # REST + Swagger UI
pnpm -F hello-mcp test # MCP over stdio (drives the server with a test client)
pnpm -F hello-hybrid start # REST + MCP from one process, both UIs
Reference app
For a complete, real-world build beyond the in-repo hello-* examples, see
ninemindai/agentback-demo —
a Weather MCP server where one Zod schema set is served over stdio, authenticated
HTTP, and a dev console, backed by the free Open-Meteo API.
For coding agents (Claude Code, Codex, …)
This repo ships an agent skill —
skills/agentback — that teaches a coding agent the
framework's decorator patterns, slot-0 input-bundle convention, DI container,
auth stack, and schema-sharing client, with task-scoped reference files the
agent loads on demand. If you're building an app with AgentBack and an
agent is doing the typing, install the skill first; it encodes the conventions
that aren't guessable from type signatures alone.
The easiest install is skills.sh, which supports Claude Code, Codex, Cursor, Copilot, Gemini, and 20+ other agents:
npx skills add ninemindai/agentback # pick agents interactively
npx skills add ninemindai/agentback -a claude-code -a codex -y
npx skills add ninemindai/agentback -g -y # user-global, all agents
Once installed, the agent discovers it automatically; it activates when a task
mentions @agentback/* packages, the REST/MCP decorators, or hybrid
Zod-shared apps.
Agents without skill support — the skill is plain markdown with a YAML
description. Point the agent at it from your instructions file (e.g.
AGENTS.md):
When working with @agentback/\* packages, first read
skills/agentback/SKILL.md and the relevant file under
skills/agentback/references/ (REST, MCP tools, DI, auth, client sharing,
or composition) before writing code.
The skill's references/ directory splits the
deep material by task — rest-and-openapi.md, mcp-tools.md,
dependency-injection.md, auth-and-rate-limiting.md,
schema-sharing-and-client.md, composition-and-operations.md — so agents
pull only the context the current task needs.
A 30-second feel
DI container (works standalone, no HTTP needed)
import {Context, BindingScope, inject, injectable} from '@agentback/context';
import {Application} from '@agentback/core';
@injectable({scope: BindingScope.SINGLETON})
class Clock {
now() {
return new Date().toISOString();
}
}
@injectable()
class Greeter {
constructor(@inject('clock') private clock: Clock) {}
greet(name: string) {
return `Hello ${name} at ${this.clock.now()}`;
}
}
const app = new Application(); // Application IS a Context
app.bind('clock').toClass(Clock);
app.service(Greeter); // tag-based service binding
const greeter = await app.get<Greeter>('services.Greeter');
console.log(greeter.greet('world'));
The same Context/Binding/@inject machinery is what the REST and
MCP servers below use under the hood — controllers and tool classes are
just tagged bindings the servers discover at start time.
REST controller (Zod-validated)
import {z} from 'zod';
import {api, get, post} from '@agentback/openapi';
import {RestApplication} from '@agentback/rest';
import {inject} from '@agentback/context';
const HelloPath = z.object({name: z.string().min(1).max(64)});
const Greeting = z.object({greeting: z.string()});
const EchoIn = z.object({text: z.string().min(1).max(280)});
const EchoOut = z.object({echoed: z.string(), at: z.string()});
@api({basePath: '/greet'})
class GreetingController {
@get('/hello/{name}', {path: HelloPath, response: Greeting})
async hello(input: {path: z.infer<typeof HelloPath>}) {
return {greeting: `Hello, ${input.path.name}!`};
}
@post('/echo', {body: EchoIn, response: EchoOut})
async echo(
input: {body: z.infer<typeof EchoIn>},
@inject('clock') clock: {now(): string},
) {
return {echoed: input.body.text, at: clock.now()};
}
}
const app = new RestApplication();
app.bind('clock').to({now: () => new Date().toISOString()});
app.restController(GreetingController);
await app.start();
// GET /openapi.json -> OpenAPI 3.1.1
// POST /greet/echo with {"text":""} -> 422 with Zod issues
Schemas live once on each verb decorator. The handler receives a single
input object with body/path/query/headers keys derived via
z.infer — change a schema and the parameter type updates. @inject
weaves in at slot 1+; on routes with no input schemas, slot 0 is yours
too (e.g. @get('/whoami') async whoami(@inject(USER) user) { … }).
MCP tool class
import {z} from 'zod';
import {mcpServer, tool, MCPComponent} from '@agentback/mcp';
const ForecastInput = z.object({
city: z.string(),
days: z.number().int().min(1).max(7),
});
const ForecastOutput = z.object({
city: z.string(),
forecast: z.string(),
});
@mcpServer()
class WeatherTools {
@tool('get_forecast', {
description: 'Returns the forecast for a city.',
input: ForecastInput,
output: ForecastOutput,
})
async getForecast(input: z.infer<typeof ForecastInput>) {
return {city: input.city, forecast: 'sunny'};
}
}
const app = new RestApplication();
app.component(MCPComponent); // registers MCPServer
app.service(WeatherTools); // tag flows from @mcpServer's @bind metadata
await app.start();
// stdio MCP transport active by default; mount mcp-inspector for a UI
The schemas live once, on the decorator. The parameter type is derived
via z.infer<typeof ForecastInput> — if you change the schema, TS
rewrites the parameter type. With output: declared, the return type
is also constrained at compile time and validated at runtime; the MCP
SDK is given the schema so structured-content clients can consume it
directly. Omit output: to keep the method's return type unconstrained.
The @mcpServer() decorator uses @bind({tags: {mcpServer: true}}) under the
hood. When you bind the class with app.service() (or app.controller()),
the framework reads that metadata via createServiceBinding and the
mcpServer tag is applied automatically — no manual .tag() call needed.
The agent-native contract
Beyond schemas, the framework ships the conventions agents need from an API:
@post('/deploy', {body: DeployIn, response: DeployOut, confirm: true})
async deploy(input: {body: z.infer<typeof DeployIn>}) { … }
// 1st call -> 409 {error: {code: 'confirmation_required', confirmationToken, hint}}
// identical retry with x-confirmation-token header -> executes.
// The token is single-use and bound to the exact payload — a confirmed
// call cannot differ from the proposed one. Same flow on MCP tools via
// @tool(..., {confirm: true}) and a `confirmationToken` input property.
@post('/charge', {body: ChargeIn, response: ChargeOut, idempotency: true})
async charge(input: {body: z.infer<typeof ChargeIn>}) { … }
// Replaying an idempotency-key header returns the original result without
// re-executing; concurrent duplicates share one execution; errors aren't cached.
- Errors are machine-actionable. Every failure is
{error: {statusCode, code, message, issues?, schema?, retryable, hint?}}— a stablecode(never parsemessage), per-fieldissues, the violated section's JSON Schema inline, and a one-line remediation hint. MCP tool errors carry the same envelope as REST, so one parser self-corrects on both surfaces. - The API documents itself to agents.
app.start()serves/llms.txt(compact endpoint index) and/llms-full.txt(full inlined schemas) from the same registry as/openapi.json;generateAgentContext()renders an agent-context manual (CLAUDE.md shape) for the live API. Components append sections via theAX_SECTION_TAGbinding tag —installMcpHttpadds the MCP tool listing automatically. - Tool definitions are a context budget.
mcpServer.toolCostReport()token-prices everytools/listentry and totals what each connection costs a caller's context window;formatToolCostReport()flags over-budget tools.
Design pivots from the upstream LoopBack 4
Three packages were rewritten rather than ported wholesale because the upstream code carries baggage the fork doesn't want:
openapi— the upstream@loopback/openapi-v3is built aroundopenapi3-ts@2.xloose types and a JSON-Schema-via-@loopback/repository-json-schemapipeline. We emit OpenAPI 3.1.1 directly from Zod viaz.toJSONSchema({target: 'draft-2020-12'}), which aligns with OpenAPI 3.1's dialect.rest— the upstream@loopback/restis ~10k LoC of sequences, actions, and middleware composition. We have a minimal RestServer that handles routing, Zod request/body validation, error mapping, and serves the OpenAPI document.mcp-inspector— the official@modelcontextprotocol/inspectoris a CLI tool, not an embeddable UI. We ship a small DOM-built inspector that talks to the in-process MCPServer directly via a JSON API.
The DI foundation (metadata, context, core) and the
http-server / express integrations are faithful ESM ports — same
source as upstream LoopBack 4, with .js extensions on relative
imports, lodash → lodash-es, and p-event v6 named exports. The
DI semantics (binding scopes, @inject, providers, interceptors,
extension points, observers) match @loopback/context and
@loopback/core exactly; if you know LB4 DI, you already know this.
What's deferred
Truly out of scope for v0
These are deliberately not in the framework — they reintroduce the upstream complexity the rewrite walked away from.
- LB4 sequences/actions (
findRoute → parseParams → invoke → send → rejectDI pipeline).RestServeris a monolithic dispatcher; per-route customization lives on the decorator, cross-cutting in middleware/interceptors, and deeper changes in subclassingRestServerand overridingdispatch/sendResult/sendError. @loopback/repositoryand theFilter<T>/Where<T>helpers.x-ts-typeinlining — replaced by Zod schemas attached to route metadata.@oas.deprecated/@oas.tags/@oas.visibilitydecorator namespace.
Already available, just not as polished
- Middleware composition —
@agentback/expressships the LB4 middleware machinery, andRestApplicationexposesapp.middleware(...)andapp.expressMiddleware(...). Registered middleware runs through the framework's chain before every route handler. - CORS — set
cors: true(or passCorsOptions) onRestServerConfig; thecorspackage is mounted globally. - MCP over Streamable HTTP —
@agentback/mcp-http'sinstallMcpHttp(app)exposes the in-process MCP server at/mcpso remote clients (Claude, Cursor) can reach the same tools; stdio remains the default. Supports OAuth 2.1 resource-server protection (auth:option +/.well-known/oauth-protected-resource), scope-based tool ACL (@tool(..., {scope})), and DNS-rebinding protection.
Not yet implemented
- MCP SSE (legacy) transport — Streamable HTTP is supported; the older SSE transport is not.
- MCP resource/prompt aggregation in the gateway —
@agentback/mcp-hostaggregates upstream tools today; resource/prompt routing is a straightforward follow-on.
About the test story
We use Vitest (2000+ tests across the workspace), not LB4's mocha/should ports. Tests run against built dist/ — pnpm build before pnpm test.
Development
Contributions welcome — see CONTRIBUTING.md for setup, conventions, and the proposal process.
pnpm install # install all workspace deps
pnpm build # tsc -b across the workspace
pnpm test # vitest run — IMPORTANT: requires a prior `pnpm build`
pnpm -F <pkg> build # build a single package
Tests run against built dist/. vitest.config.ts globs
packages/*/dist/__tests__/**/*.{test,spec,unit,integration,acceptance}.js,
so editing a .ts file requires pnpm build (or pnpm build:watch)
before pnpm test sees the change.
TypeScript project references keep incremental builds fast. ESLint flat config + Prettier match the LB4 conventions (single quotes, no bracket spacing, 80 col).
A note on the verb/tool input shape
Schemas live on the decorator (@get/@post/...'s options object,
@tool's input/output). The handler always receives one
positional input bundle whose type is derived via z.infer. @inject
parameters live at slot 1+ when schemas are declared; when no schemas
are declared, slot 0 is free for @inject too. The slot-0 reservation
is enforced at decoration time, and URL placeholders are cross-checked
against the path: schema at app.start().
License
MIT.