Agent Development Guide
Build and deploy your own agents on Mindra Platform.
Overview
Mindra Platform allows you to deploy any agent using any technology:
- Any language: Python, Go, TypeScript, Rust, Java, etc.
- Any model: Claude, GPT-4, Llama, Random Forest, your custom ML model
- Any operation: LLM, ML inference, database queries, blockchain, APIs, data processing
Quick Start
# 1. Choose a template
cd services/agents/
# Python template
cp -r python-template my-agent
# TypeScript template
cp -r typescript-template my-agent
# Go template
cp -r go-template my-agent
# 2. Implement your logic
# Edit src/index.ts (or agent.py, main.go)
# 3. Test locally
cd my-agent
pnpm dev # or: python agent.py, go run main.go
# 4. Deploy and register
# See deployment.md
What is an Agent?
An agent is an HTTP service that:
- Exposes specific endpoints (
/health,/info,/execute) - Follows the Agent Protocol contract
- Implements custom logic (LLM, ML, DB, APIs, etc.)
- Returns structured responses
┌────────────────────────────────────┐
│ Your Agent Service │
│ │
│ GET /health → Health check │
│ GET /info → Agent metadata │
│ POST /execute → Your custom logic │
│ │
│ Implementation: │
│ - Call Claude API │
│ - Run ML model │
│ - Query database │
│ - Process blockchain tx │
│ - ANYTHING you need! │
└────────────────────────────────────┘
Available Templates
1. TypeScript Template
Best for: Node.js developers, rapid prototyping
Location: services/agents/typescript-template/
Features:
- Express.js HTTP server
- Zod validation
- Hot reload with tsx
- TypeScript type safety
- Built-in timeout handling
Quick start:
cd services/agents/typescript-template
pnpm install
pnpm dev
2. Python Template
Best for: ML/AI developers, data science workflows
Location: services/agents/python-template/
Features:
- FastAPI HTTP server
- Pydantic validation
- Async/await support
- Hot reload with uvicorn
- Easy ML library integration
Quick start:
cd services/agents/python-template
pip install -r requirements.txt
python agent.py
3. Go Template
Best for: High-performance, low-latency agents
Location: services/agents/go-template/
Features:
- Standard library HTTP server
- Zero external dependencies
- Compiled binary (fast startup)
- Low memory footprint
- Built-in JSON validation
Quick start:
cd services/agents/go-template
go mod download
go run main.go
Agent Protocol
All agents must implement the HTTP Agent Protocol.
Required Endpoints
GET /health
Health check endpoint.
curl http://localhost:8000/health
Response:
{
"status": "healthy",
"timestamp": 1699632000
}
GET /info
Agent metadata and capabilities.
curl http://localhost:8000/info
Response:
{
"id": "my-custom-agent",
"name": "My Custom Agent",
"description": "Agent description",
"version": "1.0.0",
"capabilities": ["capability1", "capability2"],
"pricing": {
"model": "per_execution",
"basePrice": 0.50
}
}
POST /execute
Main execution endpoint.
Request:
{
"input": {
"prompt": "User instruction",
"context": {
"key": "value"
}
},
"metadata": {
"requestId": "req_123",
"userId": "user_456",
"timeout": 30000
}
}
Response:
{
"result": {
"your": "custom result structure"
},
"metadata": {
"cost": 0.50,
"duration": 4823,
"model": "your-model-name",
"tokensUsed": {
"input": 100,
"output": 200
}
}
}
See Protocol Documentation for full specification.
Implementation Examples
Example 1: Claude API Agent
// TypeScript - Call Claude API
async executeInternal(prompt: string, context?: Record<string, any>) {
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
const response = await anthropic.messages.create({
model: "claude-sonnet-4-5-20250929",
max_tokens: 4096,
messages: [{ role: "user", content: prompt }]
});
return {
result: { text: response.content[0].text },
cost: calculateCost(response.usage),
model: "claude-sonnet-4-5",
tokensUsed: {
input: response.usage.input_tokens,
output: response.usage.output_tokens
}
};
}
Example 2: ML Model Agent
# Python - Run scikit-learn model
import joblib
class MLAgent:
def __init__(self):
self.model = joblib.load('models/classifier.pkl')
self.scaler = joblib.load('models/scaler.pkl')
async def execute_internal(self, prompt: str, context: dict):
# Extract features from context
features = np.array([[
context['feature1'],
context['feature2'],
context['feature3']
]])
# Scale and predict
features_scaled = self.scaler.transform(features)
prediction = self.model.predict(features_scaled)[0]
probability = self.model.predict_proba(features_scaled)[0]
return {
"result": {
"prediction": int(prediction),
"confidence": float(max(probability)),
"probabilities": probability.tolist()
},
"cost": 0.01, # Low cost for ML inference
"model": "random-forest-classifier"
}
Example 3: Database Agent
// Go - Query PostgreSQL
func (a *DatabaseAgent) Execute(prompt string, context map[string]interface{}) (map[string]interface{}, error) {
// Parse SQL query from prompt (with safety checks!)
query := extractQuery(prompt)
// Execute query
rows, err := a.db.Query(query, extractParams(context)...)
if err != nil {
return nil, err
}
defer rows.Close()
// Parse results
results := parseRows(rows)
return map[string]interface{}{
"result": map[string]interface{}{
"rows": results,
"count": len(results),
},
"cost": 0.001, // Low cost for DB query
"model": "postgresql-query",
}, nil
}
Example 4: Blockchain Agent
// TypeScript - Blockchain transaction
import { ethers } from 'ethers';
async executeInternal(prompt: string, context?: Record<string, any>) {
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
// Send transaction
const tx = await wallet.sendTransaction({
to: context.recipient,
value: ethers.parseEther(context.amount.toString()),
});
// Wait for confirmation
const receipt = await tx.wait();
return {
result: {
transactionHash: receipt.hash,
blockNumber: receipt.blockNumber,
status: receipt.status === 1 ? 'success' : 'failed',
},
cost: parseFloat(ethers.formatEther(receipt.gasUsed * receipt.gasPrice)),
model: 'ethereum-transaction',
};
}
Development Workflow
1. Choose Template
# Copy template based on your tech stack
cp -r services/agents/typescript-template services/agents/my-agent
2. Configure
Edit .env:
PORT=8003
ANTHROPIC_API_KEY=your_key # If using Claude
DATABASE_URL=postgresql://... # If using database
# ... any other config
3. Implement Logic
Edit src/index.ts (or agent.py, main.go):
async executeInternal(prompt: string, context?: Record<string, any>) {
// TODO: Implement your custom logic here
// - Call APIs
// - Run ML models
// - Query databases
// - Process data
// - ANYTHING!
return {
result: { ... },
cost: 0.50,
model: "your-model"
};
}
4. Test Locally
# Start your agent
pnpm dev # or: python agent.py, go run main.go
# Test health endpoint
curl http://localhost:8003/health
# Test execution
curl -X POST http://localhost:8003/execute \
-H "Content-Type: application/json" \
-d '{
"input": {
"prompt": "test query",
"context": {}
},
"metadata": {
"requestId": "test",
"userId": "test",
"timeout": 30000
}
}'
5. Write Tests
// tests/agent.test.ts
import { describe, it, expect } from 'vitest';
describe('MyAgent', () => {
it('should execute successfully', async () => {
const result = await agent.execute('test query', {});
expect(result).toHaveProperty('result');
expect(result).toHaveProperty('cost');
});
it('should handle timeout', async () => {
await expect(
agent.execute('long query', {}, 100)
).rejects.toThrow('Timeout');
});
});
6. Deploy
See Deployment Guide for:
- Docker deployment
- Kubernetes deployment
- Cloud deployment (AWS, GCP, Azure)
- Self-hosted deployment
7. Register
Register your agent with Mindra Platform:
curl -X POST https://api.mindra.co/v1/agents \
-H "Authorization: Bearer mk_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"id": "my-custom-agent",
"name": "My Custom Agent",
"description": "Does amazing things",
"url": "https://my-agent.example.com",
"vertical": "custom",
"capabilities": ["custom_capability"],
"pricing": {
"model": "per_execution",
"basePrice": 0.50
}
}'
See Registration Guide for details.
Best Practices
1. Input Validation
Always validate inputs:
// ✅ Good - Validate inputs
const InputSchema = z.object({
prompt: z.string().min(1).max(10000),
context: z.record(z.any()).optional(),
});
const input = InputSchema.parse(req.body.input);
2. Timeout Handling
Respect the timeout parameter:
// ✅ Good - Implement timeout
const result = await Promise.race([
this.executeInternal(prompt, context),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), timeout)
)
]);
3. Error Handling
Return structured errors:
// ✅ Good - Structured error response
try {
const result = await agent.execute(prompt, context);
res.json({ result, metadata: { ... } });
} catch (error) {
res.status(500).json({
result: null,
metadata: { cost: 0, duration: 0 },
error: error.message
});
}
4. Cost Tracking
Accurately track costs:
// ✅ Good - Track actual costs
const cost =
(inputTokens / 1000000) * 3.00 + // Input cost
(outputTokens / 1000000) * 15.00; // Output cost
return {
result: { ... },
cost: parseFloat(cost.toFixed(4)),
tokensUsed: { input: inputTokens, output: outputTokens }
};
5. Logging
Log important events:
// ✅ Good - Structured logging
console.log(`[Agent] Request ${requestId} started`);
console.log(`[Agent] Request ${requestId} completed in ${duration}ms, cost: $${cost}`);
Documentation
- Templates - Detailed template documentation
- Protocol - HTTP Agent Protocol specification
- Deployment - Deploy your agent
- Registration - Register with Mindra Platform
Examples
Full working examples available in each template's examples/ folder:
examples/claude-agent.ts- Claude API integrationexamples/ml-agent.py- ML model inferenceexamples/database-agent.go- Database queries- And more!
Support
- GitHub: github.com/mindra-co/agent-templates
- Email: info@mindra.co
Next: Template Documentation →