The do Tool
Complete reference for the unified MCP.do interface
The do Tool
The do tool is MCP.do's unified interface for Business-as-Code. Instead of dozens of narrow-purpose tools, AI models write TypeScript code directly against the SDK, enabling unlimited composability and natural code patterns.
Why Code Mode? LLMs have seen millions of lines of TypeScript. They excel at writing code. The
dotool leverages this native capability instead of forcing models to learn synthetic tool schemas.
Overview
The do tool provides access to the complete .do platform through a single tool interface:
{
"name": "do",
"description": "Execute TypeScript against sdk.do modules. Semantic Business-as-Code primitives.",
"inputSchema": {
"type": "object",
"properties": {
"script": {
"type": "string",
"description": "TypeScript code to execute, or '{module}.md' for documentation"
},
"module": {
"type": "string",
"description": "MDXLD module definition with yaml frontmatter ($type, $id, $context), markdown content, and MDX/JSX components"
}
}
}
}Execution Model
The do tool uses capnweb RPC (Cap'n Proto over WebSockets) for promise chaining and automatic execution:
Promise Chaining via RPC
All SDK operations return promises that are automatically resolved by the RPC layer. The platform automatically awaits the last returned value, making async/await syntax completely optional.
// These are equivalent:
// Option 1: Using async/await (explicit)
const business = await db.Business.get('123')
const orders = await db.Order.list({ where: { businessId: business.id } })
return orders
// Option 2: Promise chaining (implicit, preferred)
db.Business.get('123')
.then(business => db.Order.list({ where: { businessId: business.id } }))
// Option 3: Direct return (simplest)
db.Business.get('123')
.then(business => db.Order.list({ where: { businessId: business.id } }))
// Last value is automatically awaited and returned
// Option 4: No await at all (works because of automatic awaiting)
const business = db.Business.get('123')
const orders = db.Order.list({ where: { businessId: business.id } })
orders // This is automatically awaited and returnedKey Points
async/awaitare optional - Use them for readability if you prefer, but they're not required- Last returned value is auto-awaited - The RPC system automatically awaits the final expression
- Promise chaining works natively -
.then()chains are fully supported - Sequential execution - Operations execute in order regardless of syntax
- Error handling - Use
.catch()ortry/catchas normal
Examples
// Simple query - no await needed
db.Business.list()
// Chained operations - no await needed
db.Business.get('123')
.then(business => db.Employee.list({ where: { businessId: business.id } }))
// Complex flow - mix and match styles
const customer = db.Customer.create({
name: 'Alice',
email: '[email protected]'
})
const order = customer.then(c =>
db.Order.create({
customerId: c.id,
total: 99.99
})
)
// Last value is automatically returned
order.then(o => send($.Order.created, { orderId: o.id }))
// Or use await if you prefer the syntax
const customer = await db.Customer.create({
name: 'Alice',
email: '[email protected]'
})
const order = await db.Order.create({
customerId: customer.id,
total: 99.99
})
await send($.Order.created, { orderId: order.id })Why This Matters
capnweb RPC enables:
- Reduced latency - Operations can pipeline without waiting for each round-trip
- Natural code - Write code the way you think, without ceremony
- Flexible syntax - Use async/await when it improves readability, skip it when it doesn't
- Automatic optimization - The RPC layer handles batching and parallelization
Best Practice: Use the syntax that makes your code most readable. The platform handles the execution details.
SDK Components
All SDK primitives are available within the do tool execution context:
Core Primitives
$ - Semantic Paths
The semantic proxy $ is the foundation of Business-as-Code. It builds semantic triple patterns following $.Subject.predicate.Object:
// Basic entity construction
const person = $.Person({
name: 'Alice Johnson',
email: '[email protected]',
role: 'CEO',
})
const business = $.Business({
name: 'Acme Corp',
industry: 'Technology',
founded: '2020-01-01',
})
// Nested entity construction
const order = $.Order({
customer: $.Person({ name: 'Bob Smith' }),
items: [
$.LineItem({ product: $.Product({ sku: 'WIDGET-001' }), quantity: 2 }),
$.LineItem({ product: $.Product({ sku: 'GADGET-042' }), quantity: 1 }),
],
total: 299.97,
status: 'pending',
})
// Semantic query patterns - temporal predicates
$.Order.after('2024-01-01')
$.Order.before('2024-12-31')
$.Order.during('2024-Q1')
$.Order.since('7 days ago')
$.Order.until('next month')
// Semantic query patterns - relational predicates
$.Order.of(person) // Orders belonging to person
$.Business.for('industry:technology') // Businesses in tech
$.Article.about('AI') // Articles about AI
$.Employee.at(business) // Employees at business
$.Product.by(business) // Products by business
// Semantic query patterns - spatial predicates
$.Business.near({ lat: 37.7749, lng: -122.4194, radius: '10mi' })
$.Business.within({ bounds: [sw, ne] })
$.Store.around({ address: '123 Main St', distance: '5km' })
// Complex semantic compositions
$.Order.of(person).after('2024-01-01').with('status:completed')
$.Business.for('industry:technology').near({ city: 'San Francisco' })
$.Article.about('AI').by(author).during('2024')
// Type schemas with validation
const CustomerSchema = $.Schema({
name: { type: 'string', required: true },
email: { type: 'string', format: 'email', required: true },
age: { type: 'number', minimum: 18 },
subscribed: { type: 'boolean', default: false },
})
// Use schema for validation
const customer = $.Customer(CustomerSchema, {
name: 'Alice',
email: '[email protected]',
age: 30,
})Real-World Examples:
// E-commerce: Build order with customer and products
const order = await db.Order.create(
$.Order({
customer: $.Person({
name: 'Sarah Chen',
email: '[email protected]',
address: $.Address({
street: '123 Market St',
city: 'San Francisco',
state: 'CA',
zip: '94103',
}),
}),
items: [
$.LineItem({
product: $.Product({ sku: 'LAPTOP-001', name: 'Pro Laptop' }),
quantity: 1,
price: 1299.99,
}),
$.LineItem({
product: $.Product({ sku: 'MOUSE-042', name: 'Wireless Mouse' }),
quantity: 2,
price: 29.99,
}),
],
subtotal: 1359.97,
tax: 108.80,
total: 1468.77,
status: 'pending_payment',
}),
)
// SaaS: Create subscription with plan and billing
const subscription = $.Subscription({
customer: $.Person({ id: 'cus_123', email: '[email protected]' }),
plan: $.Plan({
id: 'plan_pro',
name: 'Professional',
price: 99,
interval: 'month',
features: ['unlimited_users', 'priority_support', 'custom_branding'],
}),
billing: $.BillingInfo({
method: 'card',
last4: '4242',
expiry: '12/2025',
}),
startDate: '2024-01-01',
trialEnds: '2024-01-14',
})
// CRM: Build contact with company and interactions
const contact = $.Contact({
person: $.Person({
name: 'Michael Torres',
email: '[email protected]',
phone: '+1-415-555-0123',
title: 'VP of Engineering',
}),
company: $.Company({
name: 'Big Client Inc',
industry: 'Enterprise Software',
size: '500-1000',
website: 'https://bigclient.com',
}),
interactions: [
$.Interaction({
type: 'call',
date: '2024-01-15',
notes: 'Discussed integration requirements',
outcome: 'positive',
}),
$.Interaction({
type: 'email',
date: '2024-01-18',
notes: 'Sent proposal and pricing',
outcome: 'awaiting_response',
}),
],
status: 'qualified',
value: 50000,
})Documentation: $.md
db - Database Operations
Complete CRUD operations, advanced queries, relationships, and transactions:
// === BASIC CRUD ===
// List all entities of type
const businesses = await db.Business.list()
// List with filtering
const activeBusinesses = await db.Business.list({
where: { status: 'active' },
})
// List with pagination
const page1 = await db.Business.list({
limit: 50,
offset: 0,
orderBy: 'createdAt',
direction: 'desc',
})
// Get single entity by ID
const business = await db.Business.get('123')
// Get with related entities
const businessWithEmployees = await db.Business.get('123', {
include: ['employees', 'products', 'orders'],
})
// Create entity
const newBusiness = await db.Business.create({
name: 'Acme Corp',
industry: 'Technology',
founded: '2020-01-01',
website: 'https://acme.com',
})
// Create with semantic constructor
const newOrder = await db.Order.create(
$.Order({
customer: $.Person({ email: '[email protected]' }),
items: [$.LineItem({ sku: 'WIDGET-001', quantity: 2 })],
total: 199.98,
}),
)
// Update entity
await db.Business.update('123', {
status: 'active',
employees: 150,
lastUpdated: new Date().toISOString(),
})
// Partial update (patch)
await db.Business.update('123', {
revenue: 5000000, // Only update revenue field
})
// Delete entity
await db.Business.delete('123')
// Soft delete (if supported)
await db.Business.update('123', {
deleted: true,
deletedAt: new Date().toISOString(),
})
// === RELATIONSHIPS ===
// Create relationship between entities
await db.relate(business, 'employs', person)
await db.relate(order, 'belongsTo', customer)
await db.relate(product, 'manufacturedBy', company)
// Get relationships
const employees = await db.related(business, 'employs')
const orders = await db.related(customer, 'placed')
const products = await db.related(company, 'manufactures')
// Remove relationship
await db.unrelate(business, 'employs', person)
// === ADVANCED QUERIES ===
// Complex filtering
const results = await db.Order.list({
where: {
status: { in: ['pending', 'processing'] },
total: { gte: 100, lte: 1000 },
createdAt: { after: '2024-01-01' },
'customer.email': { contains: '@example.com' },
},
orderBy: 'createdAt',
direction: 'desc',
limit: 100,
})
// Full-text search
const searchResults = await db.Business.search({
query: 'AI startups San Francisco',
fields: ['name', 'description', 'tags'],
limit: 20,
})
// Aggregation queries
const stats = await db.Order.aggregate({
groupBy: 'status',
sum: 'total',
count: '*',
avg: 'total',
where: {
createdAt: { after: '2024-01-01' },
},
})
// Count entities
const totalBusinesses = await db.Business.count()
const activeBusinesses = await db.Business.count({
where: { status: 'active' },
})
// === TRANSACTIONS ===
// Execute multiple operations atomically
await db.transaction(async (tx) => {
// Create customer
const customer = await tx.Customer.create({
name: 'Alice Johnson',
email: '[email protected]',
})
// Create order for customer
const order = await tx.Order.create({
customerId: customer.id,
total: 99.99,
status: 'pending',
})
// Update inventory
await tx.Product.update('prod_123', {
stock: { decrement: 1 },
})
// All succeed or all fail together
return { customer, order }
})
// === BATCH OPERATIONS ===
// Create multiple entities
const customers = await db.Customer.createMany([
{ name: 'Alice', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' },
{ name: 'Charlie', email: '[email protected]' },
])
// Update multiple entities
await db.Order.updateMany(
{
where: { status: 'pending', createdAt: { before: '24 hours ago' } },
},
{
status: 'expired',
},
)
// Delete multiple entities
await db.TempFile.deleteMany({
where: { createdAt: { before: '30 days ago' } },
})Real-World Examples:
// E-commerce: Complete order flow with inventory management
async function processOrder(orderData) {
return await db.transaction(async (tx) => {
// Create customer if doesn't exist
let customer = await tx.Customer.findFirst({
where: { email: orderData.email },
})
if (!customer) {
customer = await tx.Customer.create({
name: orderData.name,
email: orderData.email,
address: orderData.address,
})
}
// Validate inventory for all items
for (const item of orderData.items) {
const product = await tx.Product.get(item.productId)
if (product.stock < item.quantity) {
throw new Error(`Insufficient stock for ${product.name}`)
}
}
// Create order
const order = await tx.Order.create({
customerId: customer.id,
items: orderData.items,
subtotal: orderData.subtotal,
tax: orderData.tax,
shipping: orderData.shipping,
total: orderData.total,
status: 'pending_payment',
})
// Decrement inventory
for (const item of orderData.items) {
await tx.Product.update(item.productId, {
stock: { decrement: item.quantity },
reserved: { increment: item.quantity },
})
}
// Create audit log
await tx.AuditLog.create({
type: 'order_created',
entityType: 'Order',
entityId: order.id,
userId: customer.id,
timestamp: new Date().toISOString(),
})
return order
})
}
// SaaS: User signup with trial and onboarding
async function signupUser(userData) {
const user = await db.User.create({
email: userData.email,
name: userData.name,
passwordHash: await hash(userData.password),
emailVerified: false,
createdAt: new Date().toISOString(),
})
// Create trial subscription
const subscription = await db.Subscription.create({
userId: user.id,
plan: 'trial',
status: 'active',
trialEnds: addDays(new Date(), 14).toISOString(),
startedAt: new Date().toISOString(),
})
// Create onboarding checklist
await db.OnboardingProgress.create({
userId: user.id,
steps: {
email_verified: false,
profile_completed: false,
first_project_created: false,
invited_team_member: false,
},
completedSteps: 0,
totalSteps: 4,
})
// Create welcome notification
await db.Notification.create({
userId: user.id,
type: 'welcome',
title: 'Welcome to Platform.do!',
message: 'Complete your onboarding to get started',
read: false,
createdAt: new Date().toISOString(),
})
return { user, subscription }
}
// CRM: Lead scoring and qualification
async function scoreAndQualifyLead(leadId) {
const lead = await db.Lead.get(leadId, {
include: ['company', 'interactions', 'activities'],
})
// Calculate lead score based on multiple factors
let score = 0
// Company size scoring
if (lead.company.size === '1000+') score += 50
else if (lead.company.size === '500-1000') score += 30
else if (lead.company.size === '100-500') score += 20
// Industry scoring
if (['Technology', 'Finance', 'Healthcare'].includes(lead.company.industry)) {
score += 20
}
// Engagement scoring
const recentInteractions = lead.interactions.filter((i) =>
isAfter(new Date(i.date), subDays(new Date(), 30)),
)
score += recentInteractions.length * 5
// Website visits
const websiteVisits = lead.activities.filter((a) => a.type === 'website_visit')
score += websiteVisits.length * 2
// Email opens
const emailOpens = lead.activities.filter((a) => a.type === 'email_open')
score += emailOpens.length * 3
// Demo requests
const demoRequests = lead.activities.filter((a) => a.type === 'demo_request')
score += demoRequests.length * 20
// Update lead with score and qualification
const qualification =
score >= 80 ? 'hot' : score >= 50 ? 'warm' : score >= 25 ? 'nurture' : 'cold'
await db.Lead.update(leadId, {
score,
qualification,
lastScored: new Date().toISOString(),
})
// If hot lead, notify sales team
if (qualification === 'hot') {
const salesRep = await assignSalesRep(lead)
await db.Task.create({
userId: salesRep.id,
type: 'follow_up',
priority: 'high',
title: `Follow up with hot lead: ${lead.company.name}`,
leadId: lead.id,
dueDate: addDays(new Date(), 1).toISOString(),
})
}
return { score, qualification }
}
// Analytics: Generate dashboard metrics
async function getDashboardMetrics(userId, dateRange) {
const { startDate, endDate } = dateRange
// Run multiple aggregation queries in parallel
const [revenue, orders, customers, products] = await Promise.all([
// Total revenue
db.Order.aggregate({
where: {
userId,
status: 'completed',
createdAt: { between: [startDate, endDate] },
},
sum: 'total',
count: '*',
avg: 'total',
}),
// Order breakdown by status
db.Order.aggregate({
where: {
userId,
createdAt: { between: [startDate, endDate] },
},
groupBy: 'status',
count: '*',
}),
// New customers
db.Customer.count({
where: {
userId,
createdAt: { between: [startDate, endDate] },
},
}),
// Top selling products
db.query(`
SELECT p.id, p.name, SUM(oi.quantity) as totalSold
FROM products p
JOIN order_items oi ON p.id = oi.productId
JOIN orders o ON oi.orderId = o.id
WHERE o.userId = ? AND o.createdAt BETWEEN ? AND ?
GROUP BY p.id
ORDER BY totalSold DESC
LIMIT 10
`, [userId, startDate, endDate]),
])
return {
revenue: {
total: revenue.sum,
average: revenue.avg,
orderCount: revenue.count,
},
orders: orders.reduce((acc, o) => ({ ...acc, [o.status]: o.count }), {}),
newCustomers: customers,
topProducts: products,
}
}Documentation: db.md, db.list.md, db.create.md, db.update.md, db.delete.md, db.transaction.md
ai - AI Operations
Text generation, chat, embeddings, and batch processing:
// Generate text
await ai.generate({ prompt: 'Write a haiku about code' })
// Generate StoryBrand narrative
await ai.generateStoryBrand({ business: 'SaaS startup' })
// Chat completion
await ai.chat({
messages: [{ role: 'user', content: 'Hello' }],
})
// Generate structured output
await ai.generate({
prompt: 'Create a product description',
schema: $.ProductDescription,
})
// Embeddings
await ai.embed({ text: 'Sample text' })
// Batch processing
await ai.batch([
{ prompt: 'First task' },
{ prompt: 'Second task' },
])Documentation: ai.md
api - HTTP Operations
Generic HTTP client for external APIs:
// Simple fetch
await api.fetch('https://api.example.com/data')
// With options
await api.fetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' }),
})
// Proxy to service
await api.proxy('stripe', '/customers', {
method: 'POST',
body: { email: '[email protected]' },
})Documentation: api.md
user - Authentication & Permissions
User operations, sessions, and human-in-the-loop:
// Get current user
const currentUser = await user.current()
// Check permissions
const canDeploy = await user.can('deploy', 'production')
// Request approval (human-in-the-loop)
const approval = await user.approve({
message: 'Approve this deployment to production?',
action: 'deploy',
target: 'production',
})
if (approval.approved) {
await send($.Deployment.start, { environment: 'production' })
}Documentation: user.md
on - Event Listeners
Subscribe to events with pattern matching:
// Listen for specific event
on($.Order.created, async (order) => {
await send($.Email.send, {
to: order.customer.email,
subject: 'Order Confirmation',
})
})
// Pattern matching
on($.Order['*'], async (order) => {
console.log('Order event:', order)
})
// Multiple handlers
on($.Payment.completed, handler1)
on($.Payment.failed, handler2)Documentation: on.md or events.md
send - Event Publishing
Publish events to the event system:
// Send event
await send($.Order.created, {
orderId: '123',
customerId: 'alice',
total: 99.99,
})
// Send with metadata
await send($.Notification.dispatch, {
userId: 'alice',
message: 'Your order has shipped',
channel: 'email',
})Documentation: send.md or events.md
every - Scheduled Tasks
Schedule recurring tasks with cron syntax:
// Run every hour
every('0 * * * *', async () => {
const pending = await db.list('Order', {
where: { status: 'pending' },
})
// Process pending orders
})
// Daily at 9 AM
every('0 9 * * *', async () => {
await send($.Report.generate, { type: 'daily' })
})
// Every 6 hours
every('0 */6 * * *', async () => {
// Cleanup task
})Documentation: every.md or events.md
decide - AI Decision Making
AI-powered decision making with confidence scoring:
// Make a decision
const decision = await decide({
question: 'Should we approve this loan application?',
context: {
creditScore: 750,
income: 80000,
debtRatio: 0.3,
},
})
console.log(decision.choice) // 'approve' or 'reject'
console.log(decision.confidence) // 0.0 to 1.0
console.log(decision.reasoning) // ExplanationDocumentation: decide.md
Integration APIs
Access to 40+ service integrations:
Stripe
// Access via api.stripe namespace
await api.stripe.customers.create({
email: '[email protected]',
})
await api.stripe.subscriptions.create({
customer: 'cus_123',
items: [{ price: 'price_123' }],
})Documentation: api.stripe.md
GitHub
// Repository operations
await api.github.repos.create({
name: 'new-repo',
private: true,
})
// Issues
await api.github.issues.create({
repo: 'owner/repo',
title: 'Bug report',
body: 'Description',
})Documentation: api.github.md
// Send transactional email
await api.email.send({
to: '[email protected]',
subject: 'Welcome',
body: 'Welcome to our platform!',
})Documentation: api.email.md
Predicates
Semantic predicates for temporal, spatial, and relational queries:
// Temporal
$.Order.after('2024-01-01')
$.Order.before('2024-12-31')
$.Order.during('2024-01-01', '2024-12-31')
$.Order.since('7 days ago')
// Spatial
$.Business.near({ lat: 37.7749, lng: -122.4194 })
$.Business.within({ bounds: [sw, ne] })
// Relational
$.Order.of(customer)
$.Business.for('industry:technology')
$.Article.about('AI')Documentation: predicates.md
Documentation System
The do tool includes a comprehensive inline documentation system where you can append .md to any SDK path to retrieve its documentation. This pattern is hierarchical and recursive, working at every level from top-level modules down to individual function parameters.
The Pattern
Key Concept: Nearly every object, module, function, method, and property in the SDK supports
.mddocumentation. There are thousands of documentable paths.
// PATTERN: {module}.md
// PATTERN: {module}.{function}.md
// PATTERN: {module}.{namespace}.{function}.md
// PATTERN: {module}.{namespace}.{subnamespace}.{function}.md
// ... and so on, as deep as the API goesThe .md suffix works everywhere in the SDK hierarchy. When you're unsure about how to use something, just append .md to get complete documentation with examples.
How It Works
When you request documentation with .md, the MCP server:
- Parses the path - Splits on dots (e.g.,
api.stripe.customers.create.md) - Resolves the target - Finds the corresponding module/function/method
- Returns documentation including:
- Description and purpose
- Type signatures and interfaces
- Parameters (required and optional)
- Return values and types
- Usage examples (simple and advanced)
- Best practices and gotchas
- Related functions
- Error handling
Examples (Non-Exhaustive)
These are examples to demonstrate the pattern. The actual SDK has thousands more documentable paths:
Top-Level Modules
'$.md' // Semantic proxy documentation
'db.md' // Database operations documentation
'ai.md' // AI operations documentation
'api.md' // API/HTTP client documentation
'user.md' // User and auth documentation
'on.md' // Event listener documentation
'send.md' // Event publisher documentation
'every.md' // Scheduler documentation
'decide.md' // AI decision-making documentationDatabase Operations (db.*)
// Top-level functions
'db.list.md' // List entities with filtering
'db.get.md' // Get entity by ID
'db.create.md' // Create new entity
'db.update.md' // Update existing entity
'db.delete.md' // Delete entity
'db.relate.md' // Create relationships
'db.unrelate.md' // Remove relationships
'db.related.md' // Query relationships
'db.search.md' // Full-text search
'db.aggregate.md' // Aggregation queries
'db.count.md' // Count entities
'db.transaction.md' // Atomic transactions
'db.createMany.md' // Batch create
'db.updateMany.md' // Batch update
'db.deleteMany.md' // Batch delete
// And many more...AI Operations (ai.*)
// Text generation
'ai.generate.md' // General text generation
'ai.generateText.md' // Plain text generation
'ai.generateJSON.md' // Structured JSON generation
'ai.generateStoryBrand.md' // StoryBrand narrative generation
'ai.generateMarketing.md' // Marketing copy generation
'ai.generateCode.md' // Code generation
'ai.generateEmail.md' // Email content generation
// Chat
'ai.chat.md' // Chat completions
'ai.chatStream.md' // Streaming chat
// Embeddings
'ai.embed.md' // Generate embeddings
'ai.embedBatch.md' // Batch embeddings
// Batch operations
'ai.batch.md' // Batch AI operations
// And hundreds more AI functions...API/Integration Operations (api.*)
// HTTP client
'api.fetch.md' // Generic HTTP fetch
'api.get.md' // GET request
'api.post.md' // POST request
'api.put.md' // PUT request
'api.delete.md' // DELETE request
'api.proxy.md' // Proxy to service
// Stripe integration (examples - dozens more exist)
'api.stripe.md' // Stripe overview
'api.stripe.customers.md' // Customer operations
'api.stripe.customers.create.md' // Create customer
'api.stripe.customers.update.md' // Update customer
'api.stripe.customers.delete.md' // Delete customer
'api.stripe.customers.list.md' // List customers
'api.stripe.subscriptions.md' // Subscription operations
'api.stripe.subscriptions.create.md' // Create subscription
'api.stripe.subscriptions.update.md' // Update subscription
'api.stripe.subscriptions.cancel.md' // Cancel subscription
'api.stripe.payments.md' // Payment operations
'api.stripe.payments.create.md' // Create payment
'api.stripe.paymentIntents.md' // Payment intents
'api.stripe.paymentIntents.create.md' // Create payment intent
'api.stripe.paymentIntents.confirm.md' // Confirm payment intent
'api.stripe.invoices.md' // Invoice operations
'api.stripe.invoices.create.md' // Create invoice
'api.stripe.products.md' // Product operations
'api.stripe.prices.md' // Price operations
// GitHub integration (examples - dozens more exist)
'api.github.md' // GitHub overview
'api.github.repos.md' // Repository operations
'api.github.repos.create.md' // Create repository
'api.github.repos.get.md' // Get repository
'api.github.repos.update.md' // Update repository
'api.github.repos.delete.md' // Delete repository
'api.github.repos.list.md' // List repositories
'api.github.issues.md' // Issue operations
'api.github.issues.create.md' // Create issue
'api.github.issues.update.md' // Update issue
'api.github.issues.close.md' // Close issue
'api.github.issues.list.md' // List issues
'api.github.pullRequests.md' // PR operations
'api.github.pullRequests.create.md' // Create PR
'api.github.pullRequests.merge.md' // Merge PR
'api.github.commits.md' // Commit operations
'api.github.branches.md' // Branch operations
// Email integration
'api.email.md' // Email overview
'api.email.send.md' // Send email
'api.email.sendTransactional.md' // Send transactional email
'api.email.sendBatch.md' // Send batch emails
'api.email.templates.md' // Email template operations
// And 40+ more service integrations, each with dozens of methods...User Operations (user.*)
'user.current.md' // Get current user
'user.session.md' // Get session info
'user.can.md' // Check permissions
'user.approve.md' // Request human approval
'user.authenticate.md' // Authenticate user
'user.logout.md' // Logout user
// And more...Event Operations (on., send., every.*)
// Event listeners
'on.md' // Event listener documentation
// Event publishers
'send.md' // Event publishing documentation
// Schedulers
'every.md' // Cron scheduler documentationSemantic Proxy ($.*)
'$.md' // Semantic proxy overview
'$.Person.md' // Person entity documentation
'$.Business.md' // Business entity documentation
'$.Order.md' // Order entity documentation
'$.Product.md' // Product entity documentation
// Predicates
'$.after.md' // Temporal: after predicate
'$.before.md' // Temporal: before predicate
'$.during.md' // Temporal: during predicate
'$.since.md' // Temporal: since predicate
'$.of.md' // Relational: of predicate
'$.for.md' // Relational: for predicate
'$.about.md' // Relational: about predicate
'$.near.md' // Spatial: near predicate
'$.within.md' // Spatial: within predicate
// And hundreds more entity types and predicates...Discovery Pattern
When you're exploring the SDK:
- Start broad - Request top-level docs:
'ai.md','api.md','db.md' - Navigate down - Docs include available sub-modules and functions
- Go deeper - Request specific function docs:
'ai.generate.md','api.stripe.customers.md' - Iterate - Each level shows what's available at the next level
Example discovery flow:
// 1. What can I do with API?
'api.md'
// Response shows: fetch, get, post, stripe, github, email, and 40+ services
// 2. What can I do with Stripe?
'api.stripe.md'
// Response shows: customers, subscriptions, payments, invoices, products, prices, etc.
// 3. How do I work with Stripe customers?
'api.stripe.customers.md'
// Response shows: create, update, delete, list, retrieve, search methods
// 4. How exactly do I create a Stripe customer?
'api.stripe.customers.create.md'
// Response shows: complete parameters, examples, error handlingUsage Example
// Step 1: Get documentation for a function you want to use
await client.useTool('do', {
script: 'ai.generateStoryBrand.md',
})
// Response includes:
// - What generateStoryBrand does (creates 7-part StoryBrand framework narrative)
// - Required parameters (business: string | object)
// - Optional parameters (target: string, tone: string, etc.)
// - Return type (StoryBrandNarrative object structure)
// - 3-5 complete usage examples
// - Best practices
// - Related functions
// Step 2: Use the function with confidence
await client.useTool('do', {
script: `
ai.generateStoryBrand({
business: 'E-commerce platform for handmade goods',
target: 'Small business owners and artisans',
tone: 'warm and encouraging'
})
`,
})Best Practices
- Always check docs first - Don't guess at API signatures, request
.mddocumentation - Start at the top - Begin with module-level docs (
ai.md) to understand what's available - Go as deep as needed - Keep drilling down until you find the exact function you need
- Use examples - The documentation includes real examples you can adapt
- Check related functions - Docs often suggest alternative or complementary functions
Important Notes
- This is not exhaustive - The examples above represent a tiny fraction of available documentation paths
- Thousands of paths - Every SDK function, method, property, and parameter supports
.md - Always discoverable - You can always append
.mdto explore what's available - Hierarchical - Documentation works at every level from top modules to deep method chains
- Up-to-date - Documentation reflects the current SDK implementation, not stale docs
Parameters
script Parameter
Execute TypeScript code immediately:
await client.useTool('do', {
script: `
const businesses = await db.list('Business')
return businesses.filter(b => b.industry === 'Technology')
`,
})The script returns the value of the final expression.
module Parameter
Define persistent entities with MDXLD:
await client.useTool('do', {
module: `---
$type: Workflow
$id: /workflows/order-fulfillment
$context: https://platform.do
title: Order Fulfillment
---
# Order Fulfillment Workflow
on($.Order.created, async (order) => {
await send($.Payment.process, { orderId: order.id })
})
on($.Payment.completed, async (payment) => {
await db.update('Order', payment.orderId, { status: 'paid' })
})
`,
})The module parameter accepts:
- YAML frontmatter:
$type,$id,$contextmetadata - Markdown content: Documentation
- Imports/Exports: ES module syntax
- MDX/JSX: UI components
- Code: Event handlers and business logic
Usage Patterns
Query Data
await client.useTool('do', {
script: "await db.list('Business', { where: { status: 'active' } })",
})Create and Send Event
await client.useTool('do', {
script: `
const order = await db.Order.create({
customer: $.Person({ name: 'Alice' }),
total: 99.99
})
await send($.Order.created, { orderId: order.id })
return order
`,
})AI Generation with Human Approval
await client.useTool('do', {
script: `
const content = await ai.generate({
prompt: 'Write a blog post about Business-as-Code',
schema: $.BlogPost
})
const approval = await user.approve({
message: 'Review this blog post before publishing',
data: content
})
if (approval.approved) {
await db.BlogPost.create(content)
await send($.BlogPost.published, { id: content.id })
}
return { content, approved: approval.approved }
`,
})Register Workflow Module
await client.useTool('do', {
module: `---
$type: Workflow
$id: /workflows/customer-onboarding
---
# Customer Onboarding
on($.User.created, async (user) => {
await send($.Email.send, {
to: user.email,
subject: 'Welcome!',
template: 'onboarding'
})
await db.OnboardingTask.create({
userId: user.id,
tasks: ['verify-email', 'complete-profile', 'first-purchase']
})
})
every('0 9 * * *', async () => {
const incomplete = await db.OnboardingTask.list({
where: { completed: false }
})
for (const task of incomplete) {
await send($.Email.reminder, {
userId: task.userId,
tasks: task.tasks
})
}
})
`,
})Best Practices
- Use Documentation First: Request
.mddocumentation before using unfamiliar functions - Start with Scripts: Test operations with
scriptparameter before creating modules - Keep Modules Focused: One workflow/agent per module
- Handle Errors: Wrap operations in try/catch blocks
- Use Human Approval: Request
user.approve()for critical operations - Leverage Types: Use
$.Type()constructors for type safety - Test Patterns: Verify event patterns before deploying handlers
Security
The do tool enforces security constraints:
- Authentication Required: Most operations require valid API key or OAuth token
- Rate Limiting: 10-100 requests/minute based on auth level
- Sandboxed Execution: Scripts run in isolated environment
- Readonly by Default: Write operations require explicit permissions
- Timeout Protection: Scripts timeout after 10 seconds
See Also
- SDK Reference - Complete SDK documentation
- Examples - Real-world usage examples
- Agents - Building autonomous agents
- Authentication - Auth setup and best practices