Cogitator
Server Adapters

Express Adapter

Serve your Cogitator agents over HTTP with Express.js — class-based setup with middleware, SSE streaming, and WebSocket support.

The @cogitator-ai/express package provides CogitatorServer, a class that mounts a full REST API onto your existing Express router. It handles JSON parsing, authentication, rate limiting, CORS, error handling, Swagger docs, and WebSocket support out of the box.

Installation

pnpm add @cogitator-ai/express express

Basic Setup

import express from 'express';
import { Cogitator, Agent, tool } from '@cogitator-ai/core';
import { CogitatorServer } from '@cogitator-ai/express';
import { z } from 'zod';

const app = express();

const cogitator = new Cogitator({
  llm: {
    defaultModel: 'openai/gpt-6.1-sol',
    providers: {
      openai: { apiKey: process.env.OPENAI_API_KEY! },
    },
  },
});

const search = tool({
  name: 'web_search',
  description: 'Search the web',
  parameters: z.object({ query: z.string() }),
  execute: async ({ query }) => ({ results: [`Result for: ${query}`] }),
});

const assistant = new Agent({
  name: 'assistant',
  description: 'Assistant with web search',
  model: 'openai/gpt-6.1-sol',
  instructions: 'You are a helpful assistant with web search capabilities.',
  tools: [search],
});

const server = new CogitatorServer({
  app: app,
  cogitator,
  agents: { assistant },
  config: {
    basePath: '/cogitator',
    enableSwagger: true,
    enableWebSocket: false,
  },
});

await server.init();

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
  console.log('Swagger UI: http://localhost:3000/cogitator/docs');
});

Configuration

The CogitatorServerConfig interface accepts:

interface CogitatorServerConfig {
  app: Router;
  cogitator: Cogitator;
  agents?: Record<string, Agent>;
  workflows?: Record<string, Workflow>;
  swarms?: Record<string, SwarmConfig>;
  triggers?: TriggersHost; // experimental: the trigger manager, serves /triggers/:id/fire, /webhook and /inbox
  config?: {
    basePath?: string; // default: '/cogitator'
    enableWebSocket?: boolean; // default: false
    enableSwagger?: boolean; // default: true
    auth?: AuthFunction;
    rateLimit?: RateLimitConfig;
    cors?: CorsConfig;
    swagger?: SwaggerConfig;
    websocket?: WebSocketConfig; // { path?, pingInterval? (ms, default 30000), maxPayloadSize? (bytes, default 1 MiB), deps? }
    sseHeartbeatMs?: number; // SSE heartbeat interval in ms, default 5000, 0 turns it off
    acceptContext?: boolean | string[]; // context keys clients may send: none by default, a list, or true for any
    threadMessageRoles?: ('user' | 'assistant' | 'system')[]; // roles of POST /threads/:id/messages, default user and assistant
    limits?: RunLimits; // caps on swarm timeout and workflow iterations and concurrency
    anonymous?: 'allow' | 'deny'; // default: 'allow'
    authorizeThread?: (
      auth: AuthContext | undefined,
      threadId: string
    ) => boolean | Promise<boolean>;
    deps?: (req: Request) => unknown | Promise<unknown>; // deps of HTTP agent runs, built per request
    workflowCheckpoints?: CheckpointStore; // workflow checkpoints and /workflows/:name/resume, none by default
  };
}

With triggers the server serves the trigger and inbox routes: the two trigger routes go before the JSON parser, auth and rateLimit, reading the body raw, and the inbox routes after auth like every other route.

init() mounts the router once (calling it again does nothing); server.isInitialized tells whether it ran. It writes nothing to the console: init() and the WebSocket setup report through the core logger at debug level (LOG_LEVEL=debug, or your own logger via setLogger() from @cogitator-ai/core).

