Skip to main content
Glama
NestJS MCP Starter

NestJS MCP Starter

by ARG-Software
README.md
# NestJS MCP Starter

Production-ready Clean Architecture for APIs and AI agents.

REST + MCP. One application layer. No duplicated business logic.

NestJS · MCP · React · PostgreSQL · Redis · BullMQ · OpenTelemetry · Grafana

> REST controllers and MCP tools are interface adapters over the same application use cases.

```mermaid
flowchart LR
  REST[REST API\nPresentation] --> APP[Application\nUse Cases]
  MCP[MCP Server\nPresentation] --> APP
  APP --> DOMAIN[Domain]
  INFRA[PostgreSQL / Redis / BullMQ\nInfrastructure] --> APP
  INFRA --> DOMAIN
```

## 1. What Is This?

`nestjs-mcp-starter` is a customer-support backend starter showing how to expose the same business capability through REST and MCP without duplicating business logic.

## 2. Why REST + MCP?

REST serves conventional applications. MCP serves AI agents and assistants. Both should execute the same application use cases so behavior, authorization, persistence, jobs, and observability stay consistent.

## 3. Clean Architecture

The repository is organized by business capability first, then Clean Architecture layers:

```text
packages/tickets/src/domain
packages/tickets/src/application
packages/tickets/src/infrastructure
```

Runtime apps only contain adapters:

```text
apps/api  -> REST controllers
apps/mcp  -> MCP tools/transports
apps/worker -> background job processor
apps/web -> browser test console
```

## 4. Dependency Rule

```text
Domain <- Application <- Presentation
Domain/Application <- Infrastructure implementations
```

Domain and application do not import NestJS, Prisma, MCP, Redis, BullMQ, or HTTP libraries.

## 5. Quick Start

```bash
git clone https://github.com/ARG-Software/Nestjs-mcp-starter.git
cd Nestjs-mcp-starter
pnpm install
cp .env.example .env
pnpm docker:up
pnpm db:migrate
pnpm db:seed
pnpm dev
```

Open the test console at `http://localhost:5173`. It proxies `/api/*` to the REST API.

Open the observability console at `http://localhost:3002` and sign in with the
`GRAFANA_ADMIN_USER` and `GRAFANA_ADMIN_PASSWORD` values from `.env`.

If global `pnpm` is unavailable, use `npx pnpm@10.34.5`.

## 6. 60-second Demo

List unresolved high-priority enterprise tickets through MCP:

```json
{
  "tool": "list_tickets",
  "arguments": {
    "unresolved": true,
    "priority": "HIGH",
    "customerPlan": "ENTERPRISE",
    "order": "oldest"
  }
}
```

Assign the oldest ticket:

```json
{
  "tool": "assign_ticket",
  "arguments": {
    "ticketId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1",
    "assignee": "agent@example.com"
  }
}
```

## 7. Architecture

- `packages/customers` owns customer domain/application/infrastructure.
- `packages/tickets` owns ticket domain/application/infrastructure.
- `packages/knowledge` owns knowledge-base domain/application/infrastructure.
- `packages/auth` owns API-key authentication and authorization abstractions.
- `packages/shared` owns cross-cutting primitives and infrastructure utilities.

## 8. Project Structure

```text
apps/api
apps/mcp
apps/worker
apps/web
packages/auth
packages/customers
packages/tickets
packages/knowledge
packages/shared
prisma
docker
tests
```

## 9. Domain Layer

Domain entities include `Customer`, `Ticket`, `TicketComment`, and `KnowledgeArticle`. `Ticket` enforces assignment, comments, and resolution transitions.

Domain folders are explicit:

- `aggregates` for aggregate roots.
- `entities` for domain entities.
- `value-objects` for validated value objects.
- `types` for enums and literal unions.
- `repositories` for domain repository interfaces.
- `events` for domain events.
- `errors` for domain errors.

## 10. Application Layer

Use cases are the canonical API:

- `CreateTicketUseCase`
- `GetTicketUseCase`
- `ListTicketsUseCase`
- `AssignTicketUseCase`
- `AddTicketCommentUseCase`
- `ResolveTicketUseCase`
- `GetCustomerUseCase`
- `SearchCustomersUseCase`
- `SearchKnowledgeBaseUseCase`

