Server Adapter Configuration Reference
This document provides a comprehensive reference for all configuration options available in NeuroLink Server Adapters.
Configuration via CLI
In addition to programmatic configuration, NeuroLink provides CLI commands to view and manage server settings.
Viewing Configuration
# Show all configuration
neurolink server config
# Output as JSON
neurolink server config --format json
# Get specific value
neurolink server config --get defaultPort
neurolink server config --get cors.enabled
neurolink server config --get rateLimit.maxRequests
Modifying Configuration
# Set configuration values
neurolink server config --set defaultPort=8080
neurolink server config --set defaultFramework=express
neurolink server config --set cors.enabled=true
neurolink server config --set rateLimit.maxRequests=200
# Reset to defaults
neurolink server config --reset
Configuration File Location
CLI configuration is stored at:
- Config file:
~/.neurolink/server-config.json - Server state:
~/.neurolink/server-state.json
CLI vs Programmatic Configuration
| Aspect | CLI Config | Programmatic Config |
|---|---|---|
| Persistence | File-based, survives restarts | In-memory, per-instance |
| Scope | Global defaults | Per-server instance |
| Use Case | Development, quick changes | Production, fine-grained control |
The CLI configuration provides default values that can be overridden programmatically:
// CLI defaults are used when not specified
const server = await createServer(neurolink, {
framework: "hono", // Overrides CLI default
// port uses CLI default if not specified
});
ServerAdapterConfig
The main configuration object for server adapters.
type ServerAdapterConfig = {
port?: number;
host?: string;
basePath?: string;
cors?: CORSConfig;
rateLimit?: RateLimitConfig;
bodyParser?: BodyParserConfig;
logging?: LoggingConfig;
shutdown?: ShutdownConfig;
redaction?: RedactionConfig;
timeout?: number;
enableMetrics?: boolean;
enableSwagger?: boolean;
disableBuiltInHealth?: boolean;
};
Core Options
| Option | Type | Default | Description |
|---|---|---|---|
port | number | 3000 | Server port to listen on |
host | string | "0.0.0.0" | Server host/interface to bind |
basePath | string | "/api" | Base path prefix for all routes |
timeout | number | 30000 | Request timeout in milliseconds |
enableMetrics | boolean | true | Enable metrics endpoint |
enableSwagger | boolean | false | Enable OpenAPI/Swagger documentation (see below) |
disableBuiltInHealth | boolean | false | Disable built-in health routes |
OpenAPI/Swagger Documentation (enableSwagger)
When enableSwagger is set to true, the server exposes interactive API documentation endpoints:
| Endpoint | Description |
|---|---|
GET {basePath}/openapi.json | OpenAPI 3.1 specification in JSON format |
GET {basePath}/openapi.yaml | OpenAPI 3.1 specification in YAML format |
GET {basePath}/docs | Interactive Swagger UI documentation |
Example URLs (with default basePath /api):
http://localhost:3000/api/openapi.jsonhttp://localhost:3000/api/openapi.yamlhttp://localhost:3000/api/docs
The Swagger UI provides an interactive interface where you can:
- Browse all available API endpoints
- View request/response schemas
- Test API calls directly from the browser
- Download the OpenAPI specification
Security Consideration: In production environments, consider disabling
enableSwaggerto prevent exposing internal API structure. Alternatively, protect the documentation endpoints with authentication middleware.
Example: Basic Configuration
import { createServer } from "@juspay/neurolink";
const server = await createServer(neurolink, {
config: {
port: 8080,
host: "127.0.0.1",
basePath: "/v1/api",
timeout: 60000,
enableSwagger: true,
},
});
CORS Configuration
type CORSConfig = {
enabled?: boolean;
origins?: string[];
methods?: string[];
headers?: string[];
credentials?: boolean;
maxAge?: number;
};
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable CORS support |
origins | string[] | ["*"] | Allowed origins |
methods | string[] | ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"] | Allowed HTTP methods |
headers | string[] | ["Content-Type", "Authorization"] | Allowed headers |
credentials | boolean | false | Allow credentials |
maxAge | number | 86400 | Preflight cache max age in seconds |
Security Warning: The default wildcard origin
["*"]allows requests from any domain. In production environments, always specify explicit allowed origins to prevent unauthorized cross-origin requests.
Example: Restrictive CORS
const server = await createServer(neurolink, {
config: {
cors: {
enabled: true,
origins: ["https://myapp.com", "https://staging.myapp.com"],
methods: ["GET", "POST"],
headers: ["Content-Type", "Authorization", "X-Request-ID"],
credentials: true,
maxAge: 3600,
},
},
});
Rate Limit Configuration
type RateLimitConfig = {
enabled?: boolean;
windowMs?: number;
maxRequests?: number;
message?: string;
skipPaths?: string[];
keyGenerator?: (ctx: ServerContext) => string;
};
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable rate limiting |
windowMs | number | 900000 (15 min) | Time window in milliseconds |
maxRequests | number | 100 | Maximum requests per window |
message | string | "Too many requests..." | Error message when limit exceeded |
skipPaths | string[] | [] | Paths to exclude from rate limiting |
keyGenerator | function | IP-based | Custom function to generate rate limit key |
Example: Custom Rate Limiting
const server = await createServer(neurolink, {
config: {
rateLimit: {
enabled: true,
windowMs: 60000, // 1 minute
maxRequests: 30,
skipPaths: ["/api/health", "/api/ready", "/api/version"],
keyGenerator: (ctx) => {
// Rate limit by API key instead of IP
return (
ctx.headers["x-api-key"] ||
ctx.headers["x-forwarded-for"] ||
"unknown"
);
},
},
},
});
Body Parser Configuration
type BodyParserConfig = {
enabled?: boolean;
maxSize?: string;
jsonLimit?: string;
urlEncoded?: boolean;
};
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable body parsing |
maxSize | string | "10mb" | Maximum body size |
jsonLimit | string | "10mb" | JSON body size limit |
urlEncoded | boolean | true | Enable URL-encoded body parsing |
Example: Large Payload Support
const server = await createServer(neurolink, {
config: {
bodyParser: {
enabled: true,
maxSize: "50mb",
jsonLimit: "50mb",
urlEncoded: true,
},
},
});
Logging Configuration
type LoggingConfig = {
enabled?: boolean;
level?: "debug" | "info" | "warn" | "error";
includeBody?: boolean;
includeResponse?: boolean;
};
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable request logging |
level | string | "info" | Log level |
includeBody | boolean | false | Include request body in logs |
includeResponse | boolean | false | Include response body in logs |
Example: Debug Logging
const server = await createServer(neurolink, {
config: {
logging: {
enabled: true,
level: "debug",
includeBody: true,
includeResponse: true,
},
},
});
Shutdown Configuration
type ShutdownConfig = {
gracefulShutdownTimeoutMs?: number;
drainTimeoutMs?: number;
forceClose?: boolean;
};
| Option | Type | Default | Description |
|---|---|---|---|
gracefulShutdownTimeoutMs | number | 30000 | Maximum time to wait for graceful shutdown (30 sec) |
drainTimeoutMs | number | 15000 | Time to drain existing connections (15 sec) |
forceClose | boolean | true | Force close connections after timeout |
Example: Custom Shutdown Timeouts
const server = await createServer(neurolink, {
config: {
shutdown: {
gracefulShutdownTimeoutMs: 60000, // 60 seconds for long-running requests
drainTimeoutMs: 30000, // 30 seconds to drain connections
forceClose: true, // Force close after timeout
},
},
});
Redaction Configuration
The redaction system provides automatic sanitization of sensitive data in logs and responses. This feature is opt-in and must be explicitly enabled.
type RedactionConfig = {
enabled?: boolean;
additionalFields?: string[];
preserveFields?: string[];
redactToolArgs?: boolean;
redactToolResults?: boolean;
placeholder?: string;
};
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable redaction (opt-in) |
additionalFields | string[] | [] | Extra field names to redact |
preserveFields | string[] | [] | Fields to exclude from redaction |
redactToolArgs | boolean | true | Redact tool arguments (when enabled) |
redactToolResults | boolean | true | Redact tool results (when enabled) |
placeholder | string | "[REDACTED]" | Replacement text for redacted values |
Default Redacted Fields
When redaction is enabled, the following fields are redacted by default:
apiKeytokenauthorizationcredentialspasswordsecretrequestargsresult
Example: Custom Redaction
const server = await createServer(neurolink, {
config: {
redaction: {
enabled: true,
additionalFields: ["ssn", "creditCard", "bankAccount"],
preserveFields: ["request"], // Allow 'request' field to pass through
redactToolArgs: true,
redactToolResults: false, // Keep tool results visible
placeholder: "***",
},
},
});
Example: Minimal Redaction
const server = await createServer(neurolink, {
config: {
redaction: {
enabled: true,
// Uses all defaults - redacts apiKey, token, password, etc.
},
},
});
Middleware Configuration
Authentication Middleware
import { createAuthMiddleware } from "@juspay/neurolink";
const authMiddleware = createAuthMiddleware({
type: "bearer", // 'bearer' | 'api-key' | 'basic' | 'custom'
validate: async (token, ctx) => {
// Return user info or null
const user = await verifyJWT(token);
return user ? { id: user.id, email: user.email, roles: user.roles } : null;
},
headerName: "Authorization", // Optional: custom header name
skipPaths: ["/api/health", "/api/ready"],
errorMessage: "Invalid authentication token",
});
server.registerMiddleware(authMiddleware);
Auth Types
| Type | Header Format | Description |
|---|---|---|
bearer | Authorization: Bearer <token> | JWT/OAuth token |
api-key | X-API-Key: <key> | API key authentication |
basic | Authorization: Basic <base64> | HTTP Basic auth |
custom | Custom | Use extractToken function |
Rate Limit Middleware
import {
createRateLimitMiddleware,
createSlidingWindowRateLimitMiddleware,
} from "@juspay/neurolink";
// Fixed window rate limiter
const rateLimiter = createRateLimitMiddleware({
maxRequests: 100,
windowMs: 15 * 60 * 1000,
skipPaths: ["/api/health"],
});
// Sliding window rate limiter (more accurate)
const slidingRateLimiter = createSlidingWindowRateLimitMiddleware({
maxRequests: 100,
windowMs: 15 * 60 * 1000,
subWindows: 10, // Number of sub-windows for smoothing
});
server.registerMiddleware(rateLimiter);
Cache Middleware
import { createCacheMiddleware, InMemoryCacheStore } from "@juspay/neurolink";
const cacheMiddleware = createCacheMiddleware({
ttlMs: 60 * 1000, // 1 minute cache
maxSize: 1000, // Max cached entries
methods: ["GET"], // Only cache GET requests
excludePaths: ["/api/agent/execute", "/api/agent/stream"],
includeQuery: true, // Include query params in cache key
ttlByPath: {
"/api/tools": 5 * 60 * 1000, // 5 minutes for tools
"/api/version": 60 * 60 * 1000, // 1 hour for version
},
});
server.registerMiddleware(cacheMiddleware);
Cache Response Headers
The cache middleware adds these headers to responses:
| Header | Description | Example |
|---|---|---|
X-Cache | Cache status | HIT or MISS |
X-Cache-Age | Seconds since cached (on HIT) | 45 |
Cache-Control | Caching directive (on MISS) | max-age=300 |
Validation Middleware
import {
createRequestValidationMiddleware,
createFieldValidator,
} from "@juspay/neurolink";
// JSON Schema validation
const validationMiddleware = createRequestValidationMiddleware({
body: {
type: "object",
properties: {
input: { type: "string", minLength: 1 },
provider: { type: "string" },
},
required: ["input"],
},
});
// Field-level validation
const fieldValidator = createFieldValidator({
required: ["name", "email"],
types: { name: "string", email: "string", age: "number" },
validators: {
email: (value) => typeof value === "string" && value.includes("@"),
age: (value) => typeof value === "number" && value >= 0,
},
});
server.registerMiddleware(validationMiddleware);
Role-Based Access Control
import { createRoleMiddleware } from "@juspay/neurolink";
// Require any of the specified roles
const adminMiddleware = createRoleMiddleware({
requiredRoles: ["admin", "superuser"],
requireAll: false, // Any role matches
errorMessage: "Admin access required",
});
// Require all specified roles
const superAdminMiddleware = createRoleMiddleware({
requiredRoles: ["admin", "superuser"],
requireAll: true, // All roles required
});
Framework-Specific Options
Hono
import { ServerAdapterFactory } from "@juspay/neurolink";
const server = await ServerAdapterFactory.createHono(neurolink, {
port: 3000,
// Hono uses @hono/node-server under the hood
});
For more details, see the Hono Guide.
Express
const server = await ServerAdapterFactory.createExpress(neurolink, {
port: 3000,
// Express-specific middleware can be added via getFrameworkInstance()
});
const app = server.getFrameworkInstance();
app.use(customExpressMiddleware);
For more details, see the Express Guide.
Fastify
const server = await ServerAdapterFactory.createFastify(neurolink, {
port: 3000,
// Fastify plugins can be registered on the instance
});
const fastify = server.getFrameworkInstance();
await fastify.register(customFastifyPlugin);
For more details, see the Fastify Guide.
Koa
const server = await ServerAdapterFactory.createKoa(neurolink, {
port: 3000,
// Koa middleware can be added via getFrameworkInstance()
});
const app = server.getFrameworkInstance();
app.use(customKoaMiddleware);
For more details, see the Koa Guide.
Complete Configuration Example
import {
createServer,
createAuthMiddleware,
createRateLimitMiddleware,
createCacheMiddleware,
} from "@juspay/neurolink";
import { NeuroLink } from "@juspay/neurolink";
const neurolink = new NeuroLink({
defaultProvider: "openai",
});
const server = await createServer(neurolink, {
framework: "hono",
config: {
port: 8080,
host: "0.0.0.0",
basePath: "/v1",
timeout: 120000,
enableSwagger: true,
cors: {
enabled: true,
origins: ["https://app.example.com"],
credentials: true,
},
rateLimit: {
enabled: true,
maxRequests: 1000,
windowMs: 3600000,
},
bodyParser: {
maxSize: "25mb",
},
logging: {
level: "info",
},
},
});
// Add custom middleware
server.registerMiddleware(
createAuthMiddleware({
type: "bearer",
validate: async (token) => verifyToken(token),
skipPaths: ["/v1/health", "/v1/ready"],
}),
);
server.registerMiddleware(
createCacheMiddleware({
ttlMs: 300000,
methods: ["GET"],
}),
);
// Start server
await server.start();
console.log(`Server running on http://localhost:8080`);
Environment Variables
The server adapters respect these environment variables:
| Variable | Description | Default |
|---|---|---|
PORT | Server port | 3000 |
HOST | Server host | 0.0.0.0 |
NODE_ENV | Environment mode | development |
npm_package_version | Package version (for health endpoint) | unknown |
Configuration Validation
Invalid configuration will throw errors at initialization:
// This will throw: "Invalid port number"
const server = await createServer(neurolink, {
config: { port: -1 },
});
// This will throw: "Invalid rate limit configuration"
const server = await createServer(neurolink, {
config: { rateLimit: { maxRequests: -100 } },
});
Always validate your configuration in development before deploying to production.
API Endpoints
The server adapters expose the following endpoints (all prefixed with basePath, default /api):
Health Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /health | Basic health check |
| GET | /ready | Readiness probe |
| GET | /live | Liveness probe |
| GET | /version | Version information |