Request Handling

  • Agent and swarm bodies are validated: input must contain more than whitespace ("" and " " are refused before the model is called), context an object, threadId a non-empty string, swarm timeout a positive number of at most MAX_RUN_TIMEOUT_MS (2147483647, the longest delay a timer can hold). Invalid or malformed JSON bodies return 400 INVALID_INPUT.
  • Workflow options are limited to maxConcurrency, maxIterations (positive integers) and checkpoint (boolean), other options are dropped and wrongly typed ones return 400. checkpoint: true needs config.workflowCheckpoints, which also serves POST /workflows/:name/resume and /resume/stream, see Workflow checkpoints.
  • With limits set, a swarm timeout and workflow maxIterations and maxConcurrency are held to the operator's caps, and a request that asks for nothing gets the cap. See Limits.
  • Thread messages need a role of user, assistant or system and a non-empty string content.
  • A workflow that fails answers the error it failed with, mapped like any run error (a node that hit LLM_RATE_LIMITED answers 429 with Retry-After, an internal error 500 INTERNAL_ERROR), and its stream ends with a workflow_failed event and an error event carrying that code instead of workflow_completed. A run with options.checkpoint names the last checkpoint it saved as checkpointId in both, to resume it from. Without @cogitator-ai/workflows or @cogitator-ai/swarms installed, those routes return 501 UNIMPLEMENTED.
  • Unknown agents, workflows, swarms and routes return 404 NOT_FOUND, except that under anonymous: 'deny' an unknown route answers a caller without a userId with 401 UNAUTHORIZED. GET /swarms/:name/blackboard returns the swarm's configured blackboard.sections, or 400 when its blackboard is not enabled.
  • The thread routes use cogitator.getMemory() and return 503 UNAVAILABLE when the runtime has no memory. Another user's thread returns 403 THREAD_ACCESS_DENIED, and a thread authorizeThread refuses 403 THREAD_FORBIDDEN.
  • GET /threads/:id answers the whole thread, or with ?limit=50 the newest 50 messages and a nextCursor, which ?limit=50&cursor=<nextCursor> follows to the page before. A bad limit or cursor returns 400 INVALID_INPUT.
  • CogitatorErrors keep their message and code and answer with their own statusCode (the code's mapped status unless the error carries another, for example LLM_RATE_LIMITED → 429), plus Retry-After in whole seconds when the error says when to retry. A swarm that runs out of time answers 504 RUN_TIMEOUT. Any other error is logged and answered as 500 with { "error": { "message": "Internal server error", "code": "INTERNAL_ERROR" } }. Every adapter maps errors with describeHttpError of @cogitator-ai/server-shared.
  • GET /agents exposes each agent's config.description, never its instructions.

Authentication

Pass a custom auth function that receives the Express request and returns an AuthContext:

const server = new CogitatorServer({
  app,
  cogitator,
  agents: { assistant },
  config: {
    auth: async (req) => {
      const token = req.headers.authorization?.replace('Bearer ', '');
      if (!token) return undefined;

      const user = await verifyToken(token);
      return { userId: user.id, roles: user.roles };
    },
  },
});

When auth returns undefined, the request proceeds as unauthenticated; throw to reject it with 401 UNAUTHORIZED. The AuthContext is attached to req.cogitator.auth (next to requestId and startTime), and its userId is passed to agent and swarm runs and scopes the thread routes.

The same function guards WebSocket upgrades. There it receives the raw upgrade request (http.IncomingMessage), not an Express request, so read only headers and url in code that serves both.

Anonymous callers

anonymous: 'deny' answers 401 UNAUTHORIZED to every caller whose auth returned no userId, and refuses their WebSocket upgrade. /health, /ready, /openapi.json and /docs stay open. Any other path under the base path answers 401 too, known or not, so an anonymous caller cannot probe which routes exist. The default, 'allow', lets them in, and an unknown path answers 404 NOT_FOUND in the error envelope.

Thread authorization

authorizeThread(auth, threadId) decides who may touch a thread, on top of the ownership check of core, for example threads a whole team shares:

config: {
  auth,
  authorizeThread: async (auth, threadId) => teams.canAccess(auth?.userId, threadId),
}

It runs on every route that names a thread: agent run, stream and resume, swarm run and stream, GET, DELETE and POST /threads/:id/messages, and WebSocket runs with a threadId. Answering false refuses the request with 403 THREAD_FORBIDDEN before any run starts. It also decides which WebSocket subscribers see a run's events.

Limits

limits caps what a request may ask a run for:

config: {
  limits: { swarmTimeout: 120_000, workflowMaxIterations: 50, workflowMaxConcurrency: 4 },
}

A request is never refused over a limit. It gets the smaller of what it asked for and the cap, or the cap when it asked for nothing, on the run and stream routes alike. The OpenAPI spec gives each cap as the default of its field. Each limit must be a positive integer, or the constructor throws.

Request Dependencies

deps builds what an agent's tools read as context.deps for each request, on the server, never from the request body:

config: {
  deps: async (req) => ({ db: await tenantDb(req.get('x-tenant')) }),
  websocket: {
    deps: async (req) => ({ db: await tenantDb(req.headers['x-tenant']) }),
  },
}

HTTP agent runs, streams and resumes get what deps builds. An error the hook throws is answered like a run error, before a stream starts.

WebSocket runs and resumes get what websocket.deps builds from the upgrade request, called for each run. That request is a plain Node IncomingMessage that never went through Express, so it has headers, url and socket but no req.get() and nothing a middleware adds, which is why it has a hook of its own. Without websocket.deps WebSocket runs get no deps. An error it throws, or one authorizeThread throws, answers an error frame and starts no run.

Rate Limiting

config: {
  rateLimit: {
    windowMs: 60_000,
    max: 100,
    message: 'Too many requests',
    keyGenerator: (req) => req.ip ?? 'unknown',
    skip: (req) => req.path === '/health',
    trustProxy: false, // true: key by the nearest X-Forwarded-For hop (the address your proxy saw)
  },
}

The limiter is in-memory and per process; windowMs must be positive and max non-negative, otherwise creating the middleware throws. Requests without a client address share a single bucket.

CORS

config: {
  cors: {
    origin: ['https://app.example.com'],
    credentials: true,
    methods: ['GET', 'POST', 'DELETE'],
  },
}

Preflights allow the headers of CORS_ALLOWED_HEADERS from @cogitator-ai/server-shared by default: Content-Type, Authorization, X-Request-ID and Last-Event-ID, which a client on another origin sends to reconnect to a resumable stream. An allowedHeaders of your own replaces the list, so keep Last-Event-ID in it.

credentials defaults to true for explicit origins and to false for origin: '*' (plain Access-Control-Allow-Origin: *). Setting credentials: true together with '*' reflects every origin with credentials — only do that deliberately. Disallowed origins get no CORS grants, including on preflight.

Streaming

The /agents/:name/stream endpoint returns an SSE stream: start, text-start/text-delta/text-end blocks, tool-call-start/tool-call-delta/tool-call-end as the model writes the call (the id is the model's tool call id, matching tool-result.toolCallId), tool-update while the tool runs, tool-result, then finish and [DONE], or an error event. Disconnecting aborts the run. With resumableStreams on, a client that disconnects no longer stops the run: it reconnects with Last-Event-ID and gets the rest, see Resumable Streams. Read it with fetch (EventSource cannot send a POST body):

const response = await fetch('http://localhost:3000/cogitator/agents/assistant/stream', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ input: 'Explain quantum computing' }),
});