Application folders are explicit:

- `use-cases` for application entry points.
- `ports` for outbound technical or cross-module dependencies.
- `contracts` for application data contracts.
- `results` for protocol-neutral result DTOs and mappers.
- `policies` for authorization/application policies.
- `services` for stateless application helpers.

## 11. Infrastructure Layer

Infrastructure implements repository and queue ports using Prisma and BullMQ.

Infrastructure folders are explicit:

- `persistence/prisma/repositories` for Prisma repositories.
- `persistence/prisma/mappers` for Prisma/domain mapping.
- `persistence/prisma/adapters` for persistence-backed outbound adapters.
- `messaging/bullmq` for BullMQ adapters.
- `configuration`, `observability`, `time`, and `identity` for shared adapters.
- `dependency-injection/nest` for Nest modules and provider wiring.

## 12. REST Adapter

REST controllers validate HTTP input, extract an actor, call use cases, and return application results.

## 13. MCP Adapter

MCP tools validate tool input with Zod, map to use-case input, call use cases, and return tool results.

## 14. MCP Tools

- `search_customers`
- `get_customer`
- `list_tickets`
- `get_ticket`
- `create_ticket`
- `assign_ticket`
- `add_ticket_comment`
- `resolve_ticket`
- `search_knowledge_base`

## 15. Web Console

`apps/web` is a React + Vite test console with shadcn-style local UI primitives. It supports API-key entry, health/readiness checks, customer search, ticket filtering/detail/create/assign/comment/resolve, and knowledge-base search.

## 16. Example Agent Workflow

The seed data supports finding unresolved high-priority enterprise tickets and assigning the oldest ticket to `agent@example.com` without fake data paths.

## 17. Authentication & Authorization

Static API keys map to `Actor` values with `AGENT` or `ADMIN` roles. REST and MCP both use the same `AuthenticateApiKeyUseCase` and application authorization policy.

## 18. Database

Prisma models customers, tickets, comments, and knowledge articles with UUIDs, relationships, enums, constraints, and indexes.

## 19. Background Jobs

Ticket created/resolved events enqueue BullMQ notification jobs. The worker logs mock delivery with retries and exponential backoff.

## 20. Observability

OpenTelemetry is initialized before application dependencies in each runtime and exports logs,
metrics, and traces over OTLP. The local `grafana/otel-lgtm` container provides one observability
entry point backed by Loki, Prometheus, and Tempo.

Open `http://localhost:3002` to use the provisioned application overview dashboard. It includes
request rate, error rate, latency, structured application logs, runtime memory, and recent traces.
Grafana links trace-correlated Pino logs to the corresponding Tempo trace. API keys,
authorization headers, and cookies are redacted from structured request logs.

Telemetry is near-real-time: logs and traces normally appear within a few seconds, while metrics
use the interval configured by `OTEL_METRIC_EXPORT_INTERVAL`.

## 21. Testing Strategy

- Domain unit tests do not require NestJS.
- Application unit tests use in-memory/fake ports.
- Integration and E2E tests are Docker-enabled through `RUN_DOCKER_TESTS=true`.
- The web console has its own Vite TypeScript check and production build.

## 22. Configuration

Environment variables are documented in `.env.example` and validated at runtime.

`CORS_ORIGINS` defaults to `http://localhost:5173` for the web console.

## 23. Docker

`docker-compose.yml` provides PostgreSQL, Redis, and a single Grafana OpenTelemetry LGTM
container. Only Grafana (`http://localhost:3002`) and OTLP/HTTP ingestion (`localhost:4318`) are
published for observability. The LGTM image is intended for local development, demos, and tests;
use managed or independently operated observability backends in production.

## 24. Production Considerations

Replace static API keys with OAuth/JWT verification, harden CORS/host policies, use managed PostgreSQL/Redis, and consider a transactional outbox for notification delivery guarantees.

## 25. Roadmap

- Add richer integration tests around Testcontainers.
- Add more MCP client examples.
- Add a transactional outbox variant.

## 26. Contributing

See `CONTRIBUTING.md` and `AGENTS.md`.