@ainetwork/adk
v0.7.6
Published
AI Network Agent Development Kit
Readme
AI Network Agent Development Kit (AIN-ADK)
A TypeScript library for building AI agents with multi-protocol support including MCP (Model Context Protocol) and A2A (Agent-to-Agent) communication.
NOTE
IMPORTANT: This project is currently under active development. Features may be incomplete, and there might be significant changes in future updates. Please be aware that some functionalities may not work as expected or might change without prior notice.
Features
- Multi-Protocol Support: Integrate with MCP servers and A2A agents
- Modular Architecture: Flexible module system for models, memory, MCP, and A2A
- Multiple AI Models: Support for OpenAI and Gemini with easy extensibility
- Thread Management: Built-in memory module for conversation history
- Intent System: Single/multi-intent triggering with intelligent response aggregation
- Workflow Management: Built-in workflow storage and execution with display query support
- Document System: First-class, mutable documents with slot-filling, faceted labels, and AI-generated advice
- Dual Build System: Supports both ESM and CJS formats for maximum compatibility
- Structured Logging: Winston-based logging system with service-specific loggers
- TypeScript First: Built with strict TypeScript configuration
Installation
npm
npm install @ainetwork/adkyarn
yarn add @ainetwork/adkRequirements
- Node.js >= 20
- TypeScript >= 5.8
Getting Start
To see how to use this package in your project, check out our comprehensive examples:
Architecture
Core Components
- AINAgent (
src/index.ts): Main Express.js server class that orchestrates all modules - DI Container (
src/container/): Dependency injection container for services and controllers - ModelModule (
src/modules/models/): Manages AI model integrations with streaming support - MCPModule (
src/modules/mcp/): Handles Model Context Protocol connections - A2AModule (
src/modules/a2a/): Manages agent-to-agent communication - MemoryModule (
src/modules/memory/): Provides threads, intents, and conversation history
Runtime Scope
AIN-ADK currently assumes a single agent runtime per Node.js process. Create one AINAgent instance per process; running multiple AINAgent instances concurrently in the same process is not currently supported.
Module System
The library uses a flexible module architecture:
interface AINAgentModules {
authModule: AuthModule; // Required - authentication handling
modelModule: ModelModule; // Required - AI model integrations
memoryModule: MemoryModule; // Required - thread/intent/workflow storage
a2aModule?: A2AModule; // Optional - agent-to-agent communication
mcpModule?: MCPModule; // Optional - MCP server connections
}Each module can be independently configured and passed to the agent constructor.
The MemoryModule exposes an optional IDocumentMemory (getDocumentMemory()). When the underlying memory implementation provides it, document storage and the /api/document endpoints are enabled; older implementations that omit it remain fully backward compatible.
Intent System
The library supports flexible intent triggering modes:
- Multi-Intent Mode (Default): Decomposes complex queries into multiple subqueries and maps each to an intent
- Single-Intent Mode: Identifies a single intent without query decomposition (set
DISABLE_MULTI_INTENTS=true) - Intelligent Aggregation: LLM-based aggregation determines if multiple intent responses need unification
- Streaming Support: Real-time response streaming with
thinking_processevents for progress visibility
Workflow System
Built-in workflow management capabilities:
- Workflow Storage: Save, retrieve, list, and delete workflows via MemoryModule
- Display Query Support: Separate display query for workflow execution visualization
- Structured Execution: Define workflows with tasks and response blocks
- RESTful API: Complete workflow management through
/api/workflow-templateand/api/user-workflowendpoints
Document System
Documents are first-class, mutable entities that hold the canonical result of a workflow or query as markdown. They are referenced from threads (via a document message part) rather than embedded, so manual edits are always reflected wherever the document is rendered. The system is enabled whenever the memory implementation provides an IDocumentMemory (getDocumentMemory()); it is optional and fully backward compatible.
- Document Storage: CRUD via
IDocumentMemory—getDocument,createDocument,updateDocument,deleteDocument,listDocuments(userId?, filter?). Documents are versioned (versionincrements on every update) and trackeditedManually. - Slots: A document body may contain
{{slot:slotId}}tokens backed byDocumentSlotentries. Each slot has a lifecycle status (empty→running→resolved/failed) and an optionalbindingto a workflow (withexecutionVariables) or a query. Slots are filled on demand and the resolvedDocumentFragment(markdown + structured render blocks) is substituted at render time. - Rendering:
renderDocument(document)(src/utils/document-render.ts) produces final markdown by substituting each slot token with its resolved fragment, falling back to a status placeholder for unresolved slots. Tokens with no matching slot are left untouched. - Faceted Labels:
labels(e.g.{ category: "logbook", workplaceId: "123", month: "2026-06" }) provide schema-free grouping. The nesting/hierarchy order is chosen at query or render time, so any number of grouping levels is supported without schema changes. Listing supports subset-match filtering bylabels, plusworkflowId/threadId/source. - Workflow Promotion: When document memory is available, a user-workflow execution promotes its result into a first-class document and references it from the thread (instead of embedding the markdown inline).
- Rich Messages: Thread message content supports
type: "rich"withMessagePart[]mixingTextPartandDocumentPart(adocumentIdreference resolved client-side), alongside the legacytextform.
AI Document Advice
The library can generate a short, operational AI advice from a document's rendered content:
- Streaming generation:
DocumentAdviceService.generateAdviceStreamruns a single-turn streaming completion over the rendered document and emitstext_chunkevents over SSE. - Caching: On completion the advice is cached on
document.advice({ content, generatedAt }). The cache write persists only the advice metadata and does not bump the document version, avoiding lost updates against concurrent edits. Nothing is persisted on error or empty output. - Prompt resolution: A per-call
advicePrompt(request body) takes precedence, then the agent-memory hookgetDocumentAdvicePrompt(), then a built-in Korean default prompt.
Dependency Injection
The library uses a DI Container pattern for managing services and controllers:
src/
├── config/ # Global configuration
│ ├── agent.ts # Agent instance access
│ ├── modules.ts # Module registry (ModelModule, MemoryModule, etc.)
│ ├── options.ts # Options registry (onIntentFallback, etc.)
│ └── manifest.ts # Agent manifest
├── container/ # DI Container
│ ├── index.ts # Main container with convenience methods
│ ├── services.ts # Service factory (QueryService, ThreadService, etc.)
│ └── controllers.ts # Controller factory (QueryController, etc.)Benefits:
- Centralized dependency management
- Singleton instances for memory efficiency
- Easy testing with mock injection
- Clean separation between configuration and runtime objects
Protocol Support
MCP (Model Context Protocol)
- Connects to external MCP servers via stdio
- Automatic tool discovery and execution
- Supports multiple concurrent MCP servers
- Protocol-specific tool wrapping as
IMCPTool - Per-connector
requestTimeoutMsoverride (inMCPConfig) for long-running tools; overrides the SDK's default 60s per-request timeout and usesresetTimeoutOnProgressso tools that stream progress notifications stay alive past the base timeout
A2A (Agent-to-Agent)
- RESTful API for inter-agent communication
- Streaming response support via SSE
- Agent discovery via well-known endpoints (
.well-known/agent-card.json) - Task delegation with thread context passing
- Protocol version 0.3.0 support
Key Features
- Unified Tool Interface: Protocol-agnostic
ConnectorToolandIAgentConnectorinterfaces - Streaming Support: Dual implementation for streaming and non-streaming queries
- Intent System: Single/multi-intent triggering with intelligent response aggregation
- Workflow Management: Built-in workflow storage and execution with display query support
- Document System: Mutable documents with on-demand slot-filling, faceted labels, and cached AI advice
- Service Layer: Clean separation with controllers and services
- Type Safety: Comprehensive TypeScript types with strict mode
- Error Handling: Global error middleware with structured logging
- Authentication: Required auth middleware via
AuthModuleinterface - Graceful Shutdown: Proper cleanup of modules and connections
Development
Scripts
# Build commands
yarn build # Build both ESM and CJS distributions
# Development
yarn dev # Run TypeScript directly with tsx
# Code quality
yarn biome # Check code with Biome
yarn biome:write # Check and auto-fix with Biome
# Testing
yarn test # Run Jest tests
# Clean
yarn clean # Remove build artifactsLogging System
The library uses Winston for structured logging with service-specific loggers:
import { getLogger } from '@ainetwork/adk/utils/logger';
// Get service-specific loggers
const agentLogger = getLogger('agent');
const mcpLogger = getLogger('mcp');
const a2aLogger = getLogger('a2a');
const modelLogger = getLogger('model');
// Usage examples
agentLogger.info('AINAgent started');
mcpLogger.debug('Connected to MCP server');
a2aLogger.warn('A2A connection timeout');
modelLogger.error('Model API error');Available Loggers
agent: Main agent operations (AINAgent)intent: Non-streaming query processing and intent analysis (Intent)intentStream: Streaming query processing (IntentStream)mcp: MCP server connections and tool execution (MCPModule)a2a: Agent-to-agent communication (A2AModule)model: AI model interactions (Model)server: A2A server operations (A2AServer)
Log Levels
error: Error conditionswarn: Warning conditionsinfo: Informational messages (default)debug: Debug-level messages
API Endpoints
Standard Endpoints
GET /- Welcome message and health checkPOST /query- Process queries (non-streaming)- Request:
{ message: string, threadId?: string, type?: string, workflowId?: string, title?: string, displayMessage?: string } - Response:
{ content: string, threadId: string }
- Request:
POST /query/stream- Process queries with streaming (SSE)- Request:
{ message: string, threadId?: string, type?: string, workflowId?: string, title?: string, displayMessage?: string } - Response: Server-Sent Events stream with event types:
text_chunk: Incremental text responsetask_output: Workflow task output chunktask_result: Workflow task completion statusthread_id: Thread metadatadocument_id: Document/slot reference ({ documentId, slotId }) for slot-fill streamsthinking_process: Thinking/reasoning stepscollection_name: Collection metadata emitted by integrationserror: Error message
- Request:
Agent Management
GET /api/threads- List user threads (userId from auth)GET /api/threads/:id- Get thread detailsPOST /api/threads/pin/:id- Update thread pin statePOST /api/threads/delete/:id- Delete threadGET /api/model- Get model listGET /api/agent/a2a- Get A2A connectorsGET /api/intent- List all intentsPOST /api/intent/save- Save intentPOST /api/intent/delete/:id- Delete intentGET /api/workflow-template- List all workflow templatesGET /api/workflow-template/:id- Get workflow template detailsPOST /api/workflow-template- Create workflow templatePOST /api/workflow-template/update/:id- Update workflow templatePOST /api/workflow-template/delete/:id- Delete workflow templateGET /api/user-workflow- List user workflowsGET /api/user-workflow/:id- Get user workflow detailsPOST /api/user-workflow- Create user workflowPOST /api/user-workflow/:id/execute- Execute user workflow (non-streaming)POST /api/user-workflow/:id/execute/stream- Execute user workflow with streaming (SSE)POST /api/user-workflow/update/:id- Update user workflowPOST /api/user-workflow/delete/:id- Delete user workflow
Document Endpoints (when the memory module provides IDocumentMemory)
GET /api/document- List documents (filterable byworkflowId,threadId,source, and subset-matchlabels[...])GET /api/document/:id- Get document detailsPOST /api/document- Create a document (source: MANUAL)POST /api/document/:id/slots/:slotId/fill- Fill a slot via its bound workflow/query (non-streaming)POST /api/document/:id/slots/:slotId/fill/stream- Fill a slot with streaming (SSE)- Body:
{ workflowId?: string, executionVariables?: Record<string, string> }
- Body:
POST /api/document/:id/advice/stream- Generate AI advice with streaming (SSE)- Body:
{ advicePrompt?: string }(optional per-call prompt override)
- Body:
POST /api/document/update/:id- Update document (title/content/slots/labels; markseditedManually)POST /api/document/delete/:id- Delete document
A2A Server Endpoints (when manifest.url is configured)
GET /.well-known/agent.json- Agent discovery endpoint (A2A ~v0.2.0)GET /.well-known/agent-card.json- Agent discovery endpoint (A2A v0.3.0~)- Returns
AgentCardwith capabilities and supported modes
- Returns
POST /a2a- A2A communication endpoint- Uses the
@a2a-js/sdkJSON-RPC transport - Supports JSON-RPC responses and SDK-managed SSE streaming responses
- A2A
contextIdis treated as the AIN-ADK thread ID
- Uses the
Build System
The project supports dual build output:
- ESM (
dist/esm/): ES Module format with{"type": "module"} - CJS (
dist/cjs/): CommonJS format with{"type": "commonjs"}
Error Handling
The library includes comprehensive error handling:
- Global error middleware for uncaught errors
- Custom
AinHttpErrorclass for HTTP-specific errors - Service-specific error logging with structured context
- Graceful handling of:
- MCP server connection failures
- A2A agent communication errors
- Model API failures (rate limits, timeouts)
- Tool execution errors
- Invalid requests
- Streaming errors with proper cleanup
All errors are logged with appropriate context for debugging.
Authentication
The library requires an authentication module:
import { AuthModule } from '@ainetwork/adk/modules';
import type { AuthResponse } from '@ainetwork/adk/types/auth';
class MyAuth extends AuthModule {
async authenticate(req: Request, res: Response): Promise<AuthResponse> {
// Implement your auth logic
return { isAuthenticated: true, userId: 'user-123' };
}
}
const agent = new AINAgent(manifest, {
authModule: new MyAuth(),
modelModule,
memoryModule,
});Contributing
- Follow the established code conventions (tabs, double quotes)
- Use TypeScript strict mode
- Add appropriate service-specific logging
- Run
yarn biome:writeandyarn testbefore submitting - Maintain the modular architecture
- Update JSDoc comments when changing function signatures
- Add streaming support when implementing new query handlers
License
MIT