const reader = response.body!.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  console.log(decoder.decode(value));
}

WebSocket

WebSocket support requires the ws package. Enable it, then attach it to your HTTP server after init():

import { createServer } from 'http';

const server = new CogitatorServer({
  app,
  cogitator,
  agents: { assistant },
  config: { enableWebSocket: true },
});
await server.init();

const httpServer = createServer(app);
await server.attachWebSocket(httpServer); // ws://host/cogitator/ws
httpServer.listen(3000);

attachWebSocket() returns the WebSocketServer, and throws when enableWebSocket is off, when init() has not run, or when ws is not installed. A run or resume on a thread authorizeThread refuses answers with an error frame and starts nothing. The path is <basePath>/ws, and websocket.path replaces it with a full path. The server pings every pingInterval ms and drops clients that stop answering.

Run an agent (only agent runs are supported; workflow and swarm runs answer with an error):

{
  "type": "run",
  "id": "req_1",
  "payload": { "type": "agent", "name": "assistant", "input": "Hello", "threadId": "t1" }
}

Events arrive as { "type": "event", "id": "req_1", "payload": { "type": "token" | "reasoning" | "tool-call" | "tool-result" | "complete" | "cancelled", ... } }, and failures as { "type": "error", "id": "req_1", "error": "..." }. Resume a run paused for approval with { "type": "resume", "id": "req_2", "payload": { "name": "assistant", "threadId": "t1", "decisions": { "call_1": { "approved": true } } } }. Send { "type": "stop" } to abort the running agent and { "type": "ping" } to get a pong. A new run or resume aborts the one still running on that connection.

{ "type": "subscribe", "channel": "agent:assistant" } (answered with subscribed) delivers the events of runs of that agent started from other connections of the same user (the userId your auth returned), with channel set on each frame, and unsubscribe stops them. Runs of other users never reach the subscriber. With authorizeThread set, a subscriber also sees a run only when authorizeThread(subscriberAuth, threadId) allows it on the run's thread (the run's threadId, or the one core created for it). It is asked once per subscriber and run, and a subscriber it refuses, or throws for, gets none of the run's events. Without auth every connection counts as the same anonymous user, so without authorizeThread it sees every run of that agent. A connection holds up to 64 subscriptions of at most 256 characters.

Exported Utilities

The package also exports individual building blocks if you need to compose routes manually:

import {
  createAuthMiddleware,
  createAnonymousGuard,
  createRateLimitMiddleware,
  createCorsMiddleware,
  createHealthRoutes,
  createAgentRoutes,
  createThreadRoutes,
  createToolRoutes,
  createWorkflowRoutes,
  createSwarmRoutes,
  errorHandler,
  notFoundHandler,
  ExpressStreamWriter,
  setupSSEHeaders,
  generateOpenAPISpec,
  serveSwaggerUI,
  setupWebSocket,
} from '@cogitator-ai/express';

On this page