Koa with WebSocket
easy5 minkoa-server.ts
Your app is on Koa and clients want a WebSocket as well as REST.
What it shows
- Use the
cogitatorApp()router - Attach the WebSocket endpoint with
setupWebSocket()
The code
koa-server.ts
import { Agent, Cogitator, calculator } from '@cogitator-ai/core';
import { cogitatorApp, setupWebSocket } from '@cogitator-ai/koa';
import Koa from 'koa';
const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');
const cog = new Cogitator({ llm: { providers: { google: { apiKey } } } });
const assistant = new Agent({
name: 'assistant',
description: 'General assistant with a calculator tool',
model: 'google/gemini-3.5-flash-lite',
instructions: 'You are a helpful assistant. Use tools when appropriate. Be concise.',
tools: [calculator],
temperature: 0.3,
});
const router = cogitatorApp({ cogitator: cog, agents: { assistant }, enableSwagger: false });
const app = new Koa();
app.use(router.routes());
app.use(router.allowedMethods());
const server = app.listen(3103, () => console.log('Listening on http://localhost:3103'));
await setupWebSocket(server, {
runtime: cog,
agents: { assistant },
workflows: {},
swarms: {},
});Run it
install · bash
pnpm add @cogitator-ai/core @cogitator-ai/koa koaEnvironment
GOOGLE_API_KEYrun · bash
GOOGLE_API_KEY=your-key npx tsx koa-server.tsOr run the full example from a clone of the repository (keys in .env):
repository · bash
npx tsx examples/integrations/04-koa-server.tsTry it
Try it · bash
curl -X POST http://localhost:3103/agents/assistant/run \
-H 'Content-Type: application/json' -d '{"input": "What is 123 * 456?"}'
npx wscat -c ws://localhost:3103/ws
> {"type":"run","payload":{"type":"agent","name":"assistant","input":"Hi"}}