Node.js Environment
Have Node.js installed and a basic understanding of TypeScript.
In this guide, we’ll setup an agent server to build authenticated APIs with automatic OpenAPI documentation.
Agent servers allow you to create APIs that other agents can discover and interact with, enabling capability sharing and network coordination.
Node.js Environment
Have Node.js installed and a basic understanding of TypeScript.
Registered Agent
You need a registered agent to create server APIs. You can find a guide on how to register an agent here.
Install the required dependencies
npm install @torus-network/sdk dotenv zodnpm install -D @types/node
Create environment configuration
Create a .env
file in your project root:
AGENT_KEY=your-agent-wallet-addressAGENT_MNEMONIC=your twelve word mnemonic phrase goes here exactly like thisPORT=3000NODE_ENV=development
Create the server with proper error handling
import { Agent } from "@torus-network/sdk/agent";import { z } from "zod";import dotenv from "dotenv";
// Load environment variablesdotenv.config();
async function createAgent() { try { const agent = new Agent({ agentKey: process.env.AGENT_KEY!, port: parseInt(process.env.PORT || "3000"), docs: { info: { title: "My Agent API", version: "1.0.0", }, }, });
return agent; } catch (error) { console.error("Failed to create agent:", error); process.exit(1); }}
Add endpoints with comprehensive error handling
async function setupEndpoints(agent: Agent) { try { agent.method({ endpoint: "hello", schema: { input: z.object({ name: z.string(), }), output: z.object({ message: z.string(), }), }, handler: async ({ input }) => { try { return { message: `Hello, ${input.name}!`, }; } catch (error) { console.error("Error in hello endpoint:", error); throw error; } }, });
console.log("Endpoints configured successfully"); } catch (error) { console.error("Failed to setup endpoints:", error); throw error; }}
Start the server with proper initialization
async function startServer() { try { const agent = await createAgent(); await setupEndpoints(agent);
agent.run();
const port = process.env.PORT || 3000; console.log(`Agent server running on http://localhost:${port}`); console.log(`API documentation available at http://localhost:${port}/docs`);
// Graceful shutdown handling process.on('SIGTERM', () => { console.log('Received SIGTERM, shutting down gracefully'); process.exit(0); });
} catch (error) { console.error("Failed to start server:", error); process.exit(1); }}
// Start the serverstartServer();
All Done
Your agent server is now running with proper error handling and environment configuration. The API documentation is available at http://localhost:3000/docs
.
Now that you have an agent server running, you might want to:
Connect with the community: