Getting Started
This guide will help you set up @cognipeer/agent-server in your project.
Upgrading?
Coming from 0.1.x or 0.2.x? Read Upgrading to 0.3.0 first: listing conversations now needs a user, JWT signatures are verified, and a client that disconnects no longer stops its turn.
Requirements
- Node.js 18 or newer. The package is ESM-only (
import);require()works on Node 20.19+ / 22.12+ (require(esm)). - Every integration is an optional peer dependency - install what you use:
| You use | Install | Minimum |
|---|---|---|
| PostgreSQL | pg | 8 |
| MongoDB | mongodb | 6 |
| SQLite | better-sqlite3 | 11 |
| Express | express | 4 |
| Next.js | next | 13 |
| Fastify | fastify | 4 |
| agent-sdk agents | @cognipeer/agent-sdk | 0.1.0 (0.10.6 for a Stop that hangs up on the model) |
| PDF / Office files read by the agent | @cognipeer/to-markdown | 3 |
Installation
Install the core package:
npm install @cognipeer/agent-serveryarn add @cognipeer/agent-serverpnpm add @cognipeer/agent-serverInstall your preferred storage provider and framework:
# PostgreSQL
npm install pg
# MongoDB
npm install mongodb
# SQLite (one process, one file)
npm install better-sqlite3
# Express
npm install expressA complete, runnable server (SQLite or MongoDB, an agent-sdk agent, approvals, files, a host-backed agent) is in examples/standalone.
Quick Start with Express
Here's a minimal example to get you started:
import express from 'express';
import {
createAgentServer,
createInMemoryProvider,
createExpressMiddleware,
} from '@cognipeer/agent-server';
// Create an in-memory storage (for development)
const storage = createInMemoryProvider();
// Create the agent server
const agentServer = createAgentServer({
basePath: '/api/agents',
storage,
swagger: { enabled: true },
// Listing conversations needs to know who is asking. This quick start has no sign-in, so everybody is
// the same person; with real users, use `resolveContext` or `auth` instead and drop this line.
allowAnonymousList: true,
});
// Register a simple echo agent
agentServer.registerCustomAgent('echo', {
processMessage: async ({ message }) => ({
content: `Echo: ${message}`,
}),
}, {
name: 'Echo Bot',
description: 'A simple echo bot',
});
// Create Express app
const app = express();
app.use(express.json());
// Connect storage and start server
await storage.connect();
app.use(createExpressMiddleware(agentServer));
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
console.log('Swagger UI at http://localhost:3000/api/agents/docs');
});Quick Start with Next.js
For Next.js App Router:
// app/api/agents/[...path]/route.ts
import {
createAgentServer,
createInMemoryProvider,
createNextRouteHandlers,
} from '@cognipeer/agent-server';
const storage = createInMemoryProvider();
const agentServer = createAgentServer({
basePath: '/api/agents',
storage,
swagger: { enabled: true },
allowAnonymousList: true, // no sign-in in this quick start; see "Who may list" in Request Context
});
// Register your agents
agentServer.registerCustomAgent('echo', {
processMessage: async ({ message }) => ({
content: `Echo: ${message}`,
}),
});
await storage.connect();
export const { GET, POST, PATCH, DELETE, OPTIONS } = createNextRouteHandlers(agentServer);Using with Agent SDK
If you're using @cognipeer/agent-sdk, you can register agents directly:
import { createSmartAgent, fromLangchainModel } from '@cognipeer/agent-sdk';
import { ChatOpenAI } from '@langchain/openai';
// Create your agent
const myAgent = createSmartAgent({
name: 'Assistant',
model: fromLangchainModel(new ChatOpenAI({ modelName: 'gpt-4' })),
tools: [...],
});
// Register with the server
agentServer.registerSDKAgent('assistant', myAgent, {
description: 'A helpful AI assistant',
});Your own backend as an agent
If the agent's work happens somewhere else - a product runtime behind an API, a workflow engine - register it as a host-backed agent: it streams with emit, pauses by returning pendingActions, and the server keeps the messages, the events and the pause. See Host-backed agents.
Project Structure
Here's a recommended project structure:
my-agent-app/
├── src/
│ ├── index.ts # Main entry point
│ ├── agents/
│ │ ├── assistant.ts # Agent definitions
│ │ └── tools/ # Agent tools
│ └── config/
│ └── database.ts # Storage configuration
├── package.json
└── tsconfig.jsonEnvironment Variables
We recommend using environment variables for configuration:
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
# Authentication (the secret your JWTs are signed with; the server verifies their signature with it)
JWT_SECRET=your-secret-key
# Server
PORT=3000
NODE_ENV=developmentWhich guide next
| I want to ... | Read |
|---|---|
| understand the pieces | Core Concepts, Architecture |
| keep data in a real database | Storage Providers |
| tell the server who is asking | Authentication, Request Context |
| let a person approve tool calls or answer questions | Approvals & Questions |
| survive reloads, offer a Stop button | Runs, Cancel & Reattach |
| let agents read uploaded files | Files |
| limit what a conversation costs | Usage & Budgets |
| serve an agent that runs in my own backend | Host-backed agents |
| build a chat product (regenerate, pin, feedback, export) | Chat experience |
| embed the chat in another site | Embedding & limits |
| something does not work | Troubleshooting |
Next Steps
- Core Concepts - Understand the architecture
- Storage Providers - Set up PostgreSQL, MongoDB or SQLite
- Authentication - Secure your API
- Express Integration - Detailed Express setup
- Next.js Integration - Detailed Next.js setup